diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..83868b797f9f58f2102bde6136cf448b444b6fb4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,25 @@ +# Ignore Python cache and compiled files +__pycache__/ +*.pyc +*.pyo +*.pyd + +# Ignore environment and config files +.env +.env_variables.json +.env_shell.json + +# Ignore version control and editor files +.git/ +.vscode/ +.DS_Store + +# Ignore scripts and documentation not needed in image +README.md +local.sh +generate_vector.sh +docs/ + +# Ignore repository/configuration files not needed in image +.github/ +.gitignore diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..2f0344fce670756f2d49717f421e6afbafb6024d --- /dev/null +++ b/.env.example @@ -0,0 +1,49 @@ +# Production Environment Configuration +# No Code Architect Toolkit + +# The name of your application. +APP_NAME=NCAToolkit + +# Debug mode setting. Set to `false` for production environments. +APP_DEBUG=false + +# Your app's domain or subdomain, without the 'http://' or 'https://' prefix. +APP_DOMAIN=example.com + +# Full application URL is automatically configured; no modification required. +APP_URL=https://${APP_DOMAIN} + +# SSL settings +SSL_EMAIL=user@example.com + +# API_KEY +# Purpose: Used for API authentication. +# Requirement: Mandatory. +API_KEY=1993 + +# s3 Compatible Storage Env Vars +# +#S3_ACCESS_KEY=your_access_key +#S3_SECRET_KEY=your_secret_key +#S3_ENDPOINT_URL=https://your-endpoint-url +#S3_REGION=your-region +#S3_BUCKET_NAME=your-bucket-name + + +# Google Cloud Storage Env Variables +# +# GCP_SA_CREDENTIALS +# Purpose: The JSON credentials for the GCP Service Account. +# Requirement: Mandatory if using GCP storage. +#GCP_SA_CREDENTIALS=/path/to/your/gcp/service_account.json + +# GCP_BUCKET_NAME +# Purpose: The name of the GCP storage bucket. +# Requirement: Mandatory if using GCP storage. +#GCP_BUCKET_NAME=your_gcp_bucket_name + +# STORAGE_PATH +# Purpose: The base path for storage operations. +# Default: GCP +# Requirement: Optional. +#STORAGE_PATH=GCP \ No newline at end of file diff --git a/.env.local.minio.n8n.example b/.env.local.minio.n8n.example new file mode 100644 index 0000000000000000000000000000000000000000..03444092ebf14c95ce966738a9eb321bd7878318 --- /dev/null +++ b/.env.local.minio.n8n.example @@ -0,0 +1,29 @@ +# Local Development Environment Configuration +# No Code Architect Toolkit - Local Setup with MinIO + +# App Configuration +APP_NAME=NCAToolkit +APP_DEBUG=true +APP_DOMAIN=localhost:8080 +APP_URL=http://localhost:8080 + +# API Configuration +API_KEY=local-dev-key-123 + +# MinIO S3-Compatible Storage Configuration +S3_ENDPOINT_URL=http://minio:9000 +S3_ACCESS_KEY=minioadmin +S3_SECRET_KEY=minioadmin123 +S3_REGION=us-east-1 +S3_BUCKET_NAME=nca-toolkit-local + +# Optional: Gunicorn Configuration +GUNICORN_WORKERS=2 +GUNICORN_TIMEOUT=300 + +# n8n Configuration +N8N_HOST=localhost +N8N_PORT=5678 +N8N_PROTOCOL=http +WEBHOOK_URL=http://localhost:5678/ +GENERIC_TIMEZONE=UTC \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000000000000000000000000000000000..efc67839875605b9f1b6f8a7d6bff76cf92f6b77 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,70 @@ +name: Bug Report +title: "[Bug]: " +labels: ["bug"] +description: Report broken or incorrect behaviour +body: + - type: markdown + attributes: + value: > + Thanks for taking the time to fill out a bug. + Please note that this form is for bugs only! + - type: textarea + id: what-happened + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is. + validations: + required: true + - type: textarea + attributes: + label: Reproduction Steps + description: > + What you did to make it happen. Include any request payloads, API calls, or specific commands used. + validations: + required: true + - type: textarea + attributes: + label: Expected behavior + description: > + A clear and concise description of what you expected to happen. + validations: + required: false + - type: textarea + attributes: + label: Screenshots and relevant files + description: > + If applicable, add screenshots or relevant files to help explain your problem. + validations: + required: false + - type: dropdown + id: platform + attributes: + label: "Platform" + description: "Select the platform where you encountered this bug" + options: + - "Google Cloud Platform" + - "Digital Ocean" + - "Local" + - "Other" + validations: + required: true + - type: dropdown + id: assign + attributes: + label: "Would you like to work on this issue?" + options: + - "Yes" + - type: checkboxes + attributes: + label: Checklist + description: > + Let's make sure you've properly done due diligence when reporting this issue! + options: + - label: I have searched the open issues for duplicates. + required: true + - label: I have shown the entire traceback, if possible. + required: true + - type: textarea + attributes: + label: Additional Context + description: Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..279a097a60559c8bc89cbf1827e2d996eaf6848e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,7 @@ +contact_links: + - name: Help or Questions? + url: https://www.skool.com/no-code-architects/about?ref=2f302c52a77541efa2dd5e8b27f3f8c9 + about: Get courses, community, support daily calls and more. + +blank_issues_enabled: true +# Allow blank issues for now? \ No newline at end of file diff --git a/.github/workflows/update-build-number.yml b/.github/workflows/update-build-number.yml new file mode 100644 index 0000000000000000000000000000000000000000..d3367cdd289b2aed91359338b5c9c62a9c5ea87e --- /dev/null +++ b/.github/workflows/update-build-number.yml @@ -0,0 +1,37 @@ +name: Update Build Number +on: + push: + branches: + - build +permissions: + contents: write +jobs: + update-build-number: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + token: ${{ secrets.ACTION_BYPASS }} + + - name: Update build number + run: | + if [ ! -f build_number.txt ]; then + echo "0" > build_number.txt + fi + build_number=$(( $(cat build_number.txt) + 1 )) + echo $build_number > build_number.txt + + # Update the version in your code file (e.g., version.py) + echo "BUILD_NUMBER = $build_number" > version.py + + git config user.name github-actions + git config user.email github-actions@github.com + git add build_number.txt version.py + git commit -m "Build $build_number: Bump build number [skip ci]" + git push origin build + + - name: Push changes to testing branch + run: | + git push origin build:testing --force diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bbb0886608dc9bfdc060837142f947e02830fb6a --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.env_variables.json +.DS_Store +.env_shell.json +.env \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..dfab3b524729165a806ca9d4ebfcb0cd9126502f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,158 @@ +# Contributing to No-Code Architects Toolkit + +Thanks for your interest in contributing! ❤️ + +This project exists to help **non-technical creators build smarter systems** — so every contribution should align with these core principles: + +✅ Simple +✅ Useful +✅ Low-maintenance + +This repository is focused on new contributions and feature development. Please ensure all pull requests contain complete, debugged code that is ready for review. We do not accept submissions that require significant cleanup, completion work, or debugging by maintainers. + +> If you like the project but don't know how to code, you can still support us in other ways: +> +> * ⭐ Star the project +> * 📣 Share it on social media +> * 🌲 Refer it to a friend or your community +> * 💸 [Sponsor the project](#) + +If you need help or have questions, check out the GitHub [discussions](https://github.com/stephengpope/no-code-architects-toolkit/discussions) or join the [community](https://www.skool.com/no-code-architects/about?ref=2f302c52a77541efa2dd5e8b27f3f8c9). + +--- + +## Table of Contents + +* [What We Accept](#what-we-accept-) +* [What We Reject](#what-we-reject-) +* [Feature Evaluation Framework](#feature-evaluation-framework) +* [Technical Guidelines](#technical-guidelines) +* [Contribution Types](#contribution-types) +* [Branch Naming Conventions](#branch-naming-conventions) +* [Final Thoughts](#final-thoughts-%EF%B8%8F) + +--- + +## What We Accept ✅ + +* Solves **common no-code challenges** +* **Reduces cost** or replaces paid APIs/tools +* Requires minimal input (has defaults) +* Is understandable by **non-technical users** +* Works out-of-the-box, no setup required +* One-time integrations — **no constant maintenance needed** +* Uses **existing input/output naming conventions** +* Follows our directory and structure conventions + +--- + +## What We Reject ❌ + +* Features built for one person or edge-case +* Inconsistent input/output field names +* Requires polling, retries, or callback logic +* Needs babysitting or breaks frequently +* Lacks error handling or code comments +* Includes unused code, requirements, or bloat +* Adds huge packages that inflate Docker image size +* Leaves us with more work to do + +--- + +## Feature Evaluation Framework + +| Category | Ask This... | ✅ Accept if... | ❌ Reject if... | +| --------------------- | ---------------------------------------------- | ---------------------------------------------- | ------------------------------------------ | +| **Mission Fit** | Does this reduce cost or unify tools? | Replaces APIs, reduces costs or complexity | Adds noise or solves narrow edge cases | +| **Input Familiarity** | Are inputs familiar (`file_url`, `text`, etc)? | Uses standard names/types already in use | Introduces new terms for same ideas | +| **Input Clarity** | Would a non-tech user know what to enter? | Inputs like "Enter URL", "Choose format" | Needs tech explanation or experimentation | +| **Output Usefulness** | Can this plug straight into Make/Zapier? | Returns clean files, text, URLs | Returns raw data or deep nested structures | +| **Reliability** | Will it just work? | API is stable, no retries, consistent behavior | Depends on flaky APIs or fragile setup | +| **Maintenance Cost** | Will we have to maintain this? | One-and-done, doesn't change often | Vendor changes often, breaks silently | +| **Value vs. Effort** | Is it worth it? | High impact, frequently requested | Niche, low ROI | + +--- + +## Technical Guidelines + +> These guidelines help maintain a clean and production-ready project. + +### 🧠 Code Style + +* Use **clear, descriptive names** (e.g., `convertImageToText`, not `imgTxt`) +* Comment your logic if it's not obvious +* Handle errors — don't let code crash silently +* Follow consistent formatting + + +### 🧼 Clean Contributions + +* Don't change files unrelated to your feature +* Don't leave behind unused requirements or code +* Don't introduce huge dependencies (we check image size) +* Use `git status` to review your working tree before you commit +--- + +## Branch Naming Conventions + +All contributions should follow this process: + +1. Fork the [main repository](https://github.com/stephengpope/no-code-architects-toolkit) +2. Clone your fork: + ```bash + git clone https://github.com/YOUR_USERNAME/no-code-architects-toolkit.git + cd no-code-architects-toolkit + ``` +3. Add the upstream repository: + ```bash + git remote add upstream https://github.com/stephengpope/no-code-architects-toolkit.git + ``` +4. Fetch and checkout the upstream build branch: + ```bash + git fetch upstream + git checkout -b your-feature-branch upstream/build + ``` +5. Name your feature branch following these patterns: + * For bug fixes: `fix/descriptive-bug-name` + * For new features: `feature/descriptive-feature-name` + * For documentation: `docs/descriptive-change` + +Example: +```bash +# For a new feature +git fetch upstream +git checkout -b feature/pdf-to-text-converter upstream/build + +# For a bug fix +git fetch upstream +git checkout -b fix/webp-upload-crash upstream/build +``` + +6. After making your changes, push to your fork and create a pull request: + ```bash + git push origin your-feature-branch + ``` + Then visit your fork on GitHub and create a pull request targeting the `build` branch of the main repository. + +--- + +## Contribution Types + +| Type | Good Example | +| ----------- | ---------------------------------------------------------------------- | +| 🐞 Bug Fix | "Fixes crash when uploading WebP files" | +| ⚡ Feature | "Adds endpoint to replace an expensive api" | +| 📚 Docs | "Improves deployment documentation (e.g., how to host on Netlify, AWS, Vercel, etc.)" | + + +--- + +## Final Thoughts 🧘‍♂️ + +* If it's not ready, don't submit it. +* Contributions should be helpful, obvious, and low-maintenance. +* The goal: **make complex tasks simple for no-code users**. + +We're excited to see your contributions! 🎉 + +Let's build something useful, together. \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af1f946fe1916830f422305059dded0ee6ddd89f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,215 @@ +# Base image +FROM python:3.11-slim + +# Install system dependencies, build tools, and libraries +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates \ + wget \ + tar \ + xz-utils \ + fonts-liberation \ + fontconfig \ + build-essential \ + yasm \ + cmake \ + meson \ + ninja-build \ + nasm \ + libssl-dev \ + libvpx-dev \ + libx264-dev \ + libx265-dev \ + libnuma-dev \ + libmp3lame-dev \ + libopus-dev \ + libvorbis-dev \ + libtheora-dev \ + libspeex-dev \ + libfreetype6-dev \ + libfontconfig1-dev \ + libgnutls28-dev \ + libaom-dev \ + libdav1d-dev \ + librav1e-dev \ + libzimg-dev \ + libwebp-dev \ + git \ + pkg-config \ + autoconf \ + automake \ + libtool \ + libfribidi-dev \ + libharfbuzz-dev \ + libnss3 \ + libatk1.0-0 \ + libatk-bridge2.0-0 \ + libcups2 \ + libxcomposite1 \ + libxrandr2 \ + libxdamage1 \ + libgbm1 \ + libasound2 \ + libpangocairo-1.0-0 \ + libpangoft2-1.0-0 \ + libgtk-3-0 \ + && rm -rf /var/lib/apt/lists/* + +# Install SRT from source (latest version using cmake) +RUN git clone https://github.com/Haivision/srt.git && \ + cd srt && \ + mkdir build && cd build && \ + cmake .. && \ + make -j$(nproc) && \ + make install && \ + cd ../.. && rm -rf srt + +# Install SVT-AV1 from source +RUN git clone https://gitlab.com/AOMediaCodec/SVT-AV1.git && \ + cd SVT-AV1 && \ + git checkout v0.9.0 && \ + cd Build && \ + cmake .. && \ + make -j$(nproc) && \ + make install && \ + cd ../.. && rm -rf SVT-AV1 + +# Install libvmaf from source +RUN git clone https://github.com/Netflix/vmaf.git && \ + cd vmaf/libvmaf && \ + meson build --buildtype release && \ + ninja -C build && \ + ninja -C build install && \ + cd ../.. && rm -rf vmaf && \ + ldconfig # Update the dynamic linker cache + +# Manually build and install fdk-aac (since it is not available via apt-get) +RUN git clone https://github.com/mstorsjo/fdk-aac && \ + cd fdk-aac && \ + autoreconf -fiv && \ + ./configure && \ + make -j$(nproc) && \ + make install && \ + cd .. && rm -rf fdk-aac + +# Install libunibreak (required for ASS_FEATURE_WRAP_UNICODE) +RUN git clone https://github.com/adah1972/libunibreak.git && \ + cd libunibreak && \ + ./autogen.sh && \ + ./configure && \ + make -j$(nproc) && \ + make install && \ + ldconfig && \ + cd .. && rm -rf libunibreak + +# Build and install libass with libunibreak support and ASS_FEATURE_WRAP_UNICODE enabled +RUN git clone https://github.com/libass/libass.git && \ + cd libass && \ + autoreconf -i && \ + ./configure --enable-libunibreak || { cat config.log; exit 1; } && \ + mkdir -p /app && echo "Config log located at: /app/config.log" && cp config.log /app/config.log && \ + make -j$(nproc) || { echo "Libass build failed"; exit 1; } && \ + make install && \ + ldconfig && \ + cd .. && rm -rf libass + +# Build and install FFmpeg with all required features +RUN git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg && \ + cd ffmpeg && \ + git checkout n8.0 && \ + PKG_CONFIG_PATH="/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/local/lib/pkgconfig" \ + CFLAGS="-I/usr/include/freetype2" \ + LDFLAGS="-L/usr/lib/x86_64-linux-gnu" \ + ./configure --prefix=/usr/local \ + --enable-gpl \ + --enable-pthreads \ + --enable-neon \ + --enable-libaom \ + --enable-libdav1d \ + --enable-librav1e \ + --enable-libsvtav1 \ + --enable-libvmaf \ + --enable-libzimg \ + --enable-libx264 \ + --enable-libx265 \ + --enable-libvpx \ + --enable-libwebp \ + --enable-libmp3lame \ + --enable-libopus \ + --enable-libvorbis \ + --enable-libtheora \ + --enable-libspeex \ + --enable-libass \ + --enable-libfreetype \ + --enable-libharfbuzz \ + --enable-fontconfig \ + --enable-libsrt \ + --enable-filter=drawtext \ + --extra-cflags="-I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include" \ + --extra-ldflags="-L/usr/lib/x86_64-linux-gnu -lfreetype -lfontconfig" \ + --enable-gnutls \ + && make -j$(nproc) && \ + make install && \ + cd .. && rm -rf ffmpeg + +# Add /usr/local/bin to PATH (if not already included) +ENV PATH="/usr/local/bin:${PATH}" + +# Copy fonts into the custom fonts directory +# COPY ./fonts /usr/share/fonts/custom + +# Rebuild the font cache so that fontconfig can see the custom fonts +# RUN fc-cache -f -v + +# Set work directory +WORKDIR /app + +# Set environment variable for Whisper cache +ENV WHISPER_CACHE_DIR="/app/whisper_cache" + +# Create cache directory (no need for chown here yet) +RUN mkdir -p ${WHISPER_CACHE_DIR} + +# Copy the requirements file first to optimize caching +COPY requirements.txt . + +# Install Python dependencies, upgrade pip +RUN pip install --no-cache-dir --upgrade pip && \ + pip install --no-cache-dir -r requirements.txt && \ + pip install playwright && \ + pip install jsonschema + +# Create the appuser +RUN useradd -m appuser + +# Give appuser ownership of the /app directory (including whisper_cache) +RUN chown appuser:appuser /app + +# Important: Switch to the appuser before downloading the model +USER appuser + +RUN python -c "import os; print(os.environ.get('WHISPER_CACHE_DIR')); import whisper; whisper.load_model('base')" + +# Install Playwright Chromium browser as appuser +RUN playwright install chromium + +# Copy the rest of the application code +COPY . . + + +# Expose the port the app runs on +EXPOSE 8080 + +# Set environment variables +ENV PYTHONUNBUFFERED=1 + +RUN echo '#!/bin/bash\n\ +gunicorn --bind 0.0.0.0:8080 \ + --workers ${GUNICORN_WORKERS:-2} \ + --timeout ${GUNICORN_TIMEOUT:-300} \ + --worker-class sync \ + --keep-alive 80 \ + app:app' > /app/run_gunicorn.sh && \ + chmod +x /app/run_gunicorn.sh + +# Run the shell script +CMD ["/app/run_gunicorn.sh"] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..48d64c3a34edf3f232ff554e80e658b73d482e8b --- /dev/null +++ b/LICENSE @@ -0,0 +1,340 @@ +Copyright (c) 2025 Stephen G. Pope + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Moe Ghoul, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..441c0fac13bad54d3366f6ac6ed8dbdcdf2b52c2 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +--- +title: toolkit +emoji: 🐨 +colorFrom: gray +colorTo: purple +sdk: docker +pinned: false +app_port: 8080 +--- \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..49abb5030cec9f4036fe0bd2710a59124fdd9bec --- /dev/null +++ b/app.py @@ -0,0 +1,204 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Flask, request +from queue import Queue +from services.webhook import send_webhook +import threading +import uuid +import os +import time +from version import BUILD_NUMBER # Import the BUILD_NUMBER +from app_utils import log_job_status, discover_and_register_blueprints # Import the discover_and_register_blueprints function + +MAX_QUEUE_LENGTH = int(os.environ.get('MAX_QUEUE_LENGTH', 0)) + +def create_app(): + app = Flask(__name__) + + # Create a queue to hold tasks + task_queue = Queue() + queue_id = id(task_queue) # Generate a single queue_id for this worker + + # Function to process tasks from the queue + def process_queue(): + while True: + job_id, data, task_func, queue_start_time = task_queue.get() + queue_time = time.time() - queue_start_time + run_start_time = time.time() + pid = os.getpid() # Get the PID of the actual processing thread + + # Log job status as running + log_job_status(job_id, { + "job_status": "running", + "job_id": job_id, + "queue_id": queue_id, + "process_id": pid, + "response": None + }) + + response = task_func() + run_time = time.time() - run_start_time + total_time = time.time() - queue_start_time + + response_data = { + "endpoint": response[1], + "code": response[2], + "id": data.get("id"), + "job_id": job_id, + "response": response[0] if response[2] == 200 else None, + "message": "success" if response[2] == 200 else response[0], + "pid": pid, + "queue_id": queue_id, + "run_time": round(run_time, 3), + "queue_time": round(queue_time, 3), + "total_time": round(total_time, 3), + "queue_length": task_queue.qsize(), + "build_number": BUILD_NUMBER # Add build number to response + } + + # Log job status as done + log_job_status(job_id, { + "job_status": "done", + "job_id": job_id, + "queue_id": queue_id, + "process_id": pid, + "response": response_data + }) + + # Only send webhook if webhook_url has an actual value (not an empty string) + if data.get("webhook_url") and data.get("webhook_url") != "": + send_webhook(data.get("webhook_url"), response_data) + + task_queue.task_done() + + # Start the queue processing in a separate thread + threading.Thread(target=process_queue, daemon=True).start() + + # Decorator to add tasks to the queue or bypass it + def queue_task(bypass_queue=False): + def decorator(f): + def wrapper(*args, **kwargs): + job_id = str(uuid.uuid4()) + data = request.json if request.is_json else {} + pid = os.getpid() # Get PID for non-queued tasks + start_time = time.time() + + if bypass_queue or 'webhook_url' not in data: + + # Log job status as running immediately (bypassing queue) + log_job_status(job_id, { + "job_status": "running", + "job_id": job_id, + "queue_id": queue_id, + "process_id": pid, + "response": None + }) + + response = f(job_id=job_id, data=data, *args, **kwargs) + run_time = time.time() - start_time + + response_obj = { + "code": response[2], + "id": data.get("id"), + "job_id": job_id, + "response": response[0] if response[2] == 200 else None, + "message": "success" if response[2] == 200 else response[0], + "run_time": round(run_time, 3), + "queue_time": 0, + "total_time": round(run_time, 3), + "pid": pid, + "queue_id": queue_id, + "queue_length": task_queue.qsize(), + "build_number": BUILD_NUMBER # Add build number to response + } + + # Log job status as done + log_job_status(job_id, { + "job_status": "done", + "job_id": job_id, + "queue_id": queue_id, + "process_id": pid, + "response": response_obj + }) + + return response_obj, response[2] + else: + if MAX_QUEUE_LENGTH > 0 and task_queue.qsize() >= MAX_QUEUE_LENGTH: + error_response = { + "code": 429, + "id": data.get("id"), + "job_id": job_id, + "message": f"MAX_QUEUE_LENGTH ({MAX_QUEUE_LENGTH}) reached", + "pid": pid, + "queue_id": queue_id, + "queue_length": task_queue.qsize(), + "build_number": BUILD_NUMBER # Add build number to response + } + + # Log the queue overflow error + log_job_status(job_id, { + "job_status": "done", + "job_id": job_id, + "queue_id": queue_id, + "process_id": pid, + "response": error_response + }) + + return error_response, 429 + + # Log job status as queued + log_job_status(job_id, { + "job_status": "queued", + "job_id": job_id, + "queue_id": queue_id, + "process_id": pid, + "response": None + }) + + task_queue.put((job_id, data, lambda: f(job_id=job_id, data=data, *args, **kwargs), start_time)) + + return { + "code": 202, + "id": data.get("id"), + "job_id": job_id, + "message": "processing", + "pid": pid, + "queue_id": queue_id, + "max_queue_length": MAX_QUEUE_LENGTH if MAX_QUEUE_LENGTH > 0 else "unlimited", + "queue_length": task_queue.qsize(), + "build_number": BUILD_NUMBER # Add build number to response + }, 202 + return wrapper + return decorator + + app.queue_task = queue_task + + # Register special route for Next.js root asset paths first + from routes.v1.media.feedback import create_root_next_routes + create_root_next_routes(app) + + # Use the discover_and_register_blueprints function to register all blueprints + discover_and_register_blueprints(app) + + return app + +app = create_app() + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=8080) \ No newline at end of file diff --git a/app_utils.py b/app_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a34a6463f8ec2f2bd93f4a24ca1fa893dd727933 --- /dev/null +++ b/app_utils.py @@ -0,0 +1,136 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import request, jsonify, current_app +from functools import wraps +import jsonschema +import os +import json +import time +from config import LOCAL_STORAGE_PATH + +def validate_payload(schema): + def decorator(f): + @wraps(f) + def decorated_function(*args, **kwargs): + if not request.json: + return jsonify({"message": "Missing JSON in request"}), 400 + try: + jsonschema.validate(instance=request.json, schema=schema) + except jsonschema.exceptions.ValidationError as validation_error: + return jsonify({"message": f"Invalid payload: {validation_error.message}"}), 400 + + return f(*args, **kwargs) + return decorated_function + return decorator + +def log_job_status(job_id, data): + """ + Log job status to a file in the STORAGE_PATH/jobs folder + + Args: + job_id (str): The unique job ID + data (dict): Data to write to the log file + """ + jobs_dir = os.path.join(LOCAL_STORAGE_PATH, 'jobs') + + # Create jobs directory if it doesn't exist + if not os.path.exists(jobs_dir): + os.makedirs(jobs_dir, exist_ok=True) + + # Create or update the job log file + job_file = os.path.join(jobs_dir, f"{job_id}.json") + + # Write data directly to file + with open(job_file, 'w') as f: + json.dump(data, f, indent=2) + +def queue_task_wrapper(bypass_queue=False): + def decorator(f): + def wrapper(*args, **kwargs): + return current_app.queue_task(bypass_queue=bypass_queue)(f)(*args, **kwargs) + return wrapper + return decorator + +def discover_and_register_blueprints(app, base_dir='routes'): + """ + Dynamically discovers and registers all Flask blueprints in the routes directory. + Recursively searches all subdirectories for Python modules containing Blueprint instances. + + Args: + app (Flask): The Flask application instance + base_dir (str): Base directory to start searching for blueprints (default: 'routes') + """ + import importlib + import pkgutil + import inspect + import sys + import os + from flask import Blueprint + import logging + import glob + + logger = logging.getLogger(__name__) + logger.info(f"Discovering blueprints in {base_dir}") + + # Add the current working directory to sys.path if it's not already there + cwd = os.getcwd() + if cwd not in sys.path: + sys.path.insert(0, cwd) + + # Get the absolute path to the base directory + if not os.path.isabs(base_dir): + base_dir = os.path.join(cwd, base_dir) + + registered_blueprints = set() + + # Find all Python files in the routes directory, including subdirectories + python_files = glob.glob(os.path.join(base_dir, '**', '*.py'), recursive=True) + logger.info(f"Found {len(python_files)} Python files in {base_dir}") + + for file_path in python_files: + try: + # Convert file path to import path + rel_path = os.path.relpath(file_path, cwd) + # Remove .py extension + module_path = os.path.splitext(rel_path)[0] + # Convert path separators to dots for import + module_path = module_path.replace(os.path.sep, '.') + + # Skip __init__.py files + if module_path.endswith('__init__'): + continue + + #logger.info(f"Attempting to import module: {module_path}") + + # Import the module + module = importlib.import_module(module_path) + + # Find all Blueprint instances in the module + for name, obj in inspect.getmembers(module): + if isinstance(obj, Blueprint) and obj not in registered_blueprints: + pid = os.getpid() + logger.info(f"PID {pid} Registering: {module_path}") + app.register_blueprint(obj) + registered_blueprints.add(obj) + + except Exception as e: + logger.error(f"Error importing module {module_path}: {str(e)}") + + logger.info(f"PID {pid} Registered {len(registered_blueprints)} blueprints") + return registered_blueprints \ No newline at end of file diff --git a/build_number.txt b/build_number.txt new file mode 100644 index 0000000000000000000000000000000000000000..08839f6bb296e888d311d8ea2f35f7ff82dd3f2d --- /dev/null +++ b/build_number.txt @@ -0,0 +1 @@ +200 diff --git a/config.py b/config.py new file mode 100644 index 0000000000000000000000000000000000000000..2b4e9826b54d0da41879ab9aabbdc9009a527b48 --- /dev/null +++ b/config.py @@ -0,0 +1,45 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import logging + +# Retrieve the API key from environment variables +API_KEY = os.environ.get('API_KEY') +if not API_KEY: + raise ValueError("API_KEY environment variable is not set") + +# Storage path setting +LOCAL_STORAGE_PATH = os.environ.get('LOCAL_STORAGE_PATH', '/tmp') + +# GCP environment variables +GCP_SA_CREDENTIALS = os.environ.get('GCP_SA_CREDENTIALS', '') +GCP_BUCKET_NAME = os.environ.get('GCP_BUCKET_NAME', '') + +def validate_env_vars(provider): + + """ Validate the necessary environment variables for the selected storage provider """ + required_vars = { + 'GCP': ['GCP_BUCKET_NAME', 'GCP_SA_CREDENTIALS'], + 'S3': ['S3_ENDPOINT_URL', 'S3_ACCESS_KEY', 'S3_SECRET_KEY', 'S3_BUCKET_NAME', 'S3_REGION'], + 'S3_DO': ['S3_ENDPOINT_URL', 'S3_ACCESS_KEY', 'S3_SECRET_KEY'] + } + + missing_vars = [var for var in required_vars[provider] if not os.getenv(var)] + if missing_vars: + raise ValueError(f"Missing environment variables for {provider} storage: {', '.join(missing_vars)}") diff --git a/docker-compose.local.minio.n8n.md b/docker-compose.local.minio.n8n.md new file mode 100644 index 0000000000000000000000000000000000000000..81162680fb9496bf23895f856427feeeab379d47 --- /dev/null +++ b/docker-compose.local.minio.n8n.md @@ -0,0 +1,317 @@ +# Local Development with MinIO and n8n + +This setup provides a complete local development environment for the No Code Architect Toolkit with integrated MinIO S3-compatible storage and n8n workflow automation. + +## What's Included + +- **NCA Toolkit**: Built locally from source (no pre-built image required) +- **MinIO**: S3-compatible object storage with web console for local file management +- **n8n**: Workflow automation platform for connecting and orchestrating services +- **Custom Network**: All services communicate through a dedicated Docker network +- **Persistent Storage**: Data persists between container restarts + +## Prerequisites + +- Docker and Docker Compose installed +- Git (to clone the repository) +- At least 2GB available RAM +- At least 5GB available disk space + +--- + +## Quick Start + +### 1. Prepare Environment Configuration + +Copy the example environment file and customize it: + +```bash +cp .env.local.minio.n8n.example .env.local.minio.n8n +``` + +Edit `.env.local.minio.n8n` with your preferred settings. The defaults work for most local development scenarios. + +### 2. Start the Development Environment + +```bash +docker compose -f docker-compose.local.minio.n8n.yml up -d +``` + +### 3. Access the Applications + +Once all services are running, you can access: + +- **NCA Toolkit API**: http://localhost:8080 +- **n8n Workflow Interface**: http://localhost:5678 +- **MinIO Console**: http://localhost:9001 + - Username: `minioadmin` + - Password: `minioadmin123` + +### 4. Verify Setup + +Test the NCA Toolkit API: + +```bash +curl -H "x-api-key: local-dev-key-123" http://localhost:8080/v1/toolkit/test +``` + +--- + +## Environment Configuration + +The `.env.local.minio.n8n` file contains all necessary configuration: + +### Application Settings +```env +APP_NAME=NCAToolkit +APP_DEBUG=true +APP_DOMAIN=localhost:8080 +APP_URL=http://localhost:8080 +API_KEY=local-dev-key-123 +``` + +### MinIO S3 Storage Settings +```env +S3_ENDPOINT_URL=http://minio:9000 +S3_ACCESS_KEY=minioadmin +S3_SECRET_KEY=minioadmin123 +S3_REGION=us-east-1 +S3_BUCKET_NAME=nca-toolkit-local +``` + +### n8n Configuration +```env +N8N_HOST=localhost +N8N_PORT=5678 +N8N_PROTOCOL=http +WEBHOOK_URL=http://localhost:5678/ +``` + +--- + +## Service Details + +### NCA Toolkit (Port 8080) +- Built from local Dockerfile +- Connects to MinIO for file storage +- API accessible at http://localhost:8080 +- Uses local development API key: `local-dev-key-123` + +### MinIO (Ports 9000, 9001) +- **API Endpoint**: http://localhost:9000 (S3-compatible API) +- **Web Console**: http://localhost:9001 +- **Bucket**: `nca-toolkit-local` (auto-created and configured as public) +- **Credentials**: minioadmin / minioadmin123 + +### n8n (Port 5678) +- **Web Interface**: http://localhost:5678 +- **Webhook URL**: http://localhost:5678/ +- **File Sharing**: `./local-files` directory mounted for easy file access +- Can connect to both NCA Toolkit and MinIO services + +--- + +## Development Workflow + +### Making Code Changes + +1. **Edit source code** in your local directory +2. **Rebuild the NCA Toolkit container**: + ```bash + docker compose -f docker-compose.local.minio.n8n.yml build ncat + docker compose -f docker-compose.local.minio.n8n.yml up -d + ``` + +### Viewing Logs + +```bash +# All services +docker compose -f docker-compose.local.minio.n8n.yml logs -f + +# Specific service +docker compose -f docker-compose.local.minio.n8n.yml logs -f ncat +docker compose -f docker-compose.local.minio.n8n.yml logs -f minio +docker compose -f docker-compose.local.minio.n8n.yml logs -f n8n +``` + +### Managing Storage + +#### Access MinIO Console +1. Open http://localhost:9001 +2. Login with `minioadmin` / `minioadmin123` +3. Browse the `nca-toolkit-local` bucket +4. Upload/download files as needed + +#### Reset MinIO Data +```bash +docker compose -f docker-compose.local.minio.n8n.yml down +docker volume rm no-code-architects-toolkit_minio_data +docker compose -f docker-compose.local.minio.n8n.yml up -d +``` + +--- + +## Service Communication + +All services communicate through the `nca-network` Docker network: + +- **n8n → NCA Toolkit**: `http://ncat:8080` +- **n8n → MinIO**: `http://minio:9000` (S3 API) +- **NCA Toolkit → MinIO**: `http://minio:9000` (internal network) + +### n8n Integration with NCA Toolkit + +#### Quick Test Setup + +1. **Access n8n**: Open http://localhost:5678 +2. **Create a new workflow** +3. **Add an HTTP Request node** with these settings: + - **Method**: GET + - **URL**: `http://ncat:8080/v1/toolkit/test` + - **Headers**: + - Key: `x-api-key` + - Value: `local-dev-key-123` + +#### Example: Testing the Toolkit Connection + +**HTTP Request Node Configuration:** +```json +{ + "method": "GET", + "url": "http://ncat:8080/v1/toolkit/test", + "headers": { + "x-api-key": "local-dev-key-123" + } +} +``` + +**Expected Response:** +```json +{ + "message": "NCA Toolkit is working correctly", + "status": "success" +} +``` + +#### Example: Media Processing Workflow + +**HTTP Request Node for Media Transcription:** +```json +{ + "method": "POST", + "url": "http://ncat:8080/v1/media/transcribe", + "headers": { + "x-api-key": "local-dev-key-123", + "Content-Type": "application/json" + }, + "body": { + "media_url": "https://example.com/audio.mp3", + "language": "en", + "response_format": "json" + } +} +``` + +#### All Available NCA Toolkit Endpoints + +Use the base URL `http://ncat:8080` with any of the API endpoints documented in the main README: + +- `http://ncat:8080/v1/toolkit/test` - Test connection +- `http://ncat:8080/v1/media/transcribe` - Transcribe audio/video +- `http://ncat:8080/v1/video/caption` - Add captions to videos +- `http://ncat:8080/v1/image/screenshot/webpage` - Screenshot web pages +- And all other endpoints listed in the main documentation + +#### Tips for n8n Integration + +1. **Always use the internal network URL**: `http://ncat:8080` (not `http://localhost:8080`) +2. **Include the API key header**: `x-api-key: local-dev-key-123` +3. **For file uploads**: Use the MinIO integration or webhook URLs for large files +4. **Error handling**: Add error handling nodes to manage API timeouts or failures + +--- + +## Data Persistence + +The following data persists between container restarts: + +- **Application Storage**: `storage` volume (`/app/storage`) +- **Application Logs**: `logs` volume (`/app/logs`) +- **MinIO Data**: `minio_data` volume +- **n8n Workflows**: `n8n_data` volume (`/home/node/.n8n`) +- **Shared Files**: `./local-files` directory + +--- + +## Troubleshooting + +### Services Won't Start +```bash +# Check service status +docker compose -f docker-compose.local.minio.n8n.yml ps + +# View error logs +docker compose -f docker-compose.local.minio.n8n.yml logs +``` + +### Port Conflicts +If ports 8080, 5678, 9000, or 9001 are already in use, modify the port mappings in `docker-compose.local.minio.n8n.yml`: + +```yaml +ports: + - "8081:8080" # Change 8080 to 8081 +``` + +### MinIO Bucket Issues +The `minio-init` service automatically creates and configures the bucket. If issues occur: + +```bash +# Restart the init service +docker compose -f docker-compose.local.minio.n8n.yml restart minio-init + +# Check init logs +docker compose -f docker-compose.local.minio.n8n.yml logs minio-init +``` + +### API Authentication Errors +Ensure you're using the correct API key from `.env.local.minio.n8n`: +- Default: `local-dev-key-123` +- Header: `x-api-key: local-dev-key-123` + +--- + +## Stopping the Environment + +```bash +# Stop all services +docker compose -f docker-compose.local.minio.n8n.yml down + +# Stop and remove volumes (deletes all data) +docker compose -f docker-compose.local.minio.n8n.yml down -v +``` + +--- + +## Architecture Overview + +``` +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ NCA Toolkit │ │ n8n │ │ MinIO │ +│ localhost:8080│◄──►│ localhost:5678│◄──►│ localhost:9000 │ +│ │ │ │ │ (S3 API) │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ + │ │ │ + └───────────────────────┼───────────────────────┘ + │ + ┌─────────────────┐ + │ MinIO Console │ + │ localhost:9001 │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ nca-network │ + │ (Docker Bridge) │ + └─────────────────┘ +``` + +This setup provides a complete local development environment with file storage, workflow automation, and the NCA Toolkit API all working together seamlessly. \ No newline at end of file diff --git a/docker-compose.local.minio.n8n.yml b/docker-compose.local.minio.n8n.yml new file mode 100644 index 0000000000000000000000000000000000000000..e1ba65c66b0e1e35e28a8f0a2021662a64dfa2a0 --- /dev/null +++ b/docker-compose.local.minio.n8n.yml @@ -0,0 +1,79 @@ +services: + ncat: + build: . + env_file: + - .env.local.minio.n8n + ports: + - "8080:8080" + volumes: + - storage:/app/storage + - logs:/app/logs + restart: unless-stopped + depends_on: + - minio + - minio-init + networks: + - nca-network + + minio: + image: minio/minio:latest + command: server /data --console-address ":9001" + ports: + - "9000:9000" + - "9001:9001" + environment: + MINIO_ROOT_USER: minioadmin + MINIO_ROOT_PASSWORD: minioadmin123 + volumes: + - minio_data:/data + restart: unless-stopped + networks: + - nca-network + + minio-init: + image: minio/mc:latest + depends_on: + - minio + entrypoint: > + /bin/sh -c " + sleep 5; + /usr/bin/mc alias set myminio http://minio:9000 minioadmin minioadmin123; + /usr/bin/mc mb myminio/nca-toolkit-local --ignore-existing; + /usr/bin/mc anonymous set public myminio/nca-toolkit-local; + echo 'MinIO bucket nca-toolkit-local created and configured as public'; + " + networks: + - nca-network + + n8n: + image: docker.n8n.io/n8nio/n8n + restart: unless-stopped + ports: + - "5678:5678" + environment: + - N8N_HOST=localhost + - N8N_PORT=5678 + - N8N_PROTOCOL=http + - NODE_ENV=production + - WEBHOOK_URL=http://localhost:5678/ + - GENERIC_TIMEZONE=UTC + - N8N_SECURE_COOKIE=false + volumes: + - n8n_data:/home/node/.n8n + - ./local-files:/files + networks: + - nca-network + +volumes: + storage: + driver: local + logs: + driver: local + minio_data: + driver: local + n8n_data: + driver: local + +networks: + nca-network: + driver: bridge \ No newline at end of file diff --git a/docker-compose.md b/docker-compose.md new file mode 100644 index 0000000000000000000000000000000000000000..0c76864814f2c897a7b76cc5f1520b9b1ddf07b6 --- /dev/null +++ b/docker-compose.md @@ -0,0 +1,200 @@ +# Install No Code Architect Toolkit with Docker + +Installation of No Code Architect Toolkit with Docker offers the following advantages: +- Install No Code Architect Toolkit in a clean environment. +- Simplify the setup process. +- Avoid compatibility issues across different operating systems with Docker's consistent environment. + +> **Info** +> If your domain/subdomain is already pointed to the server, start at step 2. +> If you have already installed Docker and Docker-Compose, start at step 3. + +--- + +## 1. DNS Setup + +Point your domain/subdomain to the server. Add an A record to route the domain/subdomain accordingly: + +- **Type**: A +- **Name**: The desired domain/subdomain +- **IP Address**: `` + +--- + +## 2. Install Docker + +This can vary depending on the Linux distribution used. Below are instructions for Ubuntu: + +### Set up Docker's APT Repository + +```bash +# Add Docker's official GPG key: +sudo apt-get update +sudo apt-get install ca-certificates curl +sudo install -m 0755 -d /etc/apt/keyrings +sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc +sudo chmod a+r /etc/apt/keyrings/docker.asc + +# Add the repository to APT sources: +echo \ +"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \ +$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \ +sudo tee /etc/apt/sources.list.d/docker.list > /dev/null +sudo apt-get update +``` + +### Install the Docker Packages + +```bash +sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin +``` + +--- + +## 3. Create Docker Compose File + +Create a `docker-compose.yml` file and paste the following configuration: + +### With SSL Support +Enables SSL/TLS for secure, encrypted communications. Ideal for those wanting a hands-off approach to SSL setup. + +```yaml +services: + traefik: + image: "traefik" + restart: unless-stopped + command: + - "--api=true" + - "--api.insecure=true" + - "--providers.docker=true" + - "--providers.docker.exposedbydefault=false" + - "--entrypoints.web.address=:80" + - "--entrypoints.web.http.redirections.entryPoint.to=websecure" + - "--entrypoints.web.http.redirections.entrypoint.scheme=https" + - "--entrypoints.websecure.address=:443" + - "--certificatesresolvers.mytlschallenge.acme.tlschallenge=true" + - "--certificatesresolvers.mytlschallenge.acme.email=${SSL_EMAIL}" + - "--certificatesresolvers.mytlschallenge.acme.storage=/letsencrypt/acme.json" + ports: + - "80:80" + - "443:443" + volumes: + - traefik_data:/letsencrypt + - /var/run/docker.sock:/var/run/docker.sock:ro + ncat: + image: stephengpope/no-code-architects-toolkit:latest + env_file: + - .env + labels: + - traefik.enable=true + - traefik.http.routers.ncat.rule=Host(`${APP_DOMAIN}`) + - traefik.http.routers.ncat.tls=true + - traefik.http.routers.ncat.entrypoints=web,websecure + - traefik.http.routers.ncat.tls.certresolver=mytlschallenge + volumes: + - storage:/var/www/html/storage/app + - logs:/var/www/html/storage/logs + restart: unless-stopped + +volumes: + traefik_data: + driver: local + storage: + driver: local + logs: + driver: local +``` + +--- + +## 4. Create `.env` File + +Create an `.env` file and configure it accordingly: + +```env +# The name of your application. +APP_NAME=NCAToolkit + +# Debug mode setting. Set to `false` for production environments. +APP_DEBUG=false + +# Your app's domain or subdomain, without the 'http://' or 'https://' prefix. +APP_DOMAIN=example.com + +# Full application URL is automatically configured; no modification required. +APP_URL=https://${APP_DOMAIN} + +# SSL settings +SSL_EMAIL=user@example.com + +# API_KEY +# Purpose: Used for API authentication. +# Requirement: Mandatory. +API_KEY=your_api_key_here + +# s3 Compatible Storage Env Vars +# +#S3_ACCESS_KEY=your_access_key +#S3_SECRET_KEY=your_secret_key +#S3_ENDPOINT_URL=https://your-endpoint-url +#S3_REGION=your-region +#S3_BUCKET_NAME=your-bucket-name + + +# Google Cloud Storage Env Variables +# +# GCP_SA_CREDENTIALS +# Purpose: The JSON credentials for the GCP Service Account. +# Requirement: Mandatory if using GCP storage. +#GCP_SA_CREDENTIALS=/path/to/your/gcp/service_account.json + +# GCP_BUCKET_NAME +# Purpose: The name of the GCP storage bucket. +# Requirement: Mandatory if using GCP storage. +#GCP_BUCKET_NAME=your_gcp_bucket_name + +# STORAGE_PATH +# Purpose: The base path for storage operations. +# Default: GCP +# Requirement: Optional. +#STORAGE_PATH=GCP + +``` + +--- + +## 5. Start Docker Compose + +Start No Code Architect Toolkit using the following command: + +```bash +docker compose up -d +``` + +To view logs in real time: + +```bash +docker compose logs -f +``` + +To stop the containers: + +```bash +docker compose stop +``` + +To restart and reload env vars + +# First update your .env file with the correct values +# Then run: + +```bash +docker compose up -d --force-recreate ncat +``` + +--- + +## 6. Done + +No Code Architect Toolkit is now accessible through the specified APP_URL. For example: +[https://example.com](https://example.com) diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0417b9aab09d9b691512950dbc7544893f15c4c7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,44 @@ +services: + traefik: + image: "traefik" + restart: unless-stopped + command: + - "--api=true" + - "--api.insecure=true" + - "--providers.docker=true" + - "--providers.docker.exposedbydefault=false" + - "--entrypoints.web.address=:80" + - "--entrypoints.web.http.redirections.entryPoint.to=websecure" + - "--entrypoints.web.http.redirections.entrypoint.scheme=https" + - "--entrypoints.websecure.address=:443" + - "--certificatesresolvers.mytlschallenge.acme.tlschallenge=true" + - "--certificatesresolvers.mytlschallenge.acme.email=${SSL_EMAIL}" + - "--certificatesresolvers.mytlschallenge.acme.storage=/letsencrypt/acme.json" + ports: + - "80:80" + - "443:443" + volumes: + - traefik_data:/letsencrypt + - /var/run/docker.sock:/var/run/docker.sock:ro + ncat: + image: stephengpope/no-code-architects-toolkit:latest + env_file: + - .env + labels: + - traefik.enable=true + - traefik.http.routers.ncat.rule=Host(`${APP_DOMAIN}`) + - traefik.http.routers.ncat.tls=true + - traefik.http.routers.ncat.entrypoints=web,websecure + - traefik.http.routers.ncat.tls.certresolver=mytlschallenge + volumes: + - storage:/var/www/html/storage/app + - logs:/var/www/html/storage/logs + restart: unless-stopped + +volumes: + traefik_data: + driver: local + storage: + driver: local + logs: + driver: local \ No newline at end of file diff --git a/docs/adding_routes.md b/docs/adding_routes.md new file mode 100644 index 0000000000000000000000000000000000000000..21958cfeed2126a1fab9be0f0a96bcda73280d1d --- /dev/null +++ b/docs/adding_routes.md @@ -0,0 +1,81 @@ +# Adding New Routes + +This document explains how to add new routes to the application using the dynamic route registration system. + +## Overview + +The application now uses a dynamic route registration system that automatically discovers and registers all Flask blueprints in the `routes` directory. This means you no longer need to manually import and register blueprints in `app.py`. + +## How to Add a New Route + +1. **Create a new route file** + + Create a new Python file in the appropriate location in the `routes` directory. For a v1 API endpoint, you would typically place it in a subdirectory under `routes/v1/` based on the functionality. + + For example: + ``` + routes/v1/email/send_email.py + ``` + +2. **Define your Blueprint** + + In your route file, define a Flask Blueprint with a unique name. Make sure to follow the naming convention: + + ```python + # routes/v1/email/send_email.py + from flask import Blueprint, request + from services.authentication import authenticate + from app_utils import queue_task_wrapper + + v1_email_send_bp = Blueprint('v1_email_send', __name__) + + @v1_email_send_bp.route('/v1/email/send', methods=['POST']) + @authenticate + @queue_task_wrapper(bypass_queue=False) + def send_email(job_id, data): + """ + Send an email + + Args: + job_id (str): Job ID assigned by queue_task_wrapper + data (dict): Request data containing email details + + Returns: + Tuple of (response_data, endpoint_string, status_code) + """ + # Your implementation here + endpoint = "/v1/email/send" + + # Return response + return {"message": "Email sent"}, endpoint, 200 + ``` + +3. **That's it!** + + No need to modify `app.py`. The blueprint will be automatically discovered and registered when the application starts. + +## Naming Conventions + +When creating new routes, please follow these naming conventions: + +1. **Blueprint names**: Use the format `{version}_{category}_{action}_bp` + - Example: `v1_email_send_bp` for sending emails + +2. **Route paths**: Use the format `/{version}/{category}/{action}` + - Example: `/v1/email/send` + +3. **File structure**: Place files in directories that match the route structure + - Example: `routes/v1/email/send_email.py` + +## Testing Your Route + +After adding your route, restart the application and your new endpoint should be available immediately. + +## Troubleshooting + +If your route isn't being registered: + +1. Check logs for any import errors +2. Ensure your blueprint variable is defined at the module level +3. Verify the blueprint name follows the naming convention +4. Make sure your Python file is in the correct directory under `routes/` \ No newline at end of file diff --git a/docs/audio/concatenate.md b/docs/audio/concatenate.md new file mode 100644 index 0000000000000000000000000000000000000000..17d953156c1cd09b9932127d76a5726a2bb86b9f --- /dev/null +++ b/docs/audio/concatenate.md @@ -0,0 +1,207 @@ +# Audio Concatenation API Endpoint Documentation + +## Overview + +The `/v1/audio/concatenate` endpoint provides functionality to combine multiple audio files into a single audio file. This endpoint is part of the v1 API structure and is registered in the main application through the `v1_audio_concatenate_bp` Blueprint. It leverages the application's queuing system to handle asynchronous processing, which is particularly useful for potentially time-consuming audio processing operations. + +## Endpoint + +- **URL**: `/v1/audio/concatenate` +- **Method**: `POST` + +## Request + +### Headers + +- `x-api-key`: Required. Your API authentication key. + +### Body Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `audio_urls` | Array | Yes | An array of objects, each containing an `audio_url` property pointing to an audio file to be concatenated. Must contain at least one item. | +| `webhook_url` | String | No | A URL to receive a callback notification when processing is complete. If provided, the request will be processed asynchronously. | +| `id` | String | No | A custom identifier for tracking the request. | + +Each object in the `audio_urls` array must have: +- `audio_url`: String (URI format). The URL of an audio file to be concatenated. + +### Example Request + +```json +{ + "audio_urls": [ + { "audio_url": "https://example.com/audio1.mp3" }, + { "audio_url": "https://example.com/audio2.mp3" }, + { "audio_url": "https://example.com/audio3.mp3" } + ], + "webhook_url": "https://your-webhook-endpoint.com/callback", + "id": "custom-request-id-123" +} +``` + +### Example cURL Command + +```bash +curl -X POST \ + https://api.example.com/v1/audio/concatenate \ + -H 'Content-Type: application/json' \ + -H 'x-api-key: your-api-key-here' \ + -d '{ + "audio_urls": [ + { "audio_url": "https://example.com/audio1.mp3" }, + { "audio_url": "https://example.com/audio2.mp3" } + ], + "webhook_url": "https://your-webhook-endpoint.com/callback", + "id": "custom-request-id-123" + }' +``` + +## Response + +### Synchronous Response (No webhook_url provided) + +If no `webhook_url` is provided, the request will be processed synchronously and return: + +```json +{ + "code": 200, + "id": "custom-request-id-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "response": "https://storage.example.com/combined-audio-file.mp3", + "message": "success", + "run_time": 2.345, + "queue_time": 0, + "total_time": 2.345, + "pid": 12345, + "queue_id": 67890, + "queue_length": 0, + "build_number": "1.0.123" +} +``` + +### Asynchronous Response (webhook_url provided) + +If a `webhook_url` is provided, the request will be queued for processing and immediately return: + +```json +{ + "code": 202, + "id": "custom-request-id-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "processing", + "pid": 12345, + "queue_id": 67890, + "max_queue_length": "unlimited", + "queue_length": 1, + "build_number": "1.0.123" +} +``` + +When processing is complete, a webhook will be sent to the provided URL with the following payload: + +```json +{ + "endpoint": "/v1/audio/concatenate", + "code": 200, + "id": "custom-request-id-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "response": "https://storage.example.com/combined-audio-file.mp3", + "message": "success", + "pid": 12345, + "queue_id": 67890, + "run_time": 3.456, + "queue_time": 1.234, + "total_time": 4.690, + "queue_length": 0, + "build_number": "1.0.123" +} +``` + +### Error Responses + +#### Invalid Request Format (400 Bad Request) + +```json +{ + "code": 400, + "id": null, + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "Invalid request: 'audio_urls' is a required property", + "pid": 12345, + "queue_id": 67890, + "queue_length": 0, + "build_number": "1.0.123" +} +``` + +#### Authentication Error (401 Unauthorized) + +```json +{ + "code": 401, + "message": "Invalid or missing API key", + "build_number": "1.0.123" +} +``` + +#### Queue Limit Reached (429 Too Many Requests) + +```json +{ + "code": 429, + "id": "custom-request-id-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "MAX_QUEUE_LENGTH (100) reached", + "pid": 12345, + "queue_id": 67890, + "queue_length": 100, + "build_number": "1.0.123" +} +``` + +#### Processing Error (500 Internal Server Error) + +```json +{ + "code": 500, + "id": "custom-request-id-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "Error downloading audio file: Connection refused", + "pid": 12345, + "queue_id": 67890, + "queue_length": 0, + "build_number": "1.0.123" +} +``` + +## Error Handling + +- **Missing Required Parameters**: If `audio_urls` is missing or empty, a 400 Bad Request response will be returned. +- **Invalid URL Format**: If any `audio_url` is not a valid URI, a 400 Bad Request response will be returned. +- **Authentication Failure**: If the API key is invalid or missing, a 401 Unauthorized response will be returned. +- **Queue Limit**: If the queue is full (when MAX_QUEUE_LENGTH is set), a 429 Too Many Requests response will be returned. +- **Processing Errors**: Any errors during audio download, processing, or upload will result in a 500 Internal Server Error response with details in the message field. + +## Usage Notes + +1. **Asynchronous Processing**: For long audio files, it's recommended to use the `webhook_url` parameter to process the request asynchronously. +2. **File Formats**: The service supports common audio formats. The output will be in a standard format (typically MP3). +3. **File Size**: There may be limits on the size of audio files that can be processed. Very large files might cause timeouts or failures. +4. **Queue Behavior**: If the system is under heavy load, requests with `webhook_url` will be queued. The MAX_QUEUE_LENGTH environment variable controls the maximum queue size. + +## Common Issues + +1. **Inaccessible Audio URLs**: Ensure all audio URLs are publicly accessible. Private or authentication-required URLs will cause failures. +2. **Incompatible Audio Formats**: Some exotic audio formats might not be supported. Stick to common formats like MP3, WAV, or AAC. +3. **Webhook Failures**: If your webhook endpoint is unavailable when the processing completes, you might not receive the completion notification. +4. **Timeout Issues**: Very large audio files might cause timeouts during download or processing. + +## Best Practices + +1. **Use Webhooks for Large Files**: Always use the webhook approach for large audio files or when concatenating many files. +2. **Include an ID**: Always include a custom `id` parameter to help track your requests, especially in webhook responses. +3. **Error Handling**: Implement robust error handling in your client application to handle various HTTP status codes. +4. **Webhook Reliability**: Ensure your webhook endpoint is reliable and can handle retries if necessary. +5. **File Preparation**: Pre-process your audio files to ensure they have compatible formats, sample rates, and channel configurations for best results. +6. **Queue Monitoring**: Monitor the `queue_length` in responses to understand system load and adjust your request patterns if needed. \ No newline at end of file diff --git a/docs/cloud-installation/do.md b/docs/cloud-installation/do.md new file mode 100644 index 0000000000000000000000000000000000000000..817c4c2cbd2ccf4b15167509d73e9babaa3a7efa --- /dev/null +++ b/docs/cloud-installation/do.md @@ -0,0 +1,109 @@ +# Installing on Digital Ocean + +This guide walks you through deploying the No-Code Architects Toolkit API on Digital Ocean's App Platform. + +## Prerequisites + +- A Digital Ocean account ([Sign up here](https://www.digitalocean.com/)) +- Basic familiarity with Digital Ocean App Platform +- A credit/debit card for billing (you'll only be charged for what you use) + +## Step 1: Create a New Project + +1. Sign in to your Digital Ocean account +2. Create a new project or select an existing one +3. This will organize your resources for the NCA Toolkit + +## Step 2: Create a Digital Ocean Space + +You'll need to create a Space (Digital Ocean's object storage) for the toolkit to store processed files: + +1. Navigate to **Spaces Object Storage** in the Digital Ocean dashboard +2. Click **Create a Space** +3. Select a region (e.g., New York) +4. Give your bucket a name (e.g., `nca-toolkit-bucket`) +5. Select your project +6. Click **Create Space** + +## Step 3: Generate API Keys for Your Space + +1. From your new Space, go to **Settings** +2. Click **Create Access Key** +3. Select **Full Access** +4. Give your key a name (e.g., `nca-toolkit-key`) +5. Click **Create Access Key** +6. **IMPORTANT**: Save both the Access Key and Secret Key shown - you will only see them once! +7. Also copy the Space URL (endpoint) for use in the next step + +## Step 4: Deploy the App + +1. From your Digital Ocean dashboard, click **Create** and select **App** +2. Choose **Container Image** as the deployment source +3. Select **Docker Hub** for the repository +4. Enter `stephengpope/no-code-architects-toolkit` as the image name +5. Enter `latest` for the image tag +6. Click **Next** +7. If needed, edit the name to remove any extra dashes (Digital Ocean may show an error for long names) +8. Choose **Web Service** as the service type + +## Step 5: Configure Resources + +1. Select a plan with adequate resources for your needs: + - For testing, a $50/month instance provides good performance + - For smaller workloads, you can select a smaller instance + - Note: You're only charged for the time the server is running +2. Set Containers to 1 +3. Close the resource selection dialog + +## Step 6: Configure Environment Variables + +Add the following environment variables exactly as shown (be careful with underscores vs. dashes and avoid any leading/trailing spaces): + +1. `API_KEY`: Your API key (e.g., `test123` for testing - change for production) +2. `S3_ENDPOINT_URL`: The URL of your Space (copied from Step 3) +3. `S3_ACCESS_KEY`: The access key from Step 3 +4. `S3_SECRET_KEY`: The secret key from Step 3 +5. `S3_BUCKET_NAME`: The name of your Space bucket (e.g., `nca-toolkit-bucket`) +6. `S3_REGION`: The region code of your Space (e.g., `NYC3` for New York) + +## Step 7: Finalize and Deploy + +1. For Deployment Region, select a region close to your location (e.g., San Francisco) +2. You can use the default app name or choose a custom name +3. Click **Create Resource** +4. Wait for the deployment to complete (this may take a few minutes) + - You may need to refresh the page to see updates + +## Step 8: Test Your Deployment + +### Using Postman + +1. Sign up for or log in to [Postman](https://www.postman.com/) +2. Import the [NCA Toolkit Postman Collection](https://bit.ly/49Gkh61) +3. Fork the collection to your workspace +4. Create a new environment: + - Name it "Digital Ocean" or similar + - Add a variable `x-api-key` with the value matching your API_KEY (e.g., `test123`) + - Add a variable `base_url` with the value of your app's URL (shown in the Digital Ocean dashboard) + - Save the environment +5. In the collection, navigate to the `toolkit/authenticate` endpoint and click Send +6. If you receive a success response, your deployment is working correctly +7. Then test the `toolkit/test` endpoint to verify complete functionality + +## Monitoring and Management + +- **Overview**: View basic information about your app +- **Insights**: Monitor CPU and memory usage +- **Runtime Logs**: View logs of API calls and server activity +- **Console**: Access the server's command line (rarely needed) +- **Settings**: Modify your app's configuration + +## Next Steps + +Now that you have successfully deployed the NCA Toolkit API, you can: +- Explore all the available endpoints in the Postman collection +- Integrate the API with your applications +- Consider securing your API key with a more complex value +- Scale your resources up or down based on your usage requirements + +Remember, Digital Ocean charges based on usage, so you can always delete the app when you're not using it to save costs. \ No newline at end of file diff --git a/docs/cloud-installation/gcp.md b/docs/cloud-installation/gcp.md new file mode 100644 index 0000000000000000000000000000000000000000..1475b6ed1785c4d8e19cbd9a77e5056ff82d4f15 --- /dev/null +++ b/docs/cloud-installation/gcp.md @@ -0,0 +1,140 @@ +# Installing on the Google Cloud Platform (GCP) + +## 🎥 Video Instructions + +Watch **[Detailed Video Instructions](https://youtu.be/6bC93sek9v8)** to set up the No-Code Architects Toolkit API. + +- Use the **Docker Image** below: + + ``` + stephengpope/no-code-architects-toolkit:latest + ``` + +### Video Resources + +- **[Postman Template](https://bit.ly/49Gkh61)** +- **[NCA Toolkit API GPT](https://bit.ly/4feDDk4)** + +Or use the guide below walks you through the steps to install the NCA Toolkit API on GCP. + +--- + +## **Prerequisites** +- A Google Cloud account. [Sign up here](https://cloud.google.com/) if you don't already have one. + - New users receive $300 in free credits. +- Basic knowledge of GCP services such as Cloud Run and Cloud Storage. +- A terminal or code editor for managing files. + +--- + +## **Step 1: Create a Google Cloud Project** +1. Log into the [GCP Console](https://console.cloud.google.com/). +2. Click on the **Project Selector** in the top navigation bar and select **New Project**. +3. Enter a project name, such as `NCA Toolkit Project`. +4. Click **Create**. + +--- + +## **Step 2: Enable Required APIs** +Enable the following APIs: +- **Cloud Storage API** +- **Cloud Storage JSON API** +- **Cloud Run API** + +### **How to Enable APIs:** +1. In the GCP Console, navigate to **APIs & Services** > **Enable APIs and Services**. +2. Search for each API, click on it, and enable it. + +--- + +## **Step 3: Create a Service Account** +1. Navigate to **IAM & Admin** > **Service Accounts** in the GCP Console. +2. Click **+ Create Service Account**. + - Enter a name (e.g., `NCA Toolkit Service Account`). +3. Assign the following roles to the service account: + - **Storage Admin** + - **Viewer** +4. Click **Done** to create the service account. +5. Open the service account details and navigate to the **Keys** tab. + - Click **Add Key** > **Create New Key**. + - Choose **JSON** format, download the file, and store it securely. + +--- + +## **Step 4: Create a Cloud Storage Bucket** +1. Navigate to **Storage** > **Buckets** in the GCP Console. +2. Click **+ Create Bucket**. + - Choose a unique bucket name (e.g., `nca-toolkit-bucket`). + - Leave default settings, but: + - Uncheck **Enforce public access prevention**. + - Set **Access Control** to **Uniform**. +3. Click **Create** to finish. +4. Go to the bucket permissions, and add **allUsers** as a principal with the role: + - **Storage Object Viewer**. +5. Save changes. + +--- + +## **Step 5: Deploy on Google Cloud Run** + +### 1. Navigate to Cloud Run +- Open the **Cloud Run** service in the **Google Cloud Console**. + +### 2. Create a New Service +- Click **Create Service**. +- Then **Deploy one revision from Docker Hub using the image below**: + + ``` + stephengpope/no-code-architects-toolkit:latest + ``` + +### 3. Allow Unauthenticated Invocations +- Check the box to **allow unauthenticated invocations**. + +### 4. Configure Resource Allocation +- Set **Memory**: `16 GB`. +- Set **CPU**: `4 CPUs`. +- Set **CPU Allocation**: **Always Allocated**. + +### 5. Adjust Scaling Settings +- **Minimum Instances**: `0` (to minimize cost during idle times). +- **Maximum Instances**: `5` (adjustable based on expected load). + +### 6. Use Second-Generation Servers +- Scroll to **Platform Version** and select **Second Generation**. +- Second-generation servers offer better performance and feature support for advanced use cases. + +### 7. Add Environment Variables +- Add the following environment variables: +- `API_KEY`: Your API key (e.g., `Test123`). +- `GCP_BUCKET_NAME`: The name of your Cloud Storage bucket. +- `GCP_SA_CREDENTIALS`: The JSON key of your service account. + - Paste the **entire contents** of the downloaded JSON key file into this field. + - Ensure: + - Proper JSON formatting. + - No leading or trailing spaces. + +### 8. Configure Advanced Settings +- Set the **Container Port**: Default to `8080`. +- **Request Timeout**: `300 seconds` (to handle long-running requests). +- Enable **Startup Boost** to improve performance for the first request after a cold start. + +### 9. Deploy the Service +- Verify all settings and click **Create**. +- The deployment process might take a few minutes. Once completed, a green checkmark should appear in the Cloud Run dashboard. + +By following these steps, the NCA Toolkit will be successfully deployed and accessible via Google Cloud Run with second-generation servers for optimal performance. + +--- + +## **Step 6: Test the Deployment** + +1. Install **[Postman Template](https://bit.ly/49Gkh61)** on your computer. +2. Import the API example requests from the NCA Toolkit GitHub repository. +3. Configure two environment variables in Postman: + - `base_url`: Your deployed Cloud Run service URL. + - `x-api-key`: The API key you configured in **Step 5**. +4. Use the example requests to validate that the API is functioning correctly. +5. Use the **[NCA Toolkit API GPT](https://bit.ly/4feDDk4)** to learn more. + +By following these steps, your NCA Toolkit API should be successfully deployed on Google Cloud Platform. \ No newline at end of file diff --git a/docs/code/execute/execute_python.md b/docs/code/execute/execute_python.md new file mode 100644 index 0000000000000000000000000000000000000000..b31542531b2416ebab7db10934c03ff76be965ca --- /dev/null +++ b/docs/code/execute/execute_python.md @@ -0,0 +1,174 @@ +# Execute Python Code Endpoint + +## 1. Overview + +The `/v1/code/execute/python` endpoint allows users to execute Python code on the server. This endpoint is part of the version 1.0 API structure defined in `app.py`. It is designed to provide a secure and controlled environment for executing Python code, with features like input validation, output capturing, and timeout handling. + +## 2. Endpoint + +**URL Path:** `/v1/code/execute/python` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following properties: + +- `code` (string, required): The Python code to be executed. +- `timeout` (integer, optional): The maximum execution time in seconds, between 1 and 300. Default is 30 seconds. +- `webhook_url` (string, optional): The URL to receive the execution result via a webhook. +- `id` (string, optional): A unique identifier for the request. + +The `validate_payload` directive in the routes file enforces the following JSON schema for the request body: + +```json +{ + "type": "object", + "properties": { + "code": {"type": "string"}, + "timeout": {"type": "integer", "minimum": 1, "maximum": 300}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["code"], + "additionalProperties": False +} +``` + +### Example Request + +**Request Payload:** + +```json +{ + "code": "print('Hello, World!')", + "timeout": 10, + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +} +``` + +**cURL Command:** + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"code": "print('Hello, World!')", "timeout": 10, "webhook_url": "https://example.com/webhook", "id": "unique-request-id"}' \ + http://your-api-endpoint/v1/code/execute/python +``` + +## 4. Response + +### Success Response + +The success response follows the general response format defined in `app.py`. Here's an example: + +```json +{ + "endpoint": "/v1/code/execute/python", + "code": 200, + "id": "unique-request-id", + "job_id": "generated-job-id", + "response": { + "result": null, + "stdout": "Hello, World!\n", + "stderr": "", + "exit_code": 0 + }, + "message": "success", + "pid": 12345, + "queue_id": 1234567890, + "run_time": 0.123, + "queue_time": 0.0, + "total_time": 0.123, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +#### Missing or Invalid Parameters + +**Status Code:** 400 Bad Request + +```json +{ + "error": "Missing or invalid parameters", + "stdout": "", + "exit_code": 400 +} +``` + +#### Execution Error + +**Status Code:** 400 Bad Request + +```json +{ + "error": "Error message from the executed code", + "stdout": "Output from the executed code", + "exit_code": 400 +} +``` + +#### Execution Timeout + +**Status Code:** 408 Request Timeout + +```json +{ + "error": "Execution timed out after 10 seconds" +} +``` + +#### Internal Server Error + +**Status Code:** 500 Internal Server Error + +```json +{ + "error": "An internal server error occurred", + "stdout": "", + "stderr": "", + "exit_code": 500 +} +``` + +## 5. Error Handling + +The endpoint handles various types of errors, including: + +- Missing or invalid parameters (400 Bad Request) +- Execution errors, such as syntax errors or exceptions (400 Bad Request) +- Execution timeout (408 Request Timeout) +- Internal server errors (500 Internal Server Error) + +The main application context (`app.py`) also includes error handling for queue overload (429 Too Many Requests) and other general errors. + +## 6. Usage Notes + +- The executed code runs in a sandboxed environment, with limited access to system resources. +- The code execution is limited to a maximum of 300 seconds (5 minutes) by default, but this can be adjusted using the `timeout` parameter. +- The execution result, including stdout, stderr, and the return value, is captured and returned in the response. +- If a `webhook_url` is provided, the execution result will also be sent to the specified webhook. + +## 7. Common Issues + +- Attempting to execute code that accesses restricted resources or performs disallowed operations may result in an execution error. +- Long-running or resource-intensive code may trigger the execution timeout. +- Providing an invalid `webhook_url` will prevent the execution result from being delivered to the specified webhook. + +## 8. Best Practices + +- Always validate and sanitize user input to prevent code injection attacks. +- Set an appropriate timeout value based on the expected execution time of the code. +- Monitor the execution logs for any errors or unexpected behavior. +- Implement rate limiting or queue management to prevent abuse or overload of the endpoint. +- Consider implementing additional security measures, such as code sandboxing or whitelisting/blacklisting certain operations or modules. diff --git a/docs/ffmpeg/ffmpeg_compose.md b/docs/ffmpeg/ffmpeg_compose.md new file mode 100644 index 0000000000000000000000000000000000000000..bd9e7864367fd4c1d7d9f5c893419d3eca3f05e7 --- /dev/null +++ b/docs/ffmpeg/ffmpeg_compose.md @@ -0,0 +1,245 @@ +# FFmpeg Compose API Endpoint + +## 1. Overview + +The `/v1/ffmpeg/compose` endpoint is a flexible and powerful API that allows users to compose complex FFmpeg commands by providing input files, filters, and output options. This endpoint is part of the version 1.0 API structure, as shown in the `app.py` file. It is designed to handle various media processing tasks, such as video and audio manipulation, transcoding, and more. + +## 2. Endpoint + +**URL Path:** `/v1/ffmpeg/compose` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body should be a JSON object with the following properties: + +- `inputs` (required, array): An array of input file objects, each containing: + - `file_url` (required, string): The URL of the input file. + - `options` (optional, array): An array of option objects, each containing: + - `option` (required, string): The FFmpeg option. + - `argument` (optional, string, number, or null): The argument for the option. +- `filters` (optional, array): An array of filter objects, each containing: + - `filter` (required, string): The FFmpeg filter. +- `outputs` (required, array): An array of output option objects, each containing: + - `options` (required, array): An array of option objects, each containing: + - `option` (required, string): The FFmpeg option. + - `argument` (optional, string, number, or null): The argument for the option. +- `global_options` (optional, array): An array of global option objects, each containing: + - `option` (required, string): The FFmpeg global option. + - `argument` (optional, string, number, or null): The argument for the option. +- `metadata` (optional, object): An object specifying which metadata to include in the response, with the following properties: + - `thumbnail` (optional, boolean): Whether to include a thumbnail for the output file. + - `filesize` (optional, boolean): Whether to include the file size of the output file. + - `duration` (optional, boolean): Whether to include the duration of the output file. + - `bitrate` (optional, boolean): Whether to include the bitrate of the output file. + - `encoder` (optional, boolean): Whether to include the encoder used for the output file. +- `webhook_url` (required, string): The URL to send the response webhook. +- `id` (required, string): A unique identifier for the request. + +### Example Request + +```json +{ + "inputs": [ + { + "file_url": "https://example.com/video1.mp4", + "options": [ + { + "option": "-ss", + "argument": 10 + }, + { + "option": "-t", + "argument": 20 + } + ] + }, + { + "file_url": "https://example.com/video2.mp4" + } + ], + "filters": [ + { + "filter": "hflip" + } + ], + "outputs": [ + { + "options": [ + { + "option": "-c:v", + "argument": "libx264" + }, + { + "option": "-crf", + "argument": 23 + } + ] + } + ], + "global_options": [ + { + "option": "-y" + } + ], + "metadata": { + "thumbnail": true, + "filesize": true, + "duration": true, + "bitrate": true, + "encoder": true + }, + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +} +``` + +```bash +curl -X POST \ + https://api.example.com/v1/ffmpeg/compose \ + -H 'x-api-key: YOUR_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{ + "inputs": [ + { + "file_url": "https://example.com/video1.mp4", + "options": [ + { + "option": "-ss", + "argument": 10 + }, + { + "option": "-t", + "argument": 20 + } + ] + }, + { + "file_url": "https://example.com/video2.mp4" + } + ], + "filters": [ + { + "filter": "hflip" + } + ], + "outputs": [ + { + "options": [ + { + "option": "-c:v", + "argument": "libx264" + }, + { + "option": "-crf", + "argument": 23 + } + ] + } + ], + "global_options": [ + { + "option": "-y" + } + ], + "metadata": { + "thumbnail": true, + "filesize": true, + "duration": true, + "bitrate": true, + "encoder": true + }, + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" + }' +``` + +## 4. Response + +### Success Response + +The response will be sent to the specified `webhook_url` as a JSON object with the following properties: + +- `endpoint` (string): The endpoint URL (`/v1/ffmpeg/compose`). +- `code` (number): The HTTP status code (200 for success). +- `id` (string): The unique identifier for the request. +- `job_id` (string): The unique job ID assigned to the request. +- `response` (array): An array of output file objects, each containing: + - `file_url` (string): The URL of the uploaded output file. + - `thumbnail_url` (string, optional): The URL of the uploaded thumbnail, if requested. + - `filesize` (number, optional): The file size of the output file, if requested. + - `duration` (number, optional): The duration of the output file, if requested. + - `bitrate` (number, optional): The bitrate of the output file, if requested. + - `encoder` (string, optional): The encoder used for the output file, if requested. +- `message` (string): The success message ("success"). +- `pid` (number): The process ID of the worker that processed the request. +- `queue_id` (number): The ID of the queue used for processing the request. +- `run_time` (number): The time taken to process the request (in seconds). +- `queue_time` (number): The time the request spent in the queue (in seconds). +- `total_time` (number): The total time taken to process the request, including queue time (in seconds). +- `queue_length` (number): The current length of the processing queue. +- `build_number` (string): The build number of the application. + +### Error Responses + +- **400 Bad Request**: The request payload is invalid or missing required parameters. +- **401 Unauthorized**: The provided API key is invalid or missing. +- **429 Too Many Requests**: The maximum queue length has been reached. +- **500 Internal Server Error**: An unexpected error occurred while processing the request. + +Example error response: + +```json +{ + "code": 400, + "id": "unique-request-id", + "job_id": "job-id", + "message": "Invalid request payload: 'inputs' is a required property", + "pid": 123, + "queue_id": 456, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +The API handles various types of errors, including: + +- **Missing or invalid parameters**: If the request payload is missing required parameters or contains invalid data types, a 400 Bad Request error will be returned. +- **Authentication failure**: If the provided API key is invalid or missing, a 401 Unauthorized error will be returned. +- **Queue limit reached**: If the maximum queue length is reached, a 429 Too Many Requests error will be returned. +- **Unexpected errors**: If an unexpected error occurs during request processing, a 500 Internal Server Error will be returned. + +The main application context (`app.py`) includes error handling for the processing queue. If the maximum queue length is set and the queue size reaches that limit, new requests will be rejected with a 429 Too Many Requests error. + +## 6. Usage Notes + +- The `inputs` array must contain at least one input file object. +- The `outputs` array must contain at least one output option object. +- The `filters` array is optional and can be used to apply FFmpeg filters to the input files. +- The `global_options` array is optional and can be used to specify global FFmpeg options. +- The `metadata` object is optional and can be used to request specific metadata for the output files. +- The `webhook_url` parameter is required and specifies the URL where the response should be sent. +- The `id` parameter is required and should be a unique identifier for the request. + +## 7. Common Issues + +- Providing invalid or malformed input file URLs. +- Specifying invalid or unsupported FFmpeg options or filters. +- Reaching the maximum queue length, resulting in a 429 Too Many Requests error. +- Network or connectivity issues that prevent the response webhook from being delivered. + +## 8. Best Practices + +- Validate input file URLs and ensure they are accessible before sending the request. +- Test your FFmpeg command locally before using the API to ensure it works as expected. +- Monitor the queue length and adjust the maximum queue length as needed to prevent overloading the system. +- Implement retry mechanisms for handling failed webhook deliveries or other transient errors. +- Use unique and descriptive `id` values for each request to aid in troubleshooting and monitoring. \ No newline at end of file diff --git a/docs/image/convert/image_to_video.md b/docs/image/convert/image_to_video.md new file mode 100644 index 0000000000000000000000000000000000000000..419a1151a95d7052f6e101353fa7c8c34ef11c74 --- /dev/null +++ b/docs/image/convert/image_to_video.md @@ -0,0 +1,159 @@ +# Image to Video Conversion + +## 1. Overview + +The `/v1/image/convert/video` endpoint is part of the Flask API application and is responsible for converting an image into a video file. This endpoint is registered in the `app.py` file under the `v1_image_convert_video_bp` blueprint, which is imported from the `routes.v1.image.convert.image_to_video` module. + +## 2. Endpoint + +**URL Path:** `/v1/image/convert/video` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body must be in JSON format and should include the following parameters: + +| Parameter | Type | Required | Description | +|-------------|--------|----------|--------------------------------------------------------------| +| `image_url` | string | Yes | The URL of the image to be converted into a video. | +| `length` | number | No | The desired length of the video in seconds (default: 5). | +| `frame_rate`| integer| No | The frame rate of the output video (default: 30). | +| `zoom_speed`| number | No | The speed of the zoom effect (0-100, default: 3). | +| `webhook_url`| string| No | The URL to receive a webhook notification upon completion. | +| `id` | string | No | An optional identifier for the request. | + +The `validate_payload` decorator in the `routes.v1.image.convert.image_to_video` module enforces the following JSON schema for the request body: + +```json +{ + "type": "object", + "properties": { + "image_url": {"type": "string", "format": "uri"}, + "length": {"type": "number", "minimum": 1, "maximum": 60}, + "frame_rate": {"type": "integer", "minimum": 15, "maximum": 60}, + "zoom_speed": {"type": "number", "minimum": 0, "maximum": 100}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["image_url"], + "additionalProperties": false +} +``` + +### Example Request + +```json +{ + "image_url": "https://example.com/image.jpg", + "length": 10, + "frame_rate": 24, + "zoom_speed": 5, + "webhook_url": "https://example.com/webhook", + "id": "request-123" +} +``` + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"image_url": "https://example.com/image.jpg", "length": 10, "frame_rate": 24, "zoom_speed": 5, "webhook_url": "https://example.com/webhook", "id": "request-123"}' \ + http://your-api-endpoint/v1/image/convert/video +``` + +## 4. Response + +### Success Response + +Upon successful processing, the endpoint returns a JSON response with the following structure: + +```json +{ + "code": 200, + "id": "request-123", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": "https://cloud-storage.example.com/converted-video.mp4", + "message": "success", + "run_time": 2.345, + "queue_time": 0.123, + "total_time": 2.468, + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +The `response` field contains the URL of the converted video file uploaded to cloud storage. + +### Error Responses + +#### 429 Too Many Requests + +If the maximum queue length is reached, the endpoint returns a 429 Too Many Requests response: + +```json +{ + "code": 429, + "id": "request-123", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "MAX_QUEUE_LENGTH (10) reached", + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 10, + "build_number": "1.0.0" +} +``` + +#### 500 Internal Server Error + +If an exception occurs during the image-to-video conversion process, the endpoint returns a 500 Internal Server Error response: + +```json +{ + "code": 500, + "id": "request-123", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "Error message describing the exception", + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +The endpoint handles the following types of errors: + +- **Missing or invalid parameters**: If the request body is missing required parameters or contains invalid parameter values, the `validate_payload` decorator will return a 400 Bad Request response with a descriptive error message. +- **Queue length exceeded**: If the maximum queue length is reached and the `bypass_queue` parameter is set to `False`, the endpoint returns a 429 Too Many Requests response. +- **Exceptions during processing**: If an exception occurs during the image-to-video conversion process, the endpoint returns a 500 Internal Server Error response with the error message. + +## 6. Usage Notes + +- The `image_url` parameter must be a valid URL pointing to an image file. +- The `length` parameter specifies the duration of the output video in seconds and must be between 1 and 60. +- The `frame_rate` parameter specifies the frame rate of the output video and must be between 15 and 60. +- The `zoom_speed` parameter controls the speed of the zoom effect and must be between 0 and 100. +- The `webhook_url` parameter is optional and can be used to receive a notification when the conversion is complete. +- The `id` parameter is optional and can be used to identify the request. + +## 7. Common Issues + +- Providing an invalid or inaccessible `image_url` will result in an error during processing. +- Specifying invalid parameter values outside the allowed ranges will result in a 400 Bad Request response. +- If the maximum queue length is reached and the `bypass_queue` parameter is set to `False`, the request will be rejected with a 429 Too Many Requests response. + +## 8. Best Practices + +- Validate the `image_url` parameter before sending the request to ensure it points to a valid and accessible image file. +- Use the `webhook_url` parameter to receive notifications about the completion of the conversion process, rather than polling the API repeatedly. +- Provide the `id` parameter to easily identify and track the request in logs or notifications. +- Consider setting the `bypass_queue` parameter to `True` for time-sensitive requests to bypass the queue and process the request immediately. diff --git a/docs/image/screenshot_webpage.md b/docs/image/screenshot_webpage.md new file mode 100644 index 0000000000000000000000000000000000000000..d006bedf73326ac0cf1f41e85f2b518f8dc9998a --- /dev/null +++ b/docs/image/screenshot_webpage.md @@ -0,0 +1,218 @@ +# Playwright Screenshot Endpoint + +**Implemented by:** [Harrison Fisher](https://github.com/HarrisonFisher) + +## ⚠️ Disclaimer +- This endpoint is **not intended to bypass CAPTCHAs, Cloudflare**, or other anti-bot protections. +- Please **do not create issues or requests** asking for CAPTCHA or Cloudflare bypass features. +- It will not work for sites with such defenses, and attempting to automate against protected sites could result in your IP address being blacklisted by Cloudflare or similar services. +- The screenshot endpoint supports custom HTML, JavaScript, and CSS input for flexible rendering and automation, as an alternative to using a URL. +- This feature should only be used on sites you own or have explicit permission to automate. + + +## 1. Overview + +The `/v1/image/screenshot/webpage` endpoint allows you to capture screenshots of web pages using the Playwright browser automation library. It supports advanced options such as viewport size, device emulation, cookies, headers, element targeting, and more. Screenshots are uploaded to cloud storage, and the resulting URL is returned. This endpoint is part of the v1 API suite and is registered in the main Flask application as a blueprint. + +## 2. Endpoint + +- **URL Path:** `/v1/image/screenshot/webpage` +- **HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): Your API key for authentication. +- `Content-Type`: `application/json` + +### Body Parameters + +The request body must be a JSON object with the following properties: + +- `url` (string, required): The URL of the web page to capture. +- `html` (string, optional): Raw HTML content to render and capture. + **Note:** Either `url` or `html` must be provided, but not both. +- `viewport_width` (integer, optional): Viewport width in pixels. +- `viewport_height` (integer, optional): Viewport height in pixels. +- `full_page` (boolean, optional): Capture the full scrollable page. Default: `false`. +- `format` (string, optional): Image format, either `png` or `jpeg`. Default: `png`. +- `delay` (integer, optional): Delay in milliseconds before taking the screenshot. +- `device_scale_factor` (number, optional): Device scale factor (e.g., 2 for retina). +- `user_agent` (string, optional): Custom user agent string. +- `cookies` (array, optional): List of cookies to set. Each cookie is an object with `name`, `value`, and `domain`. +- `headers` (object, optional): Additional HTTP headers to set. +- `quality` (integer, optional): JPEG quality (0-100, only for `jpeg` format). +- `clip` (object, optional): Region to capture, with `x`, `y`, `width`, `height` (all numbers). +- `timeout` (integer, optional): Navigation timeout in milliseconds. Minimum: 100. +- `wait_until` (string, optional): When to consider navigation succeeded. One of `load`, `domcontentloaded`, `networkidle`, `networkidle2`. Default: `load`. +- `wait_for_selector` (string, optional): Wait for a selector before screenshot. +- `emulate` (object, optional): Emulation options, e.g., `{ "color_scheme": "dark" }`. +- `omit_background` (boolean, optional): Hide default white background. Default: `false`. +- `selector` (string, optional): CSS selector for a specific element to screenshot. +- `webhook_url` (string, optional): If provided, results are sent to this URL asynchronously. +- `id` (string, optional): Custom identifier for the request. +- `js` (string, optional): JavaScript code to inject into the page before taking the screenshot. +- `css` (string, optional): CSS code to inject into the page before taking the screenshot. + +#### Example Request + +```json +{ + "url": "https://example.com", + "viewport_width": 1280, + "viewport_height": 720, + "js": "document.body.style.background = 'red';", + "css": "body { font-size: 30px; }", + "full_page": true, + "format": "png", + "delay": 500, + "device_scale_factor": 2, + "user_agent": "CustomAgent/1.0", + "cookies": [ + { + "name": "test_cookie", + "value": "test_value", + "domain": "example.com", + "path": "/" + } + ], + "headers": { + "Accept-Language": "en-US,en;q=0.9" + }, + "quality": 90, + "clip": { + "x": 0, + "y": 0, + "width": 800, + "height": 600 + }, + "timeout": 10000, + "wait_until": "networkidle", + "wait_for_selector": "#main-content", + "selector": "#main-content", + "emulate": { + "color_scheme": "dark" + }, + "omit_background": true, + "webhook_url": "https://your-webhook.com/callback", + "id": "custom-job-123" +} +``` + +**cURL Example:** + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "url": "https://example.com", + "viewport_width": 1280, + "viewport_height": 720, + "js": "document.body.style.background = '\''red'\'';", + "css": "body { font-size: 30px; }", + "full_page": true, + "format": "png", + "delay": 500, + "device_scale_factor": 2, + "user_agent": "CustomAgent/1.0", + "cookies": [ + {"name": "test_cookie", "value": "test_value", "domain": "example.com", "path": "/"} + ], + "headers": {"Accept-Language": "en-US,en;q=0.9"}, + "quality": 90, + "clip": {"x": 0, "y": 0, "width": 800, "height": 600}, + "timeout": 10000, + "wait_until": "networkidle", + "wait_for_selector": "#main-content", + "selector": "#main-content", + "emulate": {"color_scheme": "dark"}, + "omit_background": true, + "webhook_url": "https://your-webhook.com/callback", + "id": "custom-job-123" + }' \ + https://your-api-endpoint.com/v1/image/screenshot/webpage +``` + +## 4. Response + +### Success Response + +The response is a JSON object containing the cloud storage URL of the screenshot and job metadata. If a `webhook_url` is provided, the result is sent asynchronously to the webhook. + +```json +{ + "endpoint": "/v1/image/screenshot/webpage", + "code": 200, + "id": "custom-job-123", + "job_id": "d290f1ee-6c54-4b01-90e6-d701748f0851", + "response": "https://cloud.example.com/screenshot.png", + "message": "success", + "pid": 12345, + "queue_id": 140682639937472, + "run_time": 2.345, + "queue_time": 0.012, + "total_time": 2.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +- **400 Bad Request**: Invalid or missing parameters. +- **401 Unauthorized**: Invalid or missing API key. +- **429 Too Many Requests**: Queue is full. +- **500 Internal Server Error**: An error occurred during processing. + +Example error response: + +```json +{ + "endpoint": "/v1/image/screenshot/webpage", + "code": 500, + "id": "custom-job-123", + "job_id": "d290f1ee-6c54-4b01-90e6-d701748f0851", + "response": null, + "message": "Error message details", + "pid": 12345, + "queue_id": 140682639937472, + "run_time": 0.123, + "queue_time": 0.056, + "total_time": 0.179, + "queue_length": 1, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +- **Missing or invalid parameters**: Returns 400 with details. +- **Authentication failure**: Returns 401. +- **Queue full**: Returns 429. +- **Processing error**: Returns 500 with error message. + +## 6. Usage Notes + +- If `webhook_url` is provided, the request is processed asynchronously and the result is sent to the webhook. +- Screenshots are always uploaded to cloud storage; the response contains the file URL. +- Use `selector` to capture a specific element instead of the full page. +- The `clip` parameter allows capturing a specific region. +- The endpoint enforces strict payload validation. + +## 7. Common Issues + +- Invalid or inaccessible URL. +- Selector not found (if using `wait_for_selector` or `selector`). +- Cookie domain mismatch. +- Timeout errors for slow-loading pages. +- Invalid API key. + +## 8. Best Practices + +- Always validate your input parameters before sending the request. +- Use unique `id` values for tracking jobs. +- Monitor queue length and handle 429 errors gracefully. +- Use HTTPS for all URLs and webhooks. +- Test your selectors and page state locally before automating screenshots. diff --git a/docs/media/convert/media_convert.md b/docs/media/convert/media_convert.md new file mode 100644 index 0000000000000000000000000000000000000000..6345ecaa24841d3d070ee279bfad21568c250760 --- /dev/null +++ b/docs/media/convert/media_convert.md @@ -0,0 +1,138 @@ +# Media Convert Endpoint Documentation + +## 1. Overview + +The `/v1/media/convert` endpoint is part of the Flask API application and is responsible for converting media files (audio or video) from one format to another. This endpoint fits into the overall API structure as a part of the `v1` blueprint, which contains various media-related functionalities. + +## 2. Endpoint + +**URL Path:** `/v1/media/convert` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following properties: + +- `media_url` (required, string): The URL of the media file to be converted. +- `format` (required, string): The desired output format for the converted media file. +- `video_codec` (optional, string): The video codec to be used for the conversion. Default is `libx264`. +- `video_preset` (optional, string): The video preset to be used for the conversion. Default is `medium`. +- `video_crf` (optional, number): The Constant Rate Factor (CRF) value for video encoding. Must be between 0 and 51. Default is 23. +- `audio_codec` (optional, string): The audio codec to be used for the conversion. Default is `aac`. +- `audio_bitrate` (optional, string): The audio bitrate to be used for the conversion. Default is `128k`. +- `webhook_url` (optional, string): The URL to receive a webhook notification upon completion of the conversion process. +- `id` (optional, string): An optional identifier for the conversion request. + +### Example Request + +```json +{ + "media_url": "https://example.com/video.mp4", + "format": "avi", + "video_codec": "libx264", + "video_preset": "medium", + "video_crf": 23, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +} +``` + +```bash +curl -X POST \ + https://api.example.com/v1/media/convert \ + -H 'x-api-key: YOUR_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{ + "media_url": "https://example.com/video.mp4", + "format": "avi", + "video_codec": "libx264", + "video_preset": "medium", + "video_crf": 23, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" + }' +``` + +## 4. Response + +### Success Response + +The success response will be a JSON object containing the URL of the converted media file uploaded to cloud storage, the endpoint path, and a status code of 200. + +```json +{ + "code": 200, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": "https://cloud.example.com/converted-video.avi", + "message": "success", + "pid": 12345, + "queue_id": 1234567890, + "run_time": 10.234, + "queue_time": 0.123, + "total_time": 10.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +- **400 Bad Request**: Returned when the request payload is missing or invalid. +- **401 Unauthorized**: Returned when the `x-api-key` header is missing or invalid. +- **500 Internal Server Error**: Returned when an unexpected error occurs during the conversion process. + +Example error response: + +```json +{ + "code": 400, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "Invalid request payload", + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +The endpoint uses the `validate_payload` decorator to validate the request payload against a JSON schema. If the payload is missing or invalid, a 400 Bad Request error is returned. + +The `authenticate` decorator is used to ensure that the request includes a valid `x-api-key` header. If the header is missing or invalid, a 401 Unauthorized error is returned. + +If an unexpected error occurs during the conversion process, a 500 Internal Server Error is returned, and the error is logged. + +## 6. Usage Notes + +- The `media_url` parameter must be a valid URL pointing to the media file to be converted. +- The `format` parameter must be a valid media format supported by the conversion process. +- The optional parameters (`video_codec`, `video_preset`, `video_crf`, `audio_codec`, `audio_bitrate`) allow you to customize the conversion settings. +- If the `webhook_url` parameter is provided, a webhook notification will be sent to the specified URL upon completion of the conversion process. +- The `id` parameter is optional and can be used to identify the conversion request. + +## 7. Common Issues + +- Providing an invalid or inaccessible `media_url`. +- Specifying an unsupported `format`. +- Providing invalid values for the optional parameters (e.g., `video_crf` outside the valid range). + +## 8. Best Practices + +- Always validate the input parameters on the client-side before sending the request. +- Use the `id` parameter to track and identify conversion requests. +- Provide a `webhook_url` to receive notifications about the conversion process completion. +- Monitor the API logs for any errors or issues during the conversion process. +- Consider implementing rate limiting or queue management to handle high volumes of requests. \ No newline at end of file diff --git a/docs/media/convert/media_to_mp3.md b/docs/media/convert/media_to_mp3.md new file mode 100644 index 0000000000000000000000000000000000000000..298d39ff283d81e77c5b7c3ecd01a31af1cbd064 --- /dev/null +++ b/docs/media/convert/media_to_mp3.md @@ -0,0 +1,142 @@ +# Media to MP3 Conversion + +The `/v1/media/convert/mp3` endpoint is part of the Flask API application and is responsible for converting various media files into MP3 format. This endpoint is registered in the `app.py` file under the `v1_media_convert_mp3_bp` blueprint. + +## Endpoint Details + +**URL Path:** `/v1/media/convert/mp3` + +## 1. Overview + +The `/v1/media/convert/mp3` endpoint is a part of the API's media transformation functionality. It allows users to convert various media files (audio or video) to MP3 format. This endpoint fits into the overall API structure as a part of the `v1` namespace, which represents the first version of the API. + +## 2. Endpoint + +``` +POST /v1/media/convert/mp3 +``` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +- `media_url` (required, string): The URL of the media file to be converted. +- `webhook_url` (optional, string): The URL to receive a webhook notification upon completion. +- `id` (optional, string): A unique identifier for the request. +- `bitrate` (optional, string): The desired bitrate for the output MP3 file, in the format `k` (e.g., `128k`). If not provided, defaults to `128k`. + +The `validate_payload` directive in the routes file enforces the following JSON schema for the request body: + +```json +{ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"}, + "bitrate": {"type": "string", "pattern": "^[0-9]+k$"} + }, + "required": ["media_url"], + "additionalProperties": False +} +``` + +### Example Request + +```json +{ + "media_url": "https://example.com/video.mp4", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id", + "bitrate": "192k" +} +``` + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"media_url": "https://example.com/video.mp4", "webhook_url": "https://example.com/webhook", "id": "unique-request-id", "bitrate": "192k"}' \ + https://your-api-endpoint.com/v1/media/convert/mp3 +``` + +## 4. Response + +### Success Response + +The success response follows the general response structure defined in `app.py`. Here's an example: + +```json +{ + "endpoint": "/v1/media/convert/mp3", + "code": 200, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": "https://cloud-storage.example.com/converted-file.mp3", + "message": "success", + "pid": 12345, + "queue_id": 6789, + "run_time": 5.234, + "queue_time": 0.123, + "total_time": 5.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +- **400 Bad Request**: Returned when the request payload is invalid or missing required parameters. +- **401 Unauthorized**: Returned when the `x-api-key` header is missing or invalid. +- **500 Internal Server Error**: Returned when an unexpected error occurs during the conversion process. + +Example error response: + +```json +{ + "code": 400, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "Invalid request payload: 'media_url' is a required property", + "pid": 12345, + "queue_id": 6789, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +The endpoint handles the following common errors: + +- Missing or invalid `media_url` parameter: Returns a 400 Bad Request error. +- Invalid `bitrate` parameter: Returns a 400 Bad Request error. +- Authentication failure: Returns a 401 Unauthorized error. +- Unexpected exceptions during the conversion process: Returns a 500 Internal Server Error. + +Additionally, the main application context (`app.py`) includes error handling for queue overload. If the maximum queue length is reached, the endpoint will return a 429 Too Many Requests error. + +## 6. Usage Notes + +- The `media_url` parameter should point to a valid media file (audio or video) that can be converted to MP3 format. +- If the `webhook_url` parameter is provided, a webhook notification will be sent to the specified URL upon completion of the conversion process. +- The `id` parameter can be used to uniquely identify the request, which can be helpful for tracking and logging purposes. +- The `bitrate` parameter allows you to specify the desired bitrate for the output MP3 file. If not provided, the default bitrate of 128k will be used. + +## 7. Common Issues + +- Providing an invalid or inaccessible `media_url`. +- Attempting to convert unsupported media formats. +- Exceeding the maximum queue length, resulting in a 429 Too Many Requests error. + +## 8. Best Practices + +- Validate the `media_url` parameter before sending the request to ensure it points to a valid and accessible media file. +- Consider providing a `webhook_url` parameter to receive notifications about the conversion process completion. +- Use a unique `id` parameter for each request to facilitate tracking and logging. +- Implement retry mechanisms in case of transient errors or queue overload situations. +- Monitor the API logs for any errors or issues during the conversion process. \ No newline at end of file diff --git a/docs/media/cut.md b/docs/media/cut.md new file mode 100644 index 0000000000000000000000000000000000000000..f4ef1e35d098999d2fc83a4a5003d5ef96b07427 --- /dev/null +++ b/docs/media/cut.md @@ -0,0 +1,169 @@ +# Media Cut Endpoint + +## 1. Overview + +The `/v1/media/cut` endpoint is part of the Flask API application and is designed to cut specified segments from a media file (video or audio) with optional encoding settings. This endpoint fits into the overall API structure as a part of the `v1` blueprint, which contains various media-related functionalities. + +## 2. Endpoint + +**URL Path:** `/v1/media/cut` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following properties: + +- `media_url` (required, string): The URL of the media file to be cut. +- `cuts` (required, array of objects): An array of cut segments, where each object has the following properties: + - `start` (required, string): The start time of the cut segment in the format `hh:mm:ss.ms`. + - `end` (required, string): The end time of the cut segment in the format `hh:mm:ss.ms`. +- `video_codec` (optional, string): The video codec to be used for encoding the output file. Default is `libx264`. +- `video_preset` (optional, string): The video preset to be used for encoding the output file. Default is `medium`. +- `video_crf` (optional, number): The Constant Rate Factor (CRF) value for video encoding. Must be between 0 and 51. Default is 23. +- `audio_codec` (optional, string): The audio codec to be used for encoding the output file. Default is `aac`. +- `audio_bitrate` (optional, string): The audio bitrate to be used for encoding the output file. Default is `128k`. +- `webhook_url` (optional, string): The URL to receive a webhook notification upon completion of the task. +- `id` (optional, string): A unique identifier for the request. + +### Example Request + +```json +{ + "media_url": "https://example.com/video.mp4", + "cuts": [ + { + "start": "00:00:10.000", + "end": "00:00:20.000" + }, + { + "start": "00:00:30.000", + "end": "00:00:40.000" + } + ], + "video_codec": "libx264", + "video_preset": "medium", + "video_crf": 23, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +} +``` + +``` +curl -X POST \ + https://api.example.com/v1/media/cut \ + -H 'x-api-key: YOUR_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{ + "media_url": "https://example.com/video.mp4", + "cuts": [ + { + "start": "00:00:10.000", + "end": "00:00:20.000" + }, + { + "start": "00:00:30.000", + "end": "00:00:40.000" + } + ], + "video_codec": "libx264", + "video_preset": "medium", + "video_crf": 23, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" + }' +``` + +## 4. Response + +### Success Response + +The success response follows the general response structure defined in the `app.py` file. Here's an example: + +```json +{ + "code": 200, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": { + "file_url": "https://example.com/output.mp4" + }, + "message": "success", + "run_time": 5.234, + "queue_time": 0.012, + "total_time": 5.246, + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +- **400 Bad Request**: Returned when the request payload is missing or invalid. + + ```json + { + "code": 400, + "message": "Invalid request payload" + } + ``` + +- **401 Unauthorized**: Returned when the `x-api-key` header is missing or invalid. + + ```json + { + "code": 401, + "message": "Unauthorized" + } + ``` + +- **500 Internal Server Error**: Returned when an unexpected error occurs on the server. + + ```json + { + "code": 500, + "message": "Internal Server Error" + } + ``` + +## 5. Error Handling + +The endpoint handles the following common errors: + +- Missing or invalid request parameters: Returns a 400 Bad Request error. +- Authentication failure: Returns a 401 Unauthorized error if the `x-api-key` header is missing or invalid. +- Unexpected exceptions: Returns a 500 Internal Server Error if an unexpected exception occurs during the media cut process. + +The main application context (`app.py`) also includes error handling for queue overload. If the maximum queue length is reached, the endpoint returns a 429 Too Many Requests error. + +## 6. Usage Notes + +- The `media_url` parameter must be a valid URL pointing to a media file (video or audio). +- The `cuts` parameter must be an array of objects, where each object specifies a start and end time for a cut segment in the format `hh:mm:ss.ms`. +- The optional encoding parameters (`video_codec`, `video_preset`, `video_crf`, `audio_codec`, `audio_bitrate`) can be used to customize the output file encoding settings. +- The `webhook_url` parameter is optional and can be used to receive a webhook notification upon completion of the task. +- The `id` parameter is optional and can be used to uniquely identify the request. + +## 7. Common Issues + +- Providing an invalid or inaccessible `media_url`. +- Providing invalid or out-of-range values for the encoding parameters. +- Providing overlapping or invalid cut segments in the `cuts` parameter. + +## 8. Best Practices + +- Validate the input parameters on the client-side before sending the request. +- Use the `webhook_url` parameter to receive notifications and handle the response asynchronously. +- Monitor the `queue_length` parameter in the response to manage the load on the API. +- Use the `id` parameter to correlate requests and responses for better tracking and debugging. \ No newline at end of file diff --git a/docs/media/download.md b/docs/media/download.md new file mode 100644 index 0000000000000000000000000000000000000000..c052b37f0484475c619ac09623863fb4fdce96df --- /dev/null +++ b/docs/media/download.md @@ -0,0 +1,330 @@ +# Media Download API Endpoint Documentation + +## Overview + +The `/v1/BETA/media/download` endpoint provides a powerful interface for downloading media content from various online sources using the yt-dlp library. This endpoint is part of the v1 media services in the API structure, allowing users to download videos, extract audio, and retrieve thumbnails and subtitles from supported platforms. The endpoint handles authentication, request validation, and queues tasks for processing, making it suitable for handling resource-intensive media downloads without blocking the main application thread. + +## Endpoint + +- **URL**: `/v1/BETA/media/download` +- **Method**: `POST` +- **Blueprint**: `v1_media_download_bp` + +## Request + +### Headers + +- `x-api-key`: Required for authentication (handled by the `@authenticate` decorator) + +### Body Parameters + +#### Required Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `media_url` | string (URI format) | The URL of the media to download | + +#### Optional Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `webhook_url` | string (URI format) | URL to receive the result when processing is complete | +| `id` | string | Custom identifier for tracking the request | +| `cookie` | string | Path to cookie file, URL to cookie file, or cookie string in Netscape format | +| `cloud_upload` | boolean | When true (default), the downloaded media will be uploaded to cloud storage and a cloud URL will be returned. When false, the direct download URL of the media will be returned instead. | + +#### Format Options (Optional) + +```json +"format": { + "quality": "string", // Quality specification (e.g., "best") + "format_id": "string", // Specific format ID + "resolution": "string", // Resolution specification (e.g., "720p") + "video_codec": "string", // Video codec preference + "audio_codec": "string" // Audio codec preference +} +``` + +#### Audio Options (Optional) + +```json +"audio": { + "extract": boolean, // Whether to extract audio + "format": "string", // Audio format (e.g., "mp3", "m4a") + "quality": "string" // Audio quality specification +} +``` + +#### Thumbnail Options (Optional) + +```json +"thumbnails": { + "download": boolean, // Whether to download thumbnails + "download_all": boolean, // Whether to download all available thumbnails + "formats": ["string"], // Array of thumbnail formats to download + "convert": boolean, // Whether to convert thumbnails + "embed_in_audio": boolean // Whether to embed thumbnails in audio files +} +``` + +#### Subtitle Options (Optional) + +```json +"subtitles": { + "download": boolean, // Whether to download subtitles + "languages": ["string"], // Array of language codes for subtitles + "format": "string", // Subtitle format to download (e.g., 'srt', 'vtt', 'json3') + "cloud_upload": boolean // Whether to upload subtitles to cloud storage (defaults to true) +} +``` + +#### Download Options (Optional) + +```json +"download": { + "max_filesize": integer, // Maximum file size in bytes + "rate_limit": "string", // Download rate limit (e.g., "50K") + "retries": integer // Number of download retry attempts +} +``` + +### Example Request + +```json +{ + "media_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "webhook_url": "https://example.com/webhook", + "id": "custom-request-123", + "cookie": "# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tFALSE\t0\tCONSENT\tYES+cb", + "cloud_upload": true, + "format": { + "quality": "best", + "resolution": "720p" + }, + "audio": { + "extract": true, + "format": "mp3" + }, + "thumbnails": { + "download": true + }, + "subtitles": { + "download": true, + "languages": ["en", "es-419"], + "format": "srt", + "cloud_upload": true + } +} +``` + +### Example cURL Command + +```bash +curl -X POST \ + https://api.example.com/v1/BETA/media/download \ + -H 'Content-Type: application/json' \ + -H 'x-api-key: your-api-key-here' \ + -d '{ + "media_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "webhook_url": "https://example.com/webhook", + "id": "custom-request-123", + "cookie": "# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tFALSE\t0\tCONSENT\tYES+cb", + "cloud_upload": true, + "format": { + "quality": "best", + "resolution": "720p" + }, + "audio": { + "extract": true, + "format": "mp3" + }, + "thumbnails": { + "download": true + }, + "subtitles": { + "download": true, + "languages": ["en", "es-419"], + "format": "srt", + "cloud_upload": true + } + }' +``` + +## Response + +### Immediate Response (When Using Webhook) + +When a webhook URL is provided, the API will queue the task and return an immediate response with a 202 status code: + +```json +{ + "code": 202, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "processing", + "pid": 12345, + "queue_id": 67890, + "max_queue_length": "unlimited", + "queue_length": 3, + "build_number": "1.0.123" +} +``` + +### Success Response (When Not Using Webhook or When Webhook Is Called) + +```json +{ + "code": 200, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "response": { + "media": { + "media_url": "https://storage.example.com/media/video-123.mp4", + "title": "Never Gonna Give You Up", + "format_id": "22", + "ext": "mp4", + "resolution": "720p", + "filesize": 12345678, + "width": 1280, + "height": 720, + "fps": 30, + "video_codec": "avc1.4d401f", + "audio_codec": "mp4a.40.2", + "upload_date": "20090325", + "duration": 212, + "view_count": 1234567890, + "uploader": "Rick Astley", + "uploader_id": "RickAstleyVEVO", + "description": "Official music video for Rick Astley - Never Gonna Give You Up" + }, + "thumbnails": [ + { + "id": "default", + "image_url": "https://storage.example.com/media/thumbnail-123.jpg", + "width": 1280, + "height": 720, + "original_format": "jpg", + "converted": false + } + ] + }, + "message": "success", + "pid": 12345, + "queue_id": 67890, + "run_time": 5.123, + "queue_time": 0.456, + "total_time": 5.579, + "queue_length": 2, + "build_number": "1.0.123" +} +``` + +### Error Responses + +#### Invalid Request (400) + +```json +{ + "code": 400, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "Invalid request: 'media_url' is a required property", + "pid": 12345, + "queue_id": 67890, + "queue_length": 2, + "build_number": "1.0.123" +} +``` + +#### Authentication Error (401) + +```json +{ + "code": 401, + "message": "Invalid API key", + "build_number": "1.0.123" +} +``` + +#### Queue Full (429) + +```json +{ + "code": 429, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "MAX_QUEUE_LENGTH (100) reached", + "pid": 12345, + "queue_id": 67890, + "queue_length": 100, + "build_number": "1.0.123" +} +``` + +#### Server Error (500) + +```json +{ + "code": 500, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "Error during download process - HTTP Error 403: Forbidden", + "pid": 12345, + "queue_id": 67890, + "queue_length": 2, + "build_number": "1.0.123" +} +``` + +## Error Handling + +The endpoint handles various error scenarios: + +- **Missing Required Parameters**: Returns a 400 status code with details about the missing parameter +- **Invalid Parameter Format**: Returns a 400 status code if parameters don't match the expected format +- **Authentication Failures**: Returns a 401 status code if the API key is invalid or missing +- **Queue Limits**: Returns a 429 status code if the task queue is full (when MAX_QUEUE_LENGTH is set) +- **Download Failures**: Returns a 500 status code with details about the download failure +- **Media Source Errors**: Returns a 500 status code if the media source is unavailable or restricted + +## Usage Notes + +1. **Webhook Handling**: + - When providing a `webhook_url`, the request will be queued and processed asynchronously + - Without a `webhook_url`, the request will be processed synchronously, which may lead to longer response times + +2. **Format Selection**: + - The `format` options allow fine-grained control over the downloaded media quality + - When multiple format options are specified, they are combined with a '+' separator + +3. **Audio Extraction**: + - Setting `audio.extract` to `true` will extract audio from the media + - Specify `audio.format` to control the output audio format (e.g., "mp3", "m4a") + +4. **Thumbnail Handling**: + - When `thumbnails.download` is `true`, the API will download and provide URLs for thumbnails + - Use `thumbnails.download_all` to retrieve all available thumbnails + +5. **Rate Limiting**: + - Use `download.rate_limit` to control download speed (e.g., "50K" for 50 KB/s) + - This can help prevent IP blocking from some media sources + +## Common Issues + +1. **Geo-restricted Content**: Some media may be unavailable in certain regions +2. **Rate Limiting**: Media sources may rate-limit or block frequent downloads +3. **Large File Downloads**: Very large files may time out during download +4. **Format Availability**: Not all requested formats may be available for all media sources +5. **Webhook Failures**: If the webhook URL is unreachable, you won't receive the final result +6. **Queue Overflow**: Requests may be rejected if the processing queue is full + +## Best Practices + +1. **Use Webhooks for Large Downloads**: Always use webhooks for potentially large or slow downloads to avoid timeout issues +2. **Specify Format Constraints**: Be specific about format requirements to avoid unnecessarily large downloads +3. **Handle Thumbnails Separately**: For efficiency, only request thumbnails when needed +4. **Implement Retry Logic**: Implement client-side retry logic for handling temporary failures +5. **Monitor Queue Length**: Check the `queue_length` in responses to gauge system load +6. **Use Reasonable Rate Limits**: Set appropriate `download.rate_limit` values to avoid being blocked by media sources +7. **Validate Media URLs**: Ensure media URLs are valid and accessible before submitting +8. **Store Downloaded Media**: The cloud URLs provided in responses may have expiration times, so download and store important media promptly \ No newline at end of file diff --git a/docs/media/feedback.md b/docs/media/feedback.md new file mode 100644 index 0000000000000000000000000000000000000000..0620e3fe4f89b70ad327cc63513f5adfc6e0c17a --- /dev/null +++ b/docs/media/feedback.md @@ -0,0 +1,44 @@ +# Media Feedback Portal + +This endpoint serves a static web page for collecting media feedback. + +## Endpoint + +``` +GET /v1/media/feedback +``` + +### Authentication + +This endpoint does not require authentication and is publicly accessible. + +### Response + +Returns the HTML feedback form page. + +## Static Files + +Additional static files (CSS, JavaScript, images) can be accessed at: + +``` +GET /v1/media/feedback/ +``` + +Replace `` with the path to the static resource relative to the static directory. + +## Development + +The static website files are stored in: + +``` +services/v1/media/feedback/static/ +``` + +This directory contains: + +- `index.html` - Main HTML file +- `css/styles.css` - Stylesheet +- `js/script.js` - JavaScript code +- `images/` - Directory for image assets + +To modify the feedback page, edit these files directly. \ No newline at end of file diff --git a/docs/media/generate_ass.md b/docs/media/generate_ass.md new file mode 100644 index 0000000000000000000000000000000000000000..760476ef6f8884946f49d19d29fa4cb384fc531b --- /dev/null +++ b/docs/media/generate_ass.md @@ -0,0 +1,350 @@ +# ASS Subtitle Generation Endpoint (v1) + +## 1. Overview + +The `/v1/media/generate/ass` endpoint is part of the Media API and is responsible for generating an ASS (Advanced SubStation Alpha) subtitle file from a media file (typically a video or audio). It accepts a media URL and various styling options for the subtitles. The endpoint utilizes the `generate_ass_captions_v1` service to generate the ASS file, which is then uploaded to cloud storage, and the cloud URL is returned in the response. + +## 2. Endpoint + +**URL:** `/v1/media/generate/ass` +**Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key`: Required. The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following properties: +> **Note:** `canvas_width` and `canvas_height` are recommended for audio files (e.g., MP3) to control the subtitle canvas size. + +- `media_url` (string, required): The URL of the media file (video or audio) to generate subtitles for. +- `canvas_width` (integer, optional): Subtitle canvas width in pixels. +- `canvas_height` (integer, optional): Subtitle canvas height in pixels. +- `settings` (object, optional): An object containing various styling options for the subtitles. See the schema below for available options. +- `replace` (array, optional): An array of objects with `find` and `replace` properties, specifying text replacements to be made in the subtitles. +- `exclude_time_ranges` (array, optional): List of time ranges to skip when generating subtitles. Each item must be an object with: + - `start`: (string, required) The start time of the excluded range, as a string timecode in `hh:mm:ss.ms` format (e.g., `00:01:23.456`). + - `end`: (string, required) The end time, as a string timecode in `hh:mm:ss.ms` format, which must be strictly greater than `start`. +- `language` (string, optional): The language code for the subtitles (e.g., "en", "fr"). Defaults to "auto". +- `webhook_url` (string, optional): A URL to receive a webhook notification when the subtitle generation process is complete. +- `id` (string, optional): An identifier for the request. + + + +#### Settings Schema + +```json +{ + "type": "object", + "properties": { + "line_color": {"type": "string"}, + "word_color": {"type": "string"}, + "outline_color": {"type": "string"}, + "all_caps": {"type": "boolean"}, + "max_words_per_line": {"type": "integer"}, + "x": {"type": "integer"}, + "y": {"type": "integer"}, + "position": { + "type": "string", + "enum": [ + "bottom_left", "bottom_center", "bottom_right", + "middle_left", "middle_center", "middle_right", + "top_left", "top_center", "top_right" + ] + }, + "alignment": { + "type": "string", + "enum": ["left", "center", "right"] + }, + "font_family": {"type": "string"}, + "font_size": {"type": "integer"}, + "bold": {"type": "boolean"}, + "italic": {"type": "boolean"}, + "underline": {"type": "boolean"}, + "strikeout": {"type": "boolean"}, + "style": { + "type": "string", + "enum": [ + "classic", // Regular subtitle with all text displayed at once + "karaoke", // Highlights words sequentially in a karaoke style + "highlight", // Shows full text but highlights the current word + "underline", // Shows full text but underlines the current word + "word_by_word" // Shows one word at a time + ] + }, + "outline_width": {"type": "integer"}, + "spacing": {"type": "integer"}, + "angle": {"type": "integer"}, + "shadow_offset": {"type": "integer"} + }, + "additionalProperties": false +} +``` + +### Example Requests + +#### Example 1: Basic Automatic Subtitle Generation +```json +{ + "media_url": "https://example.com/video.mp4" +} +``` +This minimal request will automatically transcribe the media and generate white subtitles at the bottom center. + +#### Example 2: Custom Styling +```json +{ + "media_url": "https://example.com/video.mp4", + "settings": { + "style": "classic", + "line_color": "#FFFFFF", + "outline_color": "#000000", + "position": "bottom_center", + "alignment": "center", + "font_family": "Arial", + "font_size": 24, + "bold": true + } +} +``` + +#### Example 3: Karaoke-Style Subtitles with Advanced Options +```json +{ + "media_url": "https://example.com/video.mp4", + "settings": { + "line_color": "#FFFFFF", + "word_color": "#FFFF00", + "outline_color": "#000000", + "all_caps": false, + "max_words_per_line": 10, + "position": "bottom_center", + "alignment": "center", + "font_family": "Arial", + "font_size": 24, + "bold": false, + "italic": false, + "style": "karaoke", + "outline_width": 2, + "shadow_offset": 2 + }, + "replace": [ + { + "find": "um", + "replace": "" + }, + { + "find": "like", + "replace": "" + } + ], + "webhook_url": "https://example.com/webhook", + "id": "request-123", + "language": "en" +} +``` + +#### Example 4: Excluding Time Ranges from Subtitle Generation +```json +{ + "media_url": "https://example.com/video.mp4", + "settings": { + "style": "classic", + "line_color": "#FFFFFF", + "outline_color": "#000000", + "position": "bottom_center", + "font_family": "Arial", + "font_size": 24 + }, + "exclude_time_ranges": [ + { "start": "00:00:10.000", "end": "00:00:20.000" }, + { "start": "00:00:30.000", "end": "00:00:40.000" } + ] +} +``` + +#### Example 5: Generating Subtitles for an MP3 (Audio) File +```json +{ + "canvas_width": 1280, + "canvas_height": 720, + "media_url": "https://example.com/audio.mp3", + "settings": { + "style": "classic", + "font_family": "Arial", + "font_size": 32, + "line_color": "#FFFFFF", + "outline_color": "#000000" + } +} +``` + + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "media_url": "https://example.com/video.mp4", + "settings": { + "line_color": "#FFFFFF", + "word_color": "#FFFF00", + "outline_color": "#000000", + "all_caps": false, + "max_words_per_line": 10, + "position": "bottom_center", + "alignment": "center", + "font_family": "Arial", + "font_size": 24, + "style": "karaoke", + "outline_width": 2 + }, + "replace": [ + { + "find": "um", + "replace": "" + } + ], + "id": "custom-request-id" + }' \ + https://your-api-endpoint.com/v1/media/generate/ass +``` + +## 4. Response + +### Success Response + +The response will be a JSON object with the following properties: + +- `code` (integer): The HTTP status code (200 for success). +- `id` (string): The request identifier, if provided in the request. +- `job_id` (string): A unique identifier for the job. +- `response` (string): The cloud URL of the generated ASS subtitle file. +- `message` (string): A success message. +- `pid` (integer): The process ID of the worker that processed the request. +- `queue_id` (integer): The ID of the queue used for processing the request. +- `run_time` (float): The time taken to process the request (in seconds). +- `queue_time` (float): The time the request spent in the queue (in seconds). +- `total_time` (float): The total time taken for the request (in seconds). +- `queue_length` (integer): The current length of the processing queue. +- `build_number` (string): The build number of the application. + +Example: + +```json +{ + "code": 200, + "id": "request-123", + "job_id": "d290f1ee-6c54-4b01-90e6-d701748f0851", + "response": "https://cloud.example.com/generated-subtitles.ass", + "message": "success", + "pid": 12345, + "queue_id": 140682639937472, + "run_time": 2.345, + "queue_time": 0.010, + "total_time": 2.355, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +#### Missing or Invalid Parameters + +**Status Code:** 400 Bad Request + +```json +{ + "code": 400, + "id": "request-123", + "job_id": "d290f1ee-6c54-4b01-90e6-d701748f0851", + "message": "Missing or invalid parameters", + "pid": 12345, + "queue_id": 140682639937472, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +#### Font Error + +**Status Code:** 400 Bad Request + +```json +{ + "code": 400, + "error": "The requested font 'InvalidFont' is not available. Please choose from the available fonts.", + "available_fonts": ["Arial", "Times New Roman", "Courier New", ...], + "pid": 12345, + "queue_id": 140682639937472, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +#### Internal Server Error + +**Status Code:** 500 Internal Server Error + +```json +{ + "code": 500, + "id": "request-123", + "job_id": "d290f1ee-6c54-4b01-90e6-d701748f0851", + "error": "An unexpected error occurred during the subtitle generation process.", + "pid": 12345, + "queue_id": 140682639937472, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +The endpoint handles the following common errors: + +- **Missing or Invalid Parameters**: If any required parameters are missing or invalid, a 400 Bad Request error is returned with a descriptive error message. +- **Font Error**: If the requested font is not available, a 400 Bad Request error is returned with a list of available fonts. +- **Internal Server Error**: If an unexpected error occurs during the subtitle generation process, a 500 Internal Server Error is returned with an error message. + +Additionally, the main application context (`app.py`) includes error handling for queue overload. If the maximum queue length (`MAX_QUEUE_LENGTH`) is set and the queue size reaches that limit, a 429 Too Many Requests error is returned with a descriptive message. + +## 6. Usage Notes + +- The `media_url` parameter must be a valid URL pointing to a video or audio file. +- The `settings` parameter allows for customization of the subtitle appearance and behavior: + - `style` determines how subtitles are displayed, with options including: + - `classic`: Regular subtitle with all text displayed at once + - `karaoke`: Highlights words sequentially in a karaoke style as they're spoken + - `highlight`: Shows the full subtitle text but highlights each word as it's spoken + - `underline`: Shows the full subtitle text but underlines each word as it's spoken + - `word_by_word`: Shows only one word at a time + - `position` can be used to place subtitles in one of nine positions on the screen + - `alignment` determines text alignment within the position (left, center, right) + - `font_family` can be any available system font + - Color options can be set using hex codes (e.g., "#FFFFFF" for white) +- The `replace` parameter can be used to perform text replacements in the subtitles (useful for correcting words or censoring content). +- The `webhook_url` parameter is optional and can be used to receive a notification when the subtitle generation process is complete. +- The `id` parameter is optional and can be used to identify the request in webhook responses. +- The `language` parameter is optional and can be used to specify the language of the subtitles for transcription. If not provided, the language will be automatically detected. +- The `exclude_time_ranges` parameter can be used to specify time ranges to be excluded from subtitle generation. +- If either `canvas_width` or `canvas_height` is provided, both must be provided and must be greater than 0. + +## 7. Common Issues + +- Providing an invalid or inaccessible `media_url`. +- Requesting an unavailable font in the `settings` object. +- Using this endpoint with an audio-only file (e.g., MP3) and not providing both `canvas_width` and `canvas_height`. For audio files, you must specify both dimensions to generate a valid ASS subtitle file. +- Exceeding the maximum queue length, resulting in a 429 Too Many Requests error. + +## 8. Best Practices + +- Validate the `media_url` parameter before sending the request to ensure it points to a valid and accessible media file. +- Use the `webhook_url` parameter to receive notifications about the subtitle generation process, rather than polling the API for updates. +- Provide descriptive and meaningful `id` values to easily identify requests in logs and responses. +- Use the `replace` parameter judiciously to avoid unintended text replacements in the subtitles. +- Consider caching the generated ASS files for frequently requested media to improve performance and reduce processing time. diff --git a/docs/media/media_transcribe.md b/docs/media/media_transcribe.md new file mode 100644 index 0000000000000000000000000000000000000000..7971584860d4c4473a07ee0ad26ba83fdf9d51f5 --- /dev/null +++ b/docs/media/media_transcribe.md @@ -0,0 +1,270 @@ +# Media Transcription API Documentation + +## Overview +The Media Transcription endpoint is part of the v1 API suite, providing audio/video transcription and translation capabilities. This endpoint leverages a queuing system for handling long-running transcription tasks, with webhook support for asynchronous processing. It's integrated into the main Flask application as a Blueprint and supports both direct response and cloud storage options for the transcription results. + +## Endpoint +- **URL**: `/v1/media/transcribe` +- **Method**: `POST` +- **Blueprint**: `v1_media_transcribe_bp` + +## Request + +### Headers +- `x-api-key`: Required. Authentication key for API access. +- `Content-Type`: Required. Must be `application/json`. + +### Body Parameters + +#### Required Parameters +- `media_url` (string) + - Format: URI + - Description: URL of the media file to be transcribed + +#### Optional Parameters +- `task` (string) + - Allowed values: `"transcribe"`, `"translate"` + - Default: `"transcribe"` + - Description: Specifies whether to transcribe or translate the audio + +- `include_text` (boolean) + - Default: `true` + - Description: Include plain text transcription in the response + +- `include_srt` (boolean) + - Default: `false` + - Description: Include SRT format subtitles in the response + +- `include_segments` (boolean) + - Default: `false` + - Description: Include timestamped segments in the response + +- `word_timestamps` (boolean) + - Default: `false` + - Description: Include timestamps for individual words + +- `response_type` (string) + - Allowed values: `"direct"`, `"cloud"` + - Default: `"direct"` + - Description: Whether to return results directly or as cloud storage URLs + +- `language` (string) + - Optional + - Description: Source language code for transcription + +- `webhook_url` (string) + - Format: URI + - Description: URL to receive the transcription results asynchronously + +- `id` (string) + - Description: Custom identifier for the transcription job + +- `max_words_per_line` (integer) + - Minimum: 1 + - Description: Controls the maximum number of words per line in the SRT file. When specified, each segment's text will be split into multiple lines with at most the specified number of words per line. + +### Example Request + +```bash +curl -X POST "https://api.example.com/v1/media/transcribe" \ + -H "x-api-key: your_api_key" \ + -H "Content-Type: application/json" \ + -d '{ + "media_url": "https://example.com/media/file.mp3", + "task": "transcribe", + "include_text": true, + "include_srt": true, + "include_segments": true, + "response_type": "cloud", + "webhook_url": "https://your-webhook.com/callback", + "id": "custom-job-123", + "max_words_per_line": 5 + }' +``` + +## Response + +### Immediate Response (202 Accepted) +When a webhook URL is provided, the API returns an immediate acknowledgment: + +```json +{ + "code": 202, + "id": "custom-job-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "processing", + "pid": 12345, + "queue_id": 67890, + "max_queue_length": "unlimited", + "queue_length": 1, + "build_number": "1.0.0" +} +``` + +### Success Response (via Webhook) +For direct response_type: + +```json +{ + "endpoint": "/v1/transcribe/media", + "code": 200, + "id": "custom-job-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "response": { + "text": "Transcribed text content...", + "srt": "SRT formatted content...", + "segments": [...], + "text_url": null, + "srt_url": null, + "segments_url": null + }, + "message": "success", + "pid": 12345, + "queue_id": 67890, + "run_time": 5.234, + "queue_time": 0.123, + "total_time": 5.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +For cloud response_type: + +```json +{ + "endpoint": "/v1/transcribe/media", + "code": 200, + "id": "custom-job-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "response": { + "text": null, + "srt": null, + "segments": null, + "text_url": "https://storage.example.com/text.txt", + "srt_url": "https://storage.example.com/subtitles.srt", + "segments_url": "https://storage.example.com/segments.json" + }, + "message": "success", + "pid": 12345, + "queue_id": 67890, + "run_time": 5.234, + "queue_time": 0.123, + "total_time": 5.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +#### Queue Full (429 Too Many Requests) +```json +{ + "code": 429, + "id": "custom-job-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "MAX_QUEUE_LENGTH (100) reached", + "pid": 12345, + "queue_id": 67890, + "queue_length": 100, + "build_number": "1.0.0" +} +``` + +#### Server Error (500 Internal Server Error) +```json +{ + "endpoint": "/v1/transcribe/media", + "code": 500, + "id": "custom-job-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "response": null, + "message": "Error message details", + "pid": 12345, + "queue_id": 67890, + "run_time": 0.123, + "queue_time": 0.056, + "total_time": 0.179, + "queue_length": 1, + "build_number": "1.0.0" +} +``` + +## Error Handling + +### Common Errors +- **Invalid API Key**: 401 Unauthorized +- **Invalid JSON Payload**: 400 Bad Request +- **Missing Required Fields**: 400 Bad Request +- **Invalid media_url**: 400 Bad Request +- **Queue Full**: 429 Too Many Requests +- **Processing Error**: 500 Internal Server Error + +### Validation Errors +The endpoint performs strict validation of the request payload using JSON Schema. Common validation errors include: +- Invalid URI format for media_url or webhook_url +- Invalid task value (must be "transcribe" or "translate") +- Invalid response_type value (must be "direct" or "cloud") +- Unknown properties in the request body + +## Usage Notes + +1. **Webhook Processing** + - When a webhook_url is provided, the request is processed asynchronously + - The API returns an immediate 202 response with a job_id + - Final results are sent to the webhook_url when processing completes + +2. **Queue Management** + - Requests with webhook_url are queued for processing + - MAX_QUEUE_LENGTH environment variable controls queue size + - Set MAX_QUEUE_LENGTH to 0 for unlimited queue size + +3. **File Management** + - For cloud response_type, temporary files are automatically cleaned up + - Results are uploaded to cloud storage before deletion + - URLs in the response provide access to the stored files + +4. **SRT Formatting** + - The `max_words_per_line` parameter allows control over the maximum number of words per line in the SRT file + - When specified, each segment's text will be split into multiple lines with at most the specified number of words per line + - This is useful for creating more readable subtitles with consistent line lengths + +## Common Issues + +1. **Media Access** + - Ensure media_url is publicly accessible + - Verify media file format is supported + - Check for media file corruption + +2. **Webhook Delivery** + - Ensure webhook_url is publicly accessible + - Implement webhook endpoint retry logic + - Monitor webhook endpoint availability + +3. **Resource Usage** + - Large media files may take significant processing time + - Monitor queue length for production deployments + - Consider implementing request size limits + +## Best Practices + +1. **Request Handling** + - Always provide a unique id for job tracking + - Implement webhook retry logic + - Store job_id for result correlation + +2. **Resource Management** + - Monitor queue length in production + - Implement appropriate timeout handling + - Use cloud response_type for large files + +3. **Error Handling** + - Implement comprehensive webhook error handling + - Log job_id with all related operations + - Monitor processing times and error rates + +4. **Security** + - Use HTTPS for media_url and webhook_url + - Implement webhook authentication + - Validate media file types before processing \ No newline at end of file diff --git a/docs/media/metadata.md b/docs/media/metadata.md new file mode 100644 index 0000000000000000000000000000000000000000..cb9f0df3e3a57211c0a629dc5ec63a1733df9730 --- /dev/null +++ b/docs/media/metadata.md @@ -0,0 +1,156 @@ +# Media Metadata + +This endpoint extracts detailed metadata from media files (video, audio, image) including format, duration, codec information, resolution, and bitrates. + +## Endpoint + +`POST /v1/media/metadata` + +## Authentication + +This endpoint requires API authentication. See [Authentication](../toolkit/authenticate.md) for details. + +## Request + +```json +{ + "media_url": "https://example.com/media.mp4", + "webhook_url": "https://example.com/webhook", // Optional + "id": "custom-id" // Optional +} +``` + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| media_url | string | Yes | URL of the media file to analyze | +| webhook_url | string | No | URL to receive the processing result | +| id | string | No | Custom identifier for tracking the request | + +## Response + +**Success (200 OK)** + +```json +{ + "code": 200, + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "id": "custom-id", + "response": { + "filesize": 15679283, + "filesize_mb": 14.95, + "duration": 87.46, + "duration_formatted": "00:01:27.46", + "format": "mp4,mov,m4a,3gp,3g2,mj2", + "overall_bitrate": 1438692, + "overall_bitrate_mbps": 1.44, + "has_video": true, + "video_codec": "h264", + "video_codec_long": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", + "width": 1920, + "height": 1080, + "resolution": "1920x1080", + "fps": 30.0, + "video_bitrate": 1300000, + "video_bitrate_mbps": 1.3, + "pixel_format": "yuv420p", + "has_audio": true, + "audio_codec": "aac", + "audio_codec_long": "AAC (Advanced Audio Coding)", + "audio_channels": 2, + "audio_sample_rate": 48000, + "audio_sample_rate_khz": 48.0, + "audio_bitrate": 128000, + "audio_bitrate_kbps": 128 + }, + "message": "success", + "run_time": 0.542, + "queue_time": 0, + "total_time": 0.542, + "pid": 12345, + "queue_id": 67890, + "queue_length": 0, + "build_number": "123" +} +``` + +For audio-only files, video-related fields will not be included. Similarly, for video files without audio, audio-related fields will not be included. + +**Queued (202 Accepted)** + +```json +{ + "code": 202, + "id": "custom-id", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "processing", + "pid": 12345, + "queue_id": 67890, + "max_queue_length": "unlimited", + "queue_length": 0, + "build_number": "123" +} +``` + +**Error (4xx/5xx)** + +```json +{ + "code": 500, + "id": "custom-id", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "Error extracting metadata: [error details]", + "pid": 12345, + "queue_id": 67890, + "queue_length": 0, + "build_number": "123" +} +``` + +## Example + +### Request + +```bash +curl -X POST https://api.example.com/v1/media/metadata \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer your_api_key" \ + -d '{ + "media_url": "https://example.com/sample-video.mp4", + "webhook_url": "https://your-server.com/webhook" + }' +``` + +### Response + +```json +{ + "code": 200, + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "response": { + "filesize": 15679283, + "filesize_mb": 14.95, + "duration": 87.46, + "duration_formatted": "00:01:27.46", + "format": "mp4", + "overall_bitrate": 1438692, + "overall_bitrate_mbps": 1.44, + "has_video": true, + "video_codec": "h264", + "width": 1920, + "height": 1080, + "resolution": "1920x1080", + "fps": 30.0, + "video_bitrate": 1300000, + "video_bitrate_mbps": 1.3, + "has_audio": true, + "audio_codec": "aac", + "audio_channels": 2, + "audio_sample_rate": 48000, + "audio_bitrate": 128000, + "audio_bitrate_kbps": 128 + }, + "message": "success", + "run_time": 0.542, + "total_time": 0.542 +} +``` \ No newline at end of file diff --git a/docs/media/silence.md b/docs/media/silence.md new file mode 100644 index 0000000000000000000000000000000000000000..b8d059b6eb17aceb8b23cfb46dcb8c07d451ad10 --- /dev/null +++ b/docs/media/silence.md @@ -0,0 +1,176 @@ +# Silence Detection Endpoint + +## 1. Overview + +The `/v1/media/silence` endpoint is part of the Media API and is designed to detect silence intervals in a given media file. It takes a media URL, along with various parameters for configuring the silence detection process, and returns the detected silence intervals. This endpoint fits into the overall API structure as a part of the version 1 (v1) media-related endpoints. + +## 2. Endpoint + +``` +POST /v1/media/silence +``` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body should be a JSON object with the following parameters: + +- `media_url` (required, string): The URL of the media file to be processed. +- `start` (optional, string): The start time for the silence detection process, in the format `HH:MM:SS.ms`. If not provided, the process will start from the beginning of the media file. +- `end` (optional, string): The end time for the silence detection process, in the format `HH:MM:SS.ms`. If not provided, the process will continue until the end of the media file. +- `noise` (optional, string): The noise threshold for silence detection, in decibels (dB). Default is `-30dB`. +- `duration` (required, number): The minimum duration (in seconds) for a silence interval to be considered valid. +- `mono` (optional, boolean): Whether to process the audio as mono (single channel) or not. Default is `true`. +- `webhook_url` (required, string): The URL to which the response should be sent as a webhook. +- `id` (required, string): A unique identifier for the request. + +The `validate_payload` directive in the routes file enforces the following JSON schema for the request body: + +```python +{ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "start": {"type": "string"}, + "end": {"type": "string"}, + "noise": {"type": "string"}, + "duration": {"type": "number", "minimum": 0.1}, + "mono": {"type": "boolean"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["media_url", "duration"], + "additionalProperties": False +} +``` + +### Example Request + +```json +{ + "media_url": "https://example.com/audio.mp3", + "start": "00:00:10.0", + "end": "00:01:00.0", + "noise": "-25dB", + "duration": 0.5, + "mono": false, + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +} +``` + +``` +curl -X POST \ + https://api.example.com/v1/media/silence \ + -H 'x-api-key: YOUR_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{ + "media_url": "https://example.com/audio.mp3", + "start": "00:00:10.0", + "end": "00:01:00.0", + "noise": "-25dB", + "duration": 0.5, + "mono": false, + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +}' +``` + +## 4. Response + +### Success Response + +The success response will be sent as a webhook to the specified `webhook_url`. The response format follows the general response structure defined in the main application context (`app.py`). Here's an example: + +```json +{ + "endpoint": "/v1/media/silence", + "code": 200, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": [ + { + "start": 10.5, + "end": 15.2 + }, + { + "start": 20.0, + "end": 25.7 + } + ], + "message": "success", + "pid": 12345, + "queue_id": 1234567890, + "run_time": 1.234, + "queue_time": 0.123, + "total_time": 1.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +- **400 Bad Request**: This error is returned when the request body is missing or contains invalid parameters. Example response: + +```json +{ + "code": 400, + "message": "Invalid request payload" +} +``` + +- **401 Unauthorized**: This error is returned when the `x-api-key` header is missing or invalid. Example response: + +```json +{ + "code": 401, + "message": "Unauthorized" +} +``` + +- **500 Internal Server Error**: This error is returned when an unexpected error occurs during the silence detection process. Example response: + +```json +{ + "code": 500, + "message": "An error occurred during the silence detection process" +} +``` + +## 5. Error Handling + +The endpoint handles the following common errors: + +- Missing or invalid request parameters: Returns a 400 Bad Request error. +- Missing or invalid `x-api-key` header: Returns a 401 Unauthorized error. +- Unexpected exceptions during the silence detection process: Returns a 500 Internal Server Error. + +The main application context (`app.py`) also includes error handling for situations where the task queue has reached its maximum length (`MAX_QUEUE_LENGTH`). In such cases, a 429 Too Many Requests error is returned. + +## 6. Usage Notes + +- The `media_url` parameter should point to a valid media file that can be processed by the silence detection service. +- The `start` and `end` parameters are optional and can be used to specify a time range within the media file for silence detection. +- The `noise` parameter allows you to adjust the noise threshold for silence detection. Lower values (e.g., `-40dB`) will detect more silence intervals, while higher values (e.g., `-20dB`) will detect fewer silence intervals. +- The `duration` parameter specifies the minimum duration (in seconds) for a silence interval to be considered valid. This can be useful for filtering out very short silence intervals that may not be relevant. +- The `mono` parameter determines whether the audio should be processed as a single channel (mono) or multiple channels (stereo or surround). + +## 7. Common Issues + +- Providing an invalid or inaccessible `media_url`. +- Specifying `start` and `end` times that are outside the duration of the media file. +- Setting the `duration` parameter to an unreasonably low value, which may result in detecting too many short silence intervals. + +## 8. Best Practices + +- Validate the `media_url` parameter to ensure it points to a valid and accessible media file. +- Consider using the `start` and `end` parameters to focus the silence detection on a specific time range within the media file, if needed. +- Adjust the `noise` and `duration` parameters based on your specific use case and requirements for silence detection. +- If you need to process stereo or surround audio, set the `mono` parameter to `false`. +- Monitor the response from the endpoint to ensure that the silence detection process completed successfully and that the detected silence intervals meet your expectations. \ No newline at end of file diff --git a/docs/s3/upload.md b/docs/s3/upload.md new file mode 100644 index 0000000000000000000000000000000000000000..824e54cce52588b8bacecb562d696f56c745816d --- /dev/null +++ b/docs/s3/upload.md @@ -0,0 +1,66 @@ +# S3 Upload API + +This endpoint allows you to stream a file from a remote URL directly to an S3-compatible storage service without using local disk space. + +## Endpoint + +`POST /v1/s3/upload` + +## Authentication + +This endpoint requires an API key to be provided in the `X-API-Key` header. + +## Request Body + +The request body should be a JSON object with the following properties: + +| Property | Type | Required | Description | +|----------|------|----------|-------------| +| file_url | string | Yes | The URL of the file to upload to S3 | +| filename | string | No | Custom filename to use for the uploaded file. If not provided, the original filename will be used | +| public | boolean | No | Whether to make the file publicly accessible. Defaults to `false` | + +Example request body: +```json +{ + "file_url": "https://example.com/path/to/file.mp4", + "filename": "custom-name.mp4", + "public": true +} +``` + +## Response + +The response will be a JSON object with the following properties: + +| Property | Type | Description | +|----------|------|-------------| +| url | string | The URL of the uploaded file. For public files, this is a direct URL. For private files, this is a pre-signed URL that will expire after 1 hour | +| filename | string | The filename of the uploaded file | +| bucket | string | The name of the S3 bucket where the file was uploaded | +| public | boolean | Whether the file is publicly accessible | + +Example response: +```json +{ + "url": "https://bucket-name.s3.region.amazonaws.com/custom-name.mp4", + "filename": "custom-name.mp4", + "bucket": "bucket-name", + "public": true +} +``` + +## Error Handling + +If an error occurs, the response will include an error message with an appropriate HTTP status code. + +## Technical Details + +This endpoint uses the S3-compatible multipart upload API to stream the file directly from the source URL to S3 without saving it locally. This allows for efficient transfer of large files with minimal memory usage. + +The implementation: +1. Streams the file from the source URL in chunks +2. Uploads each chunk to S3 as a part of a multipart upload +3. Completes the multipart upload once all parts are uploaded + +This approach supports resumable uploads and can handle large files efficiently. \ No newline at end of file diff --git a/docs/toolkit/authenticate.md b/docs/toolkit/authenticate.md new file mode 100644 index 0000000000000000000000000000000000000000..0bfcfb5907fbdc33163e7be79c9103376dff7434 --- /dev/null +++ b/docs/toolkit/authenticate.md @@ -0,0 +1,92 @@ +# Authenticate Endpoint + +## 1. Overview + +The `/v1/toolkit/authenticate` endpoint is a part of the `v1_toolkit_auth` blueprint in the API structure. Its purpose is to authenticate requests by verifying the provided API key against a predefined value. This endpoint serves as a gatekeeper, ensuring that only authorized clients can access the API's resources. + +## 2. Endpoint + +- URL Path: `/v1/toolkit/authenticate` +- HTTP Method: `GET` + +## 3. Request + +### Headers + +- `X-API-Key` (required): The API key used for authentication. + +### Body Parameters + +This endpoint does not require any request body parameters. + +### Example Request + +```bash +curl -X GET -H "X-API-Key: YOUR_API_KEY" http://localhost:8080/v1/toolkit/authenticate +``` + +## 4. Response + +### Success Response + +If the provided API key matches the predefined value, the endpoint will return a 200 OK status code with the following response: + +```json +{ + "code": 200, + "endpoint": "/authenticate", + "id": null, + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "success", + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "response": "Authorized", + "run_time": 0.001, + "total_time": 0.001, + "queue_time": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +If the provided API key is invalid or missing, the endpoint will return a 401 Unauthorized status code with the following response: + +```json +{ + "code": 401, + "endpoint": "/authenticate", + "id": null, + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "Unauthorized", + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "response": null, + "run_time": 0.001, + "total_time": 0.001, + "queue_time": 0, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +The main error that can occur with this endpoint is providing an invalid or missing API key. In this case, the endpoint will return a 401 Unauthorized status code with an appropriate error message. + +## 6. Usage Notes + +- This endpoint is designed to be used as a gatekeeper for the API, ensuring that only authorized clients can access the API's resources. +- The API key should be kept secure and should not be shared with unauthorized parties. + +## 7. Common Issues + +- Forgetting to include the `X-API-Key` header in the request. +- Using an invalid or expired API key. + +## 8. Best Practices + +- Rotate API keys periodically to enhance security. +- Store API keys securely and avoid committing them to version control systems. +- Consider implementing additional security measures, such as rate limiting or IP whitelisting, to further protect the API. \ No newline at end of file diff --git a/docs/toolkit/job_status.md b/docs/toolkit/job_status.md new file mode 100644 index 0000000000000000000000000000000000000000..c855ec7d0c975fd40ce62b7298315b2e3c2d8c25 --- /dev/null +++ b/docs/toolkit/job_status.md @@ -0,0 +1,141 @@ +# Job Status Endpoint Documentation + +## 1. Overview + +The `/v1/toolkit/job/status` endpoint is part of the Toolkit API and is used to retrieve the status of a specific job. It fits into the overall API structure as a utility endpoint for monitoring and managing jobs submitted to the various media processing endpoints. + +## 2. Endpoint + +**URL Path:** `/v1/toolkit/job/status` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following parameter: + +- `job_id` (string, required): The unique identifier of the job for which the status is requested. + +The `validate_payload` directive in the routes file enforces the following JSON schema for the request body: + +```python +{ + "type": "object", + "properties": { + "job_id": { + "type": "string" + } + }, + "required": ["job_id"], +} +``` + +### Example Request + +```json +{ + "job_id": "e6d7f3c0-9c9f-4b8a-b7c3-f0e3c9f6b9d7" +} +``` + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"job_id": "e6d7f3c0-9c9f-4b8a-b7c3-f0e3c9f6b9d7"}' \ + http://your-api-endpoint/v1/toolkit/job/status +``` + +## 4. Response + +### Success Response + +The success response will contain the job status file content directly, as shown in the example response from `app.py`: + +```json +{ + "endpoint": "/v1/toolkit/job/status", + "code": 200, + "id": null, + "job_id": "e6d7f3c0-9c9f-4b8a-b7c3-f0e3c9f6b9d7", + "response": { + "job_status": "done", + "job_id": "e6d7f3c0-9c9f-4b8a-b7c3-f0e3c9f6b9d7", + "queue_id": 140368864456064, + "process_id": 123456, + "response": { + "endpoint": "/v1/media/transcribe", + "code": 200, + "id": "transcribe_job_123", + "job_id": "e6d7f3c0-9c9f-4b8a-b7c3-f0e3c9f6b9d7", + "response": "Transcription completed successfully.", + "message": "success", + "pid": 123456, + "queue_id": 140368864456064, + "run_time": 5.234, + "queue_time": 1.123, + "total_time": 6.357, + "queue_length": 0, + "build_number": "1.0.0" + } + }, + "message": "success", + "pid": 123456, + "queue_id": 140368864456064, + "run_time": 0.001, + "queue_time": 0.0, + "total_time": 0.001, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +- **404 Not Found**: If the job with the provided `job_id` is not found, the response will be: + +```json +{ + "error": "Job not found", + "job_id": "e6d7f3c0-9c9f-4b8a-b7c3-f0e3c9f6b9d7" +} +``` + +- **500 Internal Server Error**: If an unexpected error occurs while retrieving the job status, the response will be: + +```json +{ + "error": "Failed to retrieve job status: ", + "code": 500 +} +``` + +## 5. Error Handling + +- **Missing or Invalid Parameters**: If the `job_id` parameter is missing or invalid, the request will be rejected with a 400 Bad Request error. +- **Job Not Found**: If the job with the provided `job_id` is not found, a 404 Not Found error will be returned. +- **Unexpected Errors**: Any unexpected errors that occur during the retrieval of the job status will result in a 500 Internal Server Error response. + +The main application context (`app.py`) includes error handling for queue overflow situations, where a 429 Too Many Requests error is returned if the maximum queue length is reached. + +## 6. Usage Notes + +- Ensure that you have a valid API key for authentication. +- The `job_id` parameter must be a valid UUID string representing an existing job. +- This endpoint does not perform any media processing; it only retrieves the status of a previously submitted job. + +## 7. Common Issues + +- Providing an invalid or non-existent `job_id`. +- Attempting to retrieve the status of a job that has already been processed and removed from the system. + +## 8. Best Practices + +- Use this endpoint to monitor the progress of long-running jobs or to check the status of completed jobs. +- Implement proper error handling in your client application to handle different error scenarios, such as job not found or unexpected errors. +- Consider rate-limiting or implementing a queue system on the client side to avoid overwhelming the API with too many requests. \ No newline at end of file diff --git a/docs/toolkit/jobs_status.md b/docs/toolkit/jobs_status.md new file mode 100644 index 0000000000000000000000000000000000000000..1a19cf322702ef9e2b6e0562403077a20035a6d8 --- /dev/null +++ b/docs/toolkit/jobs_status.md @@ -0,0 +1,141 @@ +# Get All Jobs Status + +## 1. Overview + +The `/v1/toolkit/jobs/status` endpoint is part of the Toolkit API and is used to retrieve the status of all jobs within a specified time range. This endpoint fits into the overall API structure by providing a way to monitor and manage the jobs that have been submitted to the system. It is a part of the `v1_toolkit_jobs_status_bp` blueprint, which is registered in the main `app.py` file. + +## 2. Endpoint + +**URL Path:** `/v1/toolkit/jobs/status` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +- `since_seconds` (optional, number): The number of seconds to look back for jobs. If not provided, the default value is 600 seconds (10 minutes). + +The JSON payload is completely optional. If no payload is provided or if the payload is empty, the endpoint will use the default value of 600 seconds. + +### Example Request + +```json +{ + "since_seconds": 3600 +} +``` + +Or with no body: + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + http://your-api-url/v1/toolkit/jobs/status +``` + +With body: + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"since_seconds": 3600}' \ + http://your-api-url/v1/toolkit/jobs/status +``` + +## 4. Response + +### Success Response + +The response will be a JSON object containing the job statuses for all jobs within the specified time range. The response format follows the general response structure defined in `app.py`. + +```json +{ + "code": 200, + "id": null, + "job_id": "job_id_value", + "response": { + "job_id_1": "job_status_1", + "job_id_2": "job_status_2", + ... + }, + "message": "success", + "run_time": 0.123, + "queue_time": 0, + "total_time": 0.123, + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +- **404 Not Found**: If the jobs directory is not found. + +```json +{ + "code": 404, + "id": null, + "job_id": "job_id_value", + "response": null, + "message": "Jobs directory not found", + "run_time": 0.123, + "queue_time": 0, + "total_time": 0.123, + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +- **500 Internal Server Error**: If an exception occurs while retrieving the job statuses. + +```json +{ + "code": 500, + "id": null, + "job_id": "job_id_value", + "response": null, + "message": "Failed to retrieve job statuses: Error message", + "run_time": 0.123, + "queue_time": 0, + "total_time": 0.123, + "pid": 12345, + "queue_id": 1234567890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +- Missing or invalid `x-api-key` header: The `authenticate` decorator will return a 401 Unauthorized error. +- Jobs directory not found: The endpoint will return a 404 Not Found error if the jobs directory is not found. +- Exception during job status retrieval: The endpoint will return a 500 Internal Server Error if an exception occurs while retrieving the job statuses. + +The main `app.py` file includes error handling for queue overflow (429 Too Many Requests) and logging of job statuses (queued, running, done) using the `log_job_status` function. + +## 6. Usage Notes + +- This endpoint is useful for monitoring the status of jobs submitted to the system, especially when dealing with long-running or queued jobs. +- The `since_seconds` parameter can be adjusted to retrieve job statuses within a specific time range, allowing for more targeted monitoring. + +## 7. Common Issues + +- Providing an invalid `x-api-key` header will result in an authentication error. +- If the jobs directory is not found or an exception occurs during job status retrieval, the endpoint will return an error. + +## 8. Best Practices + +- Always include the `x-api-key` header with a valid API key for authentication. +- Monitor the job statuses regularly to keep track of the progress and completion of submitted jobs. +- Adjust the `since_seconds` parameter based on your monitoring requirements to retrieve job statuses within a specific time range. +- Implement error handling and logging mechanisms to track and troubleshoot any issues that may arise. \ No newline at end of file diff --git a/docs/toolkit/test.md b/docs/toolkit/test.md new file mode 100644 index 0000000000000000000000000000000000000000..a30427352aca6a70f242770b5ceb1fcffac012c3 --- /dev/null +++ b/docs/toolkit/test.md @@ -0,0 +1,89 @@ +# NCA Toolkit Test API Endpoint + +## 1. Overview + +The `/v1/toolkit/test` endpoint is a part of the NCA Toolkit API and is designed to test the API setup. It creates a temporary file, uploads it to cloud storage, and then returns the upload URL. This endpoint serves as a simple test to ensure that the API is properly configured and can perform basic file operations and cloud storage interactions. + +## 2. Endpoint + +**URL Path:** `/v1/toolkit/test` +**HTTP Method:** `GET` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +This endpoint does not require any request body parameters. + +### Example Request + +```bash +curl -X GET \ + https://your-api-url.com/v1/toolkit/test \ + -H 'x-api-key: your-api-key' +``` + +## 4. Response + +### Success Response + +```json +{ + "endpoint": "/v1/toolkit/test", + "code": 200, + "id": null, + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": "https://cloud-storage.com/success.txt", + "message": "success", + "pid": 12345, + "queue_id": 67890, + "run_time": 0.123, + "queue_time": 0.0, + "total_time": 0.123, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +**Status Code: 401 Unauthorized** + +```json +{ + "code": 401, + "message": "Unauthorized: Invalid or missing API key" +} +``` + +**Status Code: 500 Internal Server Error** + +```json +{ + "code": 500, + "message": "An error occurred while processing the request" +} +``` + +## 5. Error Handling + +- **Missing or Invalid API Key (401 Unauthorized)**: If the `x-api-key` header is missing or invalid, the API will return a 401 Unauthorized error. +- **Internal Server Error (500)**: If an unexpected error occurs during the file creation, upload, or any other operation, the API will return a 500 Internal Server Error with the error message. + +## 6. Usage Notes + +This endpoint is primarily used for testing purposes and does not require any specific input parameters. It can be called to verify that the API is set up correctly and can perform basic operations. + +## 7. Common Issues + +- Incorrect or missing API key: Ensure that the `x-api-key` header is included with a valid API key. +- Temporary file creation or upload issues: If there are any issues with creating or uploading the temporary file, the API will return an error. + +## 8. Best Practices + +- Use this endpoint during the initial setup and testing phase of the API integration to ensure that the API is configured correctly. +- Regularly test the API setup using this endpoint to catch any potential issues or configuration changes that may affect the API's functionality. \ No newline at end of file diff --git a/docs/video/caption_video.md b/docs/video/caption_video.md new file mode 100644 index 0000000000000000000000000000000000000000..d8c617e70bdde116f01f6ae006f4a68b08ff3436 --- /dev/null +++ b/docs/video/caption_video.md @@ -0,0 +1,354 @@ +# Video Captioning Endpoint (v1) + +## 1. Overview + +The `/v1/video/caption` endpoint is part of the Video API and is responsible for adding captions to a video file. It accepts a video URL, caption text, and various styling options for the captions. The endpoint utilizes the `process_captioning_v1` service to generate a captioned video file, which is then uploaded to cloud storage, and the cloud URL is returned in the response. + +## 2. Endpoint + +**URL:** `/v1/video/caption` +**Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key`: Required. The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following properties: + +- `video_url` (string, required): The URL of the video file to be captioned. +- `captions` (string, optional): Can be one of the following: + - Raw caption text to be added to the video + - URL to an SRT subtitle file + - URL to an ASS subtitle file + - If not provided, the system will automatically generate captions by transcribing the audio from the video +- `settings` (object, optional): An object containing various styling options for the captions. See the schema below for available options. +- `replace` (array, optional): An array of objects with `find` and `replace` properties, specifying text replacements to be made in the captions. +- `webhook_url` (string, optional): A URL to receive a webhook notification when the captioning process is complete. +- `id` (string, optional): An identifier for the request. +- `language` (string, optional): The language code for the captions (e.g., "en", "fr"). Defaults to "auto". +- `exclude_time_ranges` (array, optional): List of time ranges to skip when adding captions. Each item must be an object with: + - `start`: (string, required) The start time of the excluded range, as a string timecode in `hh:mm:ss.ms` format (e.g., `00:01:23.456`). + - `end`: (string, required) The end time, as a string timecode in `hh:mm:ss.ms` format, which must be strictly greater than `start`. + If either value is not a valid timecode string, or if `end` is not greater than `start`, the request will return an error. + +#### Settings Schema + +```json +{ + "type": "object", + "properties": { + "line_color": {"type": "string"}, + "word_color": {"type": "string"}, + "outline_color": {"type": "string"}, + "all_caps": {"type": "boolean"}, + "max_words_per_line": {"type": "integer"}, + "x": {"type": "integer"}, + "y": {"type": "integer"}, + "position": { + "type": "string", + "enum": [ + "bottom_left", "bottom_center", "bottom_right", + "middle_left", "middle_center", "middle_right", + "top_left", "top_center", "top_right" + ] + }, + "alignment": { + "type": "string", + "enum": ["left", "center", "right"] + }, + "font_family": {"type": "string"}, + "font_size": {"type": "integer"}, + "bold": {"type": "boolean"}, + "italic": {"type": "boolean"}, + "underline": {"type": "boolean"}, + "strikeout": {"type": "boolean"}, + "style": { + "type": "string", + "enum": [ + "classic", // Regular captioning with all text displayed at once + "karaoke", // Highlights words sequentially in a karaoke style + "highlight", // Shows full text but highlights the current word + "underline", // Shows full text but underlines the current word + "word_by_word" // Shows one word at a time + ] + }, + "outline_width": {"type": "integer"}, + "spacing": {"type": "integer"}, + "angle": {"type": "integer"}, + "shadow_offset": {"type": "integer"} + }, + "additionalProperties": false +} +``` + +### Example Requests + +#### Example 1: Basic Automatic Captioning +```json +{ + "video_url": "https://example.com/video.mp4" +} +``` +This minimal request will automatically transcribe the video and add white captions at the bottom center. + +#### Example 2: Custom Text with Styling +```json +{ + "video_url": "https://example.com/video.mp4", + "captions": "This is a sample caption text.", + "settings": { + "style": "classic", + "line_color": "#FFFFFF", + "outline_color": "#000000", + "position": "bottom_center", + "alignment": "center", + "font_family": "Arial", + "font_size": 24, + "bold": true + } +} +``` + +#### Example 3: Karaoke-Style Captions with Advanced Options +```json +{ + "video_url": "https://example.com/video.mp4", + "settings": { + "line_color": "#FFFFFF", + "word_color": "#FFFF00", + "outline_color": "#000000", + "all_caps": false, + "max_words_per_line": 10, + "position": "bottom_center", + "alignment": "center", + "font_family": "Arial", + "font_size": 24, + "bold": false, + "italic": false, + "style": "karaoke", + "outline_width": 2, + "shadow_offset": 2 + }, + "replace": [ + { + "find": "um", + "replace": "" + }, + { + "find": "like", + "replace": "" + } + ], + "webhook_url": "https://example.com/webhook", + "id": "request-123", + "language": "en" +} +``` + +#### Example 4: Using an External Subtitle File +```json +{ + "video_url": "https://example.com/video.mp4", + "captions": "https://example.com/subtitles.srt", + "settings": { + "line_color": "#FFFFFF", + "outline_color": "#000000", + "position": "bottom_center", + "font_family": "Arial", + "font_size": 24 + } +} +``` + +#### Example 5: Excluding Time Ranges from Captioning +```json +{ + "video_url": "https://example.com/video.mp4", + "settings": { + "style": "classic", + "line_color": "#FFFFFF", + "outline_color": "#000000", + "position": "bottom_center", + "font_family": "Arial", + "font_size": 24 + }, + "exclude_time_ranges": [ + { "start": "00:00:10.000", "end": "00:00:20.000" }, + { "start": "00:00:30.000", "end": "00:00:40.000" } + ] +} +``` + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "video_url": "https://example.com/video.mp4", + "settings": { + "line_color": "#FFFFFF", + "word_color": "#FFFF00", + "outline_color": "#000000", + "all_caps": false, + "max_words_per_line": 10, + "position": "bottom_center", + "alignment": "center", + "font_family": "Arial", + "font_size": 24, + "style": "karaoke", + "outline_width": 2 + }, + "replace": [ + { + "find": "um", + "replace": "" + } + ], + "id": "custom-request-id" + }' \ + https://your-api-endpoint.com/v1/video/caption +``` + +## 4. Response + +### Success Response + +The response will be a JSON object with the following properties: + +- `code` (integer): The HTTP status code (200 for success). +- `id` (string): The request identifier, if provided in the request. +- `job_id` (string): A unique identifier for the job. +- `response` (string): The cloud URL of the captioned video file. +- `message` (string): A success message. +- `pid` (integer): The process ID of the worker that processed the request. +- `queue_id` (integer): The ID of the queue used for processing the request. +- `run_time` (float): The time taken to process the request (in seconds). +- `queue_time` (float): The time the request spent in the queue (in seconds). +- `total_time` (float): The total time taken for the request (in seconds). +- `queue_length` (integer): The current length of the processing queue. +- `build_number` (string): The build number of the application. + +Example: + +```json +{ + "code": 200, + "id": "request-123", + "job_id": "d290f1ee-6c54-4b01-90e6-d701748f0851", + "response": "https://cloud.example.com/captioned-video.mp4", + "message": "success", + "pid": 12345, + "queue_id": 140682639937472, + "run_time": 5.234, + "queue_time": 0.012, + "total_time": 5.246, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +#### Missing or Invalid Parameters + +**Status Code:** 400 Bad Request + +```json +{ + "code": 400, + "id": "request-123", + "job_id": "d290f1ee-6c54-4b01-90e6-d701748f0851", + "message": "Missing or invalid parameters", + "pid": 12345, + "queue_id": 140682639937472, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +#### Font Error + +**Status Code:** 400 Bad Request + +```json +{ + "code": 400, + "error": "The requested font 'InvalidFont' is not available. Please choose from the available fonts.", + "available_fonts": ["Arial", "Times New Roman", "Courier New", ...], + "pid": 12345, + "queue_id": 140682639937472, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +#### Internal Server Error + +**Status Code:** 500 Internal Server Error + +```json +{ + "code": 500, + "id": "request-123", + "job_id": "d290f1ee-6c54-4b01-90e6-d701748f0851", + "error": "An unexpected error occurred during the captioning process.", + "pid": 12345, + "queue_id": 140682639937472, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +The endpoint handles the following common errors: + +- **Missing or Invalid Parameters**: If any required parameters are missing or invalid, a 400 Bad Request error is returned with a descriptive error message. +- **Font Error**: If the requested font is not available, a 400 Bad Request error is returned with a list of available fonts. +- **Internal Server Error**: If an unexpected error occurs during the captioning process, a 500 Internal Server Error is returned with an error message. + +Additionally, the main application context (`app.py`) includes error handling for queue overload. If the maximum queue length (`MAX_QUEUE_LENGTH`) is set and the queue size reaches that limit, a 429 Too Many Requests error is returned with a descriptive message. + +## 6. Usage Notes + +- The `video_url` parameter must be a valid URL pointing to a video file (MP4, MOV, etc.). +- The `captions` parameter is optional and can be used in multiple ways: + - If not provided, the endpoint will automatically transcribe the audio and generate captions + - If provided as plain text, the text will be used as captions for the entire video + - If provided as a URL to an SRT or ASS subtitle file, the system will use that file for captioning + - For SRT files, only 'classic' style is supported + - For ASS files, the original styling will be preserved +- The `settings` parameter allows for customization of the caption appearance and behavior: + - `style` determines how captions are displayed, with options including: + - `classic`: Regular captioning with all text displayed at once + - `karaoke`: Highlights words sequentially in a karaoke style as they're spoken + - `highlight`: Shows the full caption text but highlights each word as it's spoken + - `underline`: Shows the full caption text but underlines each word as it's spoken + - `word_by_word`: Shows only one word at a time + - `position` can be used to place captions in one of nine positions on the screen + - `alignment` determines text alignment within the position (left, center, right) + - `font_family` can be any available system font + - Color options can be set using hex codes (e.g., "#FFFFFF" for white) +- The `replace` parameter can be used to perform text replacements in the captions (useful for correcting words or censoring content). +- The `webhook_url` parameter is optional and can be used to receive a notification when the captioning process is complete. +- The `id` parameter is optional and can be used to identify the request in webhook responses. +- The `language` parameter is optional and can be used to specify the language of the captions for transcription. If not provided, the language will be automatically detected. +- The `exclude_time_ranges` parameter can be used to specify time ranges to be excluded from captioning. + +## 7. Common Issues + +- Providing an invalid or inaccessible `video_url`. +- Requesting an unavailable font in the `settings` object. +- Exceeding the maximum queue length, resulting in a 429 Too Many Requests error. + +## 8. Best Practices + +- Validate the `video_url` parameter before sending the request to ensure it points to a valid and accessible video file. +- Use the `webhook_url` parameter to receive notifications about the captioning process, rather than polling the API for updates. +- Provide descriptive and meaningful `id` values to easily identify requests in logs and responses. +- Use the `replace` parameter judiciously to avoid unintended text replacements in the captions. +- Consider caching the captioned video files for frequently requested videos to improve performance and reduce processing time. \ No newline at end of file diff --git a/docs/video/concatenate.md b/docs/video/concatenate.md new file mode 100644 index 0000000000000000000000000000000000000000..eb998a7df20e8e8c2ca584f29f5f7feecef4230c --- /dev/null +++ b/docs/video/concatenate.md @@ -0,0 +1,180 @@ +# Video Concatenation Endpoint + +## 1. Overview + +The `/v1/video/concatenate` endpoint is a part of the Video API and is responsible for combining multiple video files into a single video file. This endpoint fits into the overall API structure as a part of the version 1 (v1) routes, specifically under the `/v1/video` namespace. + +## 2. Endpoint + +**URL Path:** `/v1/video/concatenate` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following properties: + +- `video_urls` (required, array of objects): An array of video URLs to be concatenated. Each object in the array must have a `video_url` property (string, URI format) containing the URL of the video file. +- `webhook_url` (optional, string, URI format): The URL to which the response should be sent as a webhook. +- `id` (optional, string): An identifier for the request. + +The `validate_payload` decorator in the routes file enforces the following JSON schema for the request body: + +```json +{ + "type": "object", + "properties": { + "video_urls": { + "type": "array", + "items": { + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"} + }, + "required": ["video_url"] + }, + "minItems": 1 + }, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_urls"], + "additionalProperties": False +} +``` + +### Example Request + +```json +{ + "video_urls": [ + {"video_url": "https://example.com/video1.mp4"}, + {"video_url": "https://example.com/video2.mp4"}, + {"video_url": "https://example.com/video3.mp4"} + ], + "webhook_url": "https://example.com/webhook", + "id": "request-123" +} +``` + +```bash +curl -X POST \ + -H "x-api-key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "video_urls": [ + {"video_url": "https://example.com/video1.mp4"}, + {"video_url": "https://example.com/video2.mp4"}, + {"video_url": "https://example.com/video3.mp4"} + ], + "webhook_url": "https://example.com/webhook", + "id": "request-123" + }' \ + https://your-api-endpoint.com/v1/video/concatenate +``` + +## 4. Response + +### Success Response + +The success response follows the general response format defined in the `app.py` file. Here's an example: + +```json +{ + "endpoint": "/v1/video/concatenate", + "code": 200, + "id": "request-123", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": "https://cloud-storage.example.com/combined-video.mp4", + "message": "success", + "pid": 12345, + "queue_id": 6789, + "run_time": 10.234, + "queue_time": 2.345, + "total_time": 12.579, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +The `response` field contains the URL of the combined video file uploaded to cloud storage. + +### Error Responses + +- **400 Bad Request**: Returned when the request body is missing or invalid. + + ```json + { + "code": 400, + "message": "Invalid request payload" + } + ``` + +- **401 Unauthorized**: Returned when the `x-api-key` header is missing or invalid. + + ```json + { + "code": 401, + "message": "Unauthorized" + } + ``` + +- **429 Too Many Requests**: Returned when the maximum queue length is reached. + + ```json + { + "code": 429, + "id": "request-123", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "MAX_QUEUE_LENGTH (100) reached", + "pid": 12345, + "queue_id": 6789, + "queue_length": 100, + "build_number": "1.0.0" + } + ``` + +- **500 Internal Server Error**: Returned when an unexpected error occurs during the video concatenation process. + + ```json + { + "code": 500, + "message": "An error occurred during video concatenation" + } + ``` + +## 5. Error Handling + +The endpoint handles the following common errors: + +- **Missing or invalid request body**: If the request body is missing or does not conform to the expected JSON schema, a 400 Bad Request error is returned. +- **Missing or invalid API key**: If the `x-api-key` header is missing or invalid, a 401 Unauthorized error is returned. +- **Queue length exceeded**: If the maximum queue length is reached (determined by the `MAX_QUEUE_LENGTH` environment variable), a 429 Too Many Requests error is returned. +- **Unexpected errors during video concatenation**: If an unexpected error occurs during the video concatenation process, a 500 Internal Server Error is returned with the error message. + +The main application context (`app.py`) also includes error handling for the task queue. If the queue length exceeds the `MAX_QUEUE_LENGTH` limit, the request is rejected with a 429 Too Many Requests error. + +## 6. Usage Notes + +- The video files to be concatenated must be accessible via the provided URLs. +- The order of the video files in the `video_urls` array determines the order in which they will be concatenated. +- If the `webhook_url` parameter is provided, the response will be sent as a webhook to the specified URL. +- The `id` parameter can be used to identify the request in the response. + +## 7. Common Issues + +- Providing invalid or inaccessible video URLs. +- Exceeding the maximum queue length, which can lead to requests being rejected with a 429 Too Many Requests error. +- Encountering unexpected errors during the video concatenation process, which can result in a 500 Internal Server Error. + +## 8. Best Practices + +- Validate the video URLs before sending the request to ensure they are accessible and in the correct format. +- Monitor the queue length and adjust the `MAX_QUEUE_LENGTH` value accordingly to prevent requests from being rejected due to a full queue. +- Implement retry mechanisms for handling temporary errors or failures during the video concatenation process. +- Provide meaningful and descriptive `id` values to easily identify requests in the response. \ No newline at end of file diff --git a/docs/video/cut.md b/docs/video/cut.md new file mode 100644 index 0000000000000000000000000000000000000000..b727ac076a9b86374a6d11af9be7dd91615d55c9 --- /dev/null +++ b/docs/video/cut.md @@ -0,0 +1,197 @@ +# Video Cut Endpoint + +## 1. Overview + +The `/v1/video/cut` endpoint is part of the Video API and allows users to cut specified segments from a video file with optional encoding settings. This endpoint fits into the overall API structure as a part of the version 1 (`v1`) routes, specifically under the `video` category. + +## 2. Endpoint + +``` +POST /v1/video/cut +``` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following properties: + +- `video_url` (required, string): The URL of the video file to be cut. +- `cuts` (required, array of objects): An array of cut segments, where each object has the following properties: + - `start` (required, string): The start time of the cut segment in the format `hh:mm:ss.ms`. + - `end` (required, string): The end time of the cut segment in the format `hh:mm:ss.ms`. +- `video_codec` (optional, string): The video codec to use for encoding the output video. Default is `libx264`. +- `video_preset` (optional, string): The video preset to use for encoding the output video. Default is `medium`. +- `video_crf` (optional, number): The Constant Rate Factor (CRF) value for video encoding. Must be between 0 and 51. Default is 23. +- `audio_codec` (optional, string): The audio codec to use for encoding the output video. Default is `aac`. +- `audio_bitrate` (optional, string): The audio bitrate to use for encoding the output video. Default is `128k`. +- `webhook_url` (optional, string): The URL to receive a webhook notification when the job is completed. +- `id` (optional, string): A unique identifier for the request. + +### Example Request + +```json +{ + "video_url": "https://example.com/video.mp4", + "cuts": [ + { + "start": "00:00:10.000", + "end": "00:00:20.000" + }, + { + "start": "00:00:30.000", + "end": "00:00:40.000" + } + ], + "video_codec": "libx264", + "video_preset": "medium", + "video_crf": 23, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +} +``` + +```bash +curl -X POST \ + https://api.example.com/v1/video/cut \ + -H 'x-api-key: YOUR_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{ + "video_url": "https://example.com/video.mp4", + "cuts": [ + { + "start": "00:00:10.000", + "end": "00:00:20.000" + }, + { + "start": "00:00:30.000", + "end": "00:00:40.000" + } + ], + "video_codec": "libx264", + "video_preset": "medium", + "video_crf": 23, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" + }' +``` + +## 4. Response + +### Success Response + +The response follows the general response format defined in the main application context (`app.py`). Here's an example of a successful response: + +```json +{ + "endpoint": "/v1/video/cut", + "code": 200, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": "https://example.com/processed-video.mp4", + "message": "success", + "pid": 12345, + "queue_id": 6789, + "run_time": 5.234, + "queue_time": 0.123, + "total_time": 5.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +The `response` field contains the URL of the processed video file. + +### Error Responses + +- **400 Bad Request** + + ```json + { + "code": 400, + "message": "Invalid request payload" + } + ``` + + This error occurs when the request payload is missing required fields or contains invalid data. + +- **401 Unauthorized** + + ```json + { + "code": 401, + "message": "Invalid API key" + } + ``` + + This error occurs when the provided `x-api-key` header is missing or invalid. + +- **429 Too Many Requests** + + ```json + { + "code": 429, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "MAX_QUEUE_LENGTH (100) reached", + "pid": 12345, + "queue_id": 6789, + "queue_length": 100, + "build_number": "1.0.0" + } + ``` + + This error occurs when the maximum queue length has been reached, and the request cannot be processed immediately. + +- **500 Internal Server Error** + + ```json + { + "code": 500, + "message": "An error occurred during video processing" + } + ``` + + This error occurs when an unexpected error occurs during the video processing or encoding. + +## 5. Error Handling + +The endpoint handles the following common errors: + +- **Missing or invalid request parameters**: If any required parameters are missing or invalid, the endpoint returns a 400 Bad Request error with an appropriate error message. +- **Invalid API key**: If the provided `x-api-key` header is missing or invalid, the endpoint returns a 401 Unauthorized error. +- **Queue limit reached**: If the maximum queue length has been reached, the endpoint returns a 429 Too Many Requests error with the current queue length and the maximum queue length. +- **Unexpected errors during video processing**: If an unexpected error occurs during the video processing or encoding, the endpoint returns a 500 Internal Server Error with a generic error message. + +The main application context (`app.py`) also includes error handling for the queue system and webhook notifications. + +## 6. Usage Notes + +- The `video_url` parameter must be a valid URL that points to a video file accessible by the server. +- The `cuts` parameter must be an array of objects, where each object represents a cut segment with a start and end time in the format `hh:mm:ss.ms`. +- The optional encoding parameters (`video_codec`, `video_preset`, `video_crf`, `audio_codec`, `audio_bitrate`) allow you to customize the encoding settings for the output video file. +- If the `webhook_url` parameter is provided, the server will send a webhook notification to the specified URL when the job is completed. +- The `id` parameter can be used to associate the request with a unique identifier for tracking purposes. + +## 7. Common Issues + +- Providing an invalid or inaccessible `video_url`. +- Specifying overlapping or invalid cut segments in the `cuts` parameter. +- Providing invalid encoding settings that are not supported by the server. +- Reaching the maximum queue length, which can cause requests to be rejected with a 429 Too Many Requests error. + +## 8. Best Practices + +- Validate the `video_url` parameter before sending the request to ensure it points to a valid and accessible video file. +- Ensure that the cut segments in the `cuts` parameter are correctly formatted and do not overlap or exceed the duration of the video. +- Use the optional encoding parameters judiciously, as they can impact the processing time and output video quality. +- Implement retry mechanisms for handling 429 Too Many Requests errors, as the queue length may fluctuate over time. +- Monitor the webhook notifications or poll the server for job status updates to track the progress of long-running jobs. \ No newline at end of file diff --git a/docs/video/split.md b/docs/video/split.md new file mode 100644 index 0000000000000000000000000000000000000000..2b86c6fa9d0dd1e32c155ae1638125645a56a423 --- /dev/null +++ b/docs/video/split.md @@ -0,0 +1,173 @@ +# Video Split Endpoint + +## 1. Overview + +The `/v1/video/split` endpoint is part of the Video API and is used to split a video file into multiple segments based on specified start and end times. This endpoint fits into the overall API structure as a part of the version 1 (`v1`) routes, specifically under the `video` category. + +## 2. Endpoint + +**URL Path:** `/v1/video/split` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +The request body must be a JSON object with the following properties: + +- `video_url` (required, string): The URL of the video file to be split. +- `splits` (required, array of objects): An array of objects specifying the start and end times for each split. Each object must have the following properties: + - `start` (required, string): The start time of the split in the format `hh:mm:ss.ms`. + - `end` (required, string): The end time of the split in the format `hh:mm:ss.ms`. +- `video_codec` (optional, string): The video codec to use for encoding the split videos. Default is `libx264`. +- `video_preset` (optional, string): The video preset to use for encoding the split videos. Default is `medium`. +- `video_crf` (optional, number): The Constant Rate Factor (CRF) value for video encoding. Must be between 0 and 51. Default is 23. +- `audio_codec` (optional, string): The audio codec to use for encoding the split videos. Default is `aac`. +- `audio_bitrate` (optional, string): The audio bitrate to use for encoding the split videos. Default is `128k`. +- `webhook_url` (optional, string): The URL to receive a webhook notification when the split operation is complete. +- `id` (optional, string): A unique identifier for the request. + +### Example Request + +```json +{ + "video_url": "https://example.com/video.mp4", + "splits": [ + { + "start": "00:00:10.000", + "end": "00:00:20.000" + }, + { + "start": "00:00:30.000", + "end": "00:00:40.000" + } + ], + "video_codec": "libx264", + "video_preset": "medium", + "video_crf": 23, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +} +``` + +```bash +curl -X POST \ + https://api.example.com/v1/video/split \ + -H 'x-api-key: YOUR_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{ + "video_url": "https://example.com/video.mp4", + "splits": [ + { + "start": "00:00:10.000", + "end": "00:00:20.000" + }, + { + "start": "00:00:30.000", + "end": "00:00:40.000" + } + ], + "video_codec": "libx264", + "video_preset": "medium", + "video_crf": 23, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" + }' +``` + +## 4. Response + +### Success Response + +The success response follows the general response format specified in `app.py`. Here's an example: + +```json +{ + "endpoint": "/v1/video/split", + "code": 200, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": [ + { + "file_url": "https://example.com/split-1.mp4" + }, + { + "file_url": "https://example.com/split-2.mp4" + } + ], + "message": "success", + "pid": 12345, + "queue_id": 6789, + "run_time": 5.234, + "queue_time": 0.123, + "total_time": 5.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +The `response` field contains an array of objects, each representing a split video file. Each object has a `file_url` property containing the URL of the split video file. + +### Error Responses + +- **400 Bad Request**: Returned when the request payload is missing or invalid. +- **401 Unauthorized**: Returned when the `x-api-key` header is missing or invalid. +- **429 Too Many Requests**: Returned when the maximum queue length has been reached. +- **500 Internal Server Error**: Returned when an unexpected error occurs during the video split process. + +Example error response: + +```json +{ + "code": 400, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "message": "Invalid request payload: 'splits' is a required property", + "pid": 12345, + "queue_id": 6789, + "queue_length": 2, + "build_number": "1.0.0" +} +``` + +## 5. Error Handling + +The endpoint handles the following common errors: + +- Missing or invalid request parameters: Returns a 400 Bad Request error with a descriptive error message. +- Authentication failure: Returns a 401 Unauthorized error if the `x-api-key` header is missing or invalid. +- Queue length exceeded: Returns a 429 Too Many Requests error if the maximum queue length has been reached. +- Unexpected exceptions: Returns a 500 Internal Server Error with the exception message. + +The main application context (`app.py`) also includes error handling for queue length limits and webhook notifications. + +## 6. Usage Notes + +- The `video_url` parameter must be a valid URL pointing to a video file. +- The `splits` array must contain at least one object specifying the start and end times for a split. +- The start and end times must be in the format `hh:mm:ss.ms` (hours:minutes:seconds.milliseconds). +- The `video_codec`, `video_preset`, `video_crf`, `audio_codec`, and `audio_bitrate` parameters are optional and can be used to customize the encoding settings for the split videos. +- If the `webhook_url` parameter is provided, a webhook notification will be sent to the specified URL when the split operation is complete. +- The `id` parameter is optional and can be used to uniquely identify the request. + +## 7. Common Issues + +- Providing an invalid or inaccessible `video_url`. +- Specifying overlapping or invalid start and end times in the `splits` array. +- Exceeding the maximum queue length, which can result in a 429 Too Many Requests error. + +## 8. Best Practices + +- Validate the `video_url` parameter before sending the request to ensure it points to a valid video file. +- Ensure that the start and end times in the `splits` array are correctly formatted and do not overlap. +- Consider using the `webhook_url` parameter to receive notifications about the completion of the split operation, especially for long-running or asynchronous requests. +- Implement retry mechanisms and error handling in your client application to handle potential errors and failures. +- Monitor the queue length and adjust the `MAX_QUEUE_LENGTH` environment variable as needed to prevent excessive queuing and potential timeouts. \ No newline at end of file diff --git a/docs/video/thumbnail.md b/docs/video/thumbnail.md new file mode 100644 index 0000000000000000000000000000000000000000..b572742176eff733ddf36fe15a55bf6e9cfd0d21 --- /dev/null +++ b/docs/video/thumbnail.md @@ -0,0 +1,165 @@ +# Video Thumbnail Generation API + +## Overview + +The `/v1/video/thumbnail` endpoint allows users to extract a thumbnail image from a specific timestamp in a video. This endpoint is part of the video processing capabilities of the API, which includes other features like video concatenation and captioning. The endpoint processes the request asynchronously using a queue system, uploads the generated thumbnail to cloud storage, and returns the URL of the uploaded image. + +## Endpoint + +- **URL**: `/v1/video/thumbnail` +- **Method**: `POST` + +## Request + +### Headers + +- `x-api-key`: Required. Your API authentication key. + +### Body Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `video_url` | string (URI format) | Yes | URL of the video from which to extract the thumbnail | +| `second` | number (minimum: 0) | No | Timestamp in seconds at which to extract the thumbnail (defaults to 0) | +| `webhook_url` | string (URI format) | No | URL to receive the processing result asynchronously | +| `id` | string | No | Custom identifier for tracking the request | + +### Example Request + +```json +{ + "video_url": "https://example.com/video.mp4", + "second": 30, + "webhook_url": "https://your-service.com/webhook", + "id": "custom-request-123" +} +``` + +### Example cURL Command + +```bash +curl -X POST \ + https://api.example.com/v1/video/thumbnail \ + -H 'Content-Type: application/json' \ + -H 'x-api-key: your-api-key' \ + -d '{ + "video_url": "https://example.com/video.mp4", + "second": 30, + "webhook_url": "https://your-service.com/webhook", + "id": "custom-request-123" + }' +``` + +## Response + +### Immediate Response (Status Code: 202) + +When a webhook URL is provided, the API immediately returns a 202 Accepted response and processes the request asynchronously: + +```json +{ + "code": 202, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "processing", + "pid": 12345, + "queue_id": 67890, + "max_queue_length": "unlimited", + "queue_length": 1, + "build_number": "1.0.0" +} +``` + +### Success Response (Status Code: 200) + +When no webhook URL is provided or when the webhook is called after processing: + +```json +{ + "code": 200, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "response": "https://storage.example.com/thumbnails/video-thumbnail-123.jpg", + "message": "success", + "run_time": 1.234, + "queue_time": 0.567, + "total_time": 1.801, + "pid": 12345, + "queue_id": 67890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +#### Invalid Request (Status Code: 400) + +```json +{ + "code": 400, + "message": "Invalid request: 'video_url' is a required property", + "job_id": "550e8400-e29b-41d4-a716-446655440000" +} +``` + +#### Queue Full (Status Code: 429) + +```json +{ + "code": 429, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "MAX_QUEUE_LENGTH (100) reached", + "pid": 12345, + "queue_id": 67890, + "queue_length": 100, + "build_number": "1.0.0" +} +``` + +#### Server Error (Status Code: 500) + +```json +{ + "code": 500, + "id": "custom-request-123", + "job_id": "550e8400-e29b-41d4-a716-446655440000", + "message": "Failed to download video from provided URL", + "pid": 12345, + "queue_id": 67890, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +## Error Handling + +The endpoint handles various error scenarios: + +- **Missing Required Parameters**: Returns a 400 error if `video_url` is missing. +- **Invalid Parameter Format**: Returns a 400 error if parameters don't match the expected format (e.g., invalid URLs). +- **Queue Capacity**: Returns a 429 error if the processing queue is full. +- **Processing Errors**: Returns a 500 error if there are issues during thumbnail extraction or upload. + +## Usage Notes + +1. **Asynchronous Processing**: For long-running operations, provide a `webhook_url` to receive the result asynchronously. +2. **Timestamp Selection**: Choose an appropriate `second` value to capture a meaningful frame from the video. +3. **Request Tracking**: Use the `id` parameter to track your requests across your systems. +4. **Queue Management**: The API uses a queue system with configurable maximum length (set by the `MAX_QUEUE_LENGTH` environment variable). + +## Common Issues + +1. **Inaccessible Video URLs**: Ensure the video URL is publicly accessible or has proper authentication. +2. **Invalid Timestamp**: If the specified second exceeds the video duration, the API may use the last frame or return an error. +3. **Webhook Failures**: If your webhook endpoint is unavailable, you won't receive the processing result. +4. **Large Videos**: Processing very large videos may take longer and could time out. + +## Best Practices + +1. **Use Webhooks for Long Videos**: Always use webhooks when processing large videos to avoid HTTP timeout issues. +2. **Optimize Thumbnail Selection**: Choose meaningful timestamps for thumbnails (e.g., after intro sequences). +3. **Error Handling**: Implement proper error handling in your application to manage API errors gracefully. +4. **Rate Limiting**: Monitor the queue length in responses to avoid overwhelming the service. +5. **Idempotent Requests**: Use the `id` parameter to make requests idempotent and avoid duplicate processing. \ No newline at end of file diff --git a/docs/video/trim.md b/docs/video/trim.md new file mode 100644 index 0000000000000000000000000000000000000000..b7a05baad1eb5bcfc3f2406f9cf99dea4e9922ef --- /dev/null +++ b/docs/video/trim.md @@ -0,0 +1,147 @@ +# Video Trim Endpoint + +## 1. Overview + +The `/v1/video/trim` endpoint is part of the Video API and allows users to trim a video by removing specified portions from the beginning and/or end. It also provides optional encoding settings to control the output video quality. This endpoint fits into the overall API structure as a part of the version 1 (`v1`) routes, specifically under the `video` category. + +## 2. Endpoint + +**URL Path:** `/v1/video/trim` +**HTTP Method:** `POST` + +## 3. Request + +### Headers + +- `x-api-key` (required): The API key for authentication. + +### Body Parameters + +- `video_url` (required, string): The URL of the video file to be trimmed. +- `start` (optional, string): The start time for trimming in the format `hh:mm:ss` or `mm:ss`. +- `end` (optional, string): The end time for trimming in the format `hh:mm:ss` or `mm:ss`. +- `video_codec` (optional, string): The video codec to be used for encoding the output video. Default is `libx264`. +- `video_preset` (optional, string): The video preset to be used for encoding the output video. Default is `medium`. +- `video_crf` (optional, number): The Constant Rate Factor (CRF) value for video encoding, ranging from 0 to 51. Default is 23. +- `audio_codec` (optional, string): The audio codec to be used for encoding the output video. Default is `aac`. +- `audio_bitrate` (optional, string): The audio bitrate to be used for encoding the output video. Default is `128k`. +- `webhook_url` (optional, string): The URL to receive a webhook notification upon completion of the task. +- `id` (optional, string): A unique identifier for the request. + +The `validate_payload` directive in the routes file ensures that the request payload adheres to the specified schema, which includes the required and optional parameters, their data types, and any additional constraints. + +### Example Request + +```json +{ + "video_url": "https://example.com/video.mp4", + "start": "00:01:00", + "end": "00:03:00", + "video_codec": "libx264", + "video_preset": "faster", + "video_crf": 28, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" +} +``` + +```bash +curl -X POST \ + https://api.example.com/v1/video/trim \ + -H 'x-api-key: YOUR_API_KEY' \ + -H 'Content-Type: application/json' \ + -d '{ + "video_url": "https://example.com/video.mp4", + "start": "00:01:00", + "end": "00:03:00", + "video_codec": "libx264", + "video_preset": "faster", + "video_crf": 28, + "audio_codec": "aac", + "audio_bitrate": "128k", + "webhook_url": "https://example.com/webhook", + "id": "unique-request-id" + }' +``` + +## 4. Response + +### Success Response + +The success response follows the general response structure defined in the `app.py` file. Here's an example: + +```json +{ + "endpoint": "/v1/video/trim", + "code": 200, + "id": "unique-request-id", + "job_id": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6", + "response": "https://example.com/trimmed-video.mp4", + "message": "success", + "pid": 12345, + "queue_id": 6789, + "run_time": 5.234, + "queue_time": 0.123, + "total_time": 5.357, + "queue_length": 0, + "build_number": "1.0.0" +} +``` + +### Error Responses + +- **400 Bad Request**: Returned when the request payload is missing or contains invalid parameters. + + ```json + { + "code": 400, + "message": "Invalid request payload" + } + ``` + +- **401 Unauthorized**: Returned when the `x-api-key` header is missing or invalid. + + ```json + { + "code": 401, + "message": "Unauthorized" + } + ``` + +- **500 Internal Server Error**: Returned when an unexpected error occurs during the video trimming process. + + ```json + { + "code": 500, + "message": "An error occurred during the video trimming process" + } + ``` + +## 5. Error Handling + +The endpoint handles common errors such as missing or invalid parameters by returning appropriate HTTP status codes and error messages. The `validate_payload` decorator ensures that the request payload adheres to the specified schema, and any violations will result in a 400 Bad Request error. + +The main application context (`app.py`) includes error handling for the task queue. If the maximum queue length is reached, the endpoint will return a 429 Too Many Requests error with a corresponding message. + +## 6. Usage Notes + +- The `start` and `end` parameters are optional, but at least one of them must be provided to perform the trimming operation. +- The `video_codec`, `video_preset`, `video_crf`, `audio_codec`, and `audio_bitrate` parameters are optional and allow users to customize the encoding settings for the output video. +- The `webhook_url` parameter is optional and can be used to receive a notification when the task is completed. +- The `id` parameter is optional and can be used to uniquely identify the request. + +## 7. Common Issues + +- Providing an invalid or inaccessible `video_url`. +- Specifying invalid or unsupported values for the encoding parameters (`video_codec`, `video_preset`, `video_crf`, `audio_codec`, `audio_bitrate`). +- Encountering issues with the video trimming process due to unsupported video formats or corrupted files. + +## 8. Best Practices + +- Validate the `video_url` parameter to ensure it points to a valid and accessible video file. +- Use appropriate encoding settings based on the desired output quality and file size requirements. +- Implement error handling and retry mechanisms for failed requests or network issues. +- Monitor the task queue length and adjust the `MAX_QUEUE_LENGTH` value accordingly to prevent overloading the system. +- Implement rate limiting or throttling mechanisms to prevent abuse or excessive requests. \ No newline at end of file diff --git a/generate_docs.py b/generate_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..befe26deb4de61d41bfb82663bffaa9cdcfdda80 --- /dev/null +++ b/generate_docs.py @@ -0,0 +1,329 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import sys +import json +import requests +import time +from pathlib import Path +from datetime import datetime, timedelta + +def load_config(): + """Load configuration from env_shell.json file.""" + config_path = Path(__file__).parent / '.env_shell.json' + try: + with open(config_path, 'r') as f: + config = json.load(f) + return config.get('ANTHROPIC_API_KEY'), config.get('API_DOC_OUTPUT_DIR') + except FileNotFoundError: + print(f"Error: Configuration file not found at: {config_path}") + sys.exit(1) + except json.JSONDecodeError: + print(f"Error: Invalid JSON in configuration file: {config_path}") + sys.exit(1) + except Exception as e: + print(f"Error loading configuration: {str(e)}") + sys.exit(1) + +def load_app_context(): + """Load the app.py file from the root of the repository.""" + try: + # Get the root directory by going up from the current file's location + root_dir = Path(__file__).parent.parent + app_path = Path(__file__).parent / 'app.py' + + if not app_path.exists(): + print("Warning: app.py not found in repository root. Documentation will be generated without API context.") + return None + + with open(app_path, 'r', encoding='utf-8') as f: + return f.read() + except Exception as e: + print(f"Warning: Could not load app.py: {str(e)}") + return None + +# The prompt template to send to Claude +CLAUDE_PROMPT = ''' + + I am providing you with a Python file containing API endpoint definitions. + + First, here is the main application context from app.py that shows how the API is structured and handled: + +** app.py below + +{app_context} + +** app.py DONE + + Now, please read through the following endpoint code and analyze it in the context of the main application: + +**endpoint below + +{file_content} + + Please generate detailed documentation in Markdown format as follows: + + 1. Overview: Describe the purpose of the endpoint and how it fits into the overall API structure shown in app.py. + 2. Endpoint: Specify the URL path and HTTP method. + 3. Request: + - Headers: List any required headers, such as the x-api-key headers. + - Body Parameters: List the required and optional parameters, including the parameter type and purpose. + - Specifically study the validate_payload directive in the routes file to build the documentation + - Example Request: Provide a sample request payload and a sample curl command. + 4. Response: + - Success Response: Reference the endpoint and general response from the app.py to show a full sample response from the api + - Error Responses: Include examples of common error status codes, with example JSON responses for each. + 5. Error Handling: + - Describe common errors, like missing or invalid parameters, and indicate which status codes they produce + - Include any specific error handling from the main application context + 6. Usage Notes: Any additional notes on using the endpoint effectively. + 7. Common Issues: List any common issues a user might encounter. + 8. Best Practices: Any recommended best practices for this endpoint. + + Format the documentation with markdown headings, bullet points, and code blocks. +''' + +def call_claude_api(message: str, api_key: str) -> str: + """Make a direct API call to Claude.""" + headers = { + "Content-Type": "application/json", + "x-api-key": api_key, + "anthropic-version": "2023-06-01" + } + + data = { + "model": "claude-3-sonnet-20240229", + "max_tokens": 4096, + "temperature": 0, + "messages": [ + {"role": "user", "content": message} + ] + } + + response = requests.post( + "https://api.anthropic.com/v1/messages", + headers=headers, + json=data + ) + + if response.status_code != 200: + raise Exception(f"API call failed with status {response.status_code}: {response.text}") + + return response.json()["content"][0]["text"] + +def should_skip_doc_generation(output_file: Path, force: bool = False) -> bool: + """ + Check if documentation was updated in the last 24 hours. + + Args: + output_file: Path to the output markdown file + force: If True, always return False to force generation + + Returns: + bool: True if file was updated in the last 24 hours and not forced, False otherwise + """ + # If force flag is provided, never skip + if force: + return False + + if not output_file.exists(): + return False + + # Get file modification time + mod_time = datetime.fromtimestamp(output_file.stat().st_mtime) + + # Check if file was modified in the last 24 hours + time_threshold = datetime.now() - timedelta(hours=24) + + return mod_time > time_threshold + +def process_single_file(source_file: Path, output_path: Path, api_key: str, force: bool = False): + """ + Process a single Python file. + + Args: + source_file: Path to the source Python file + output_path: Path to output the markdown file + api_key: Anthropic API key + force: If True, generate docs even if they were updated recently + """ + try: + # Create output file path + if output_path.is_dir(): + output_file = output_path / source_file.with_suffix('.md').name + else: + output_file = output_path + + # Check if docs were recently updated + if should_skip_doc_generation(output_file, force): + print(f"Skipping {source_file} - documentation updated within the last 24 hours") + return + + # Read the source file + with open(source_file, 'r', encoding='utf-8') as f: + file_content = f.read() + + # Load app.py context + app_context = load_app_context() + if app_context is None: + app_context = "No app.py context available." + + # Create the full prompt + message = CLAUDE_PROMPT.format( + app_context=app_context, + file_content=file_content + ) + + # Get documentation from Claude + markdown_content = call_claude_api(message, api_key) + + # Create necessary directories + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Write the markdown content (will overwrite if exists) + with open(output_file, 'w', encoding='utf-8') as f: + f.write(markdown_content) + + print(f"Generated documentation for: {source_file}") + print(f"Output saved to: {output_file}") + + except Exception as e: + print(f"Error processing {source_file}: {str(e)}", file=sys.stderr) + +def process_directory(source_dir: Path, output_dir: Path, api_key: str, force: bool = False): + """Process all Python files in the source directory recursively.""" + # Track statistics + total_files = 0 + processed_files = 0 + skipped_files = 0 + error_files = 0 + + start_time = time.time() + + # Walk through all files in source directory + for root, _, files in os.walk(source_dir): + for file in files: + if file.endswith('.py'): + # Get the source file path + source_file = Path(root) / file + total_files += 1 + + try: + # Calculate relative path to maintain directory structure + rel_path = source_file.relative_to(source_dir) + output_file = output_dir / rel_path.with_suffix('.md') + + # Create necessary directories + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Check if we should skip this file + if should_skip_doc_generation(output_file, force): + print(f"Skipping {source_file} - documentation updated within the last 24 hours") + skipped_files += 1 + continue + + # Process the file + process_single_file(source_file, output_file, api_key, force) + processed_files += 1 + + except Exception as e: + print(f"Error processing {source_file}: {str(e)}", file=sys.stderr) + error_files += 1 + + # Print summary + elapsed_time = time.time() - start_time + print("\nDocumentation Generation Summary:") + print(f"Total Python files found: {total_files}") + print(f"Files processed: {processed_files}") + print(f"Files skipped (updated in last 24h): {skipped_files}") + print(f"Files with errors: {error_files}") + print(f"Total time: {elapsed_time:.2f} seconds") + +def main(): + # Check if --force flag is provided + force_generation = False + source_path_arg = None + + for arg in sys.argv[1:]: + if arg == "--force": + force_generation = True + else: + source_path_arg = arg + + if not source_path_arg: + print("Usage: python script.py [--force]") + print("Note: source_path can be either a single .py file or a directory") + print("Options:") + print(" --force: Generate documentation even if it was updated within 24 hours") + print("\nPlease ensure .env_shell.json exists in the same directory with:") + print(" ANTHROPIC_API_KEY: Your Anthropic API key") + print(" API_DOC_OUTPUT_DIR: Directory where documentation will be saved") + sys.exit(1) + + # Load configuration from JSON file + api_key, output_dir = load_config() + + # Validate configuration + if not api_key: + print("Error: ANTHROPIC_API_KEY not found in configuration file") + sys.exit(1) + + if not output_dir: + print("Error: API_DOC_OUTPUT_DIR not found in configuration file") + sys.exit(1) + + output_path = Path(output_dir) + + # Get and validate source path + source_path = Path(source_path_arg) + + if not source_path.exists(): + print(f"Error: Source path does not exist: {source_path}") + sys.exit(1) + + if source_path.is_file() and not source_path.suffix == '.py': + print("Error: Source file must be a Python file (.py)") + sys.exit(1) + + # Create output directory if it doesn't exist + output_path.mkdir(parents=True, exist_ok=True) + + print(f"Starting documentation generation...") + print(f"Source: {source_path}") + print(f"Output: {output_path}") + if force_generation: + print(f"Force flag enabled: Will generate all documentation regardless of last update time.\n") + else: + print(f"Note: Files updated within the last 24 hours will be skipped (use --force to override).\n") + + # Process based on source type + if source_path.is_file(): + # For a single file + output_file = output_path / source_path.with_suffix('.md').name if output_path.is_dir() else output_path + + # Check if should skip + if should_skip_doc_generation(output_file, force_generation): + print(f"Skipping {source_path} - documentation updated within the last 24 hours") + else: + process_single_file(source_path, output_path, api_key, force_generation) + else: + process_directory(source_path, output_path, api_key, force_generation) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/generate_vector.sh b/generate_vector.sh new file mode 100755 index 0000000000000000000000000000000000000000..53c3f80bcca753021639ce7b946e2941dbc872df --- /dev/null +++ b/generate_vector.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +for file in $(find . -type f \( -iname "*.md" -o -iname "*.txt" -o -name "*.py" -o -name "Dockerfile" \) \ + -not -name "audio_mixing.py" \ + -not -name "authenticate.py" \ + -not -name "authentication.py" \ + -not -name "caption_video.py" \ + -not -name "combine_videos.py" \ + -not -name "extract_keyframes.py" \ + -not -name "ffmpeg_toolkit.py" \ + -not -name "file_management.py" \ + -not -name "image_to_video.py" \ + -not -name "media_to_mp3.py" \ + -not -name "transcribe_media.py" \ + -not -name "transcription.py"); do + echo "File: $file" >> "NCA Toolkit API Vector Doc.txt" + echo -e "\n\n" >> "NCA Toolkit API Vector Doc.txt" + cat "$file" >> "NCA Toolkit API Vector Doc.txt" + echo -e "\n\n" >> "NCA Toolkit API Vector Doc.txt" +done \ No newline at end of file diff --git a/local.sh b/local.sh new file mode 100755 index 0000000000000000000000000000000000000000..76928f7c4dea06bd2aaa991ca70577357b9d595c --- /dev/null +++ b/local.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +# Stop all running Docker containers +echo "Stopping no-code-architects running Docker containers..." +docker stop $(docker ps -a --filter ancestor=no-code-architects-toolkit:testing --format="{{.ID}}") + +# Build the Docker image +echo "Building Docker image..." +docker build -t no-code-architects-toolkit:testing . + +# Read variables from .variables file +echo "Reading environment variables..." +VARS=$(cat .env_variables.json) + +# Function to escape JSON strings for bash +escape_json() { + echo "$1" | sed 's/"/\\"/g' +} + +# Build the docker run command with environment variables +CMD="docker run -p 8080:8080" + +# Add environment variables from JSON +for key in $(echo "$VARS" | jq -r 'keys[]'); do + value=$(echo "$VARS" | jq -r --arg k "$key" '.[$k]') + + # Handle nested JSON (specifically for GCP_SA_CREDENTIALS) + if [[ "$key" == "GCP_SA_CREDENTIALS" ]]; then + value=$(echo "$VARS" | jq -r --arg k "$key" '.[$k]') + value=$(escape_json "$value") + fi + + CMD="$CMD -e $key=\"$value\"" +done + +# Complete the command +CMD="$CMD no-code-architects-toolkit:testing" + +# Run the Docker container +echo "Running Docker container..." +eval "$CMD" \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc1732461e30e0465b4e514ef7c81073ef512444 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,34 @@ +Flask +Werkzeug +requests +ffmpeg-python +gunicorn +pandas +APScheduler +srt +numpy +google-auth +google-auth-oauthlib +google-auth-httplib2 +google-api-python-client +google-cloud-storage +psutil +boto3 +Pillow +matplotlib +yt-dlp + + +beautifulsoup4 +openpyxl +seaborn +scikit-learn +scipy +pytesseract +face-recognition +mediapipe +qrcode[pil] +pdf2image +reportlab +pydub +librosa diff --git a/routes/audio_mixing.py b/routes/audio_mixing.py new file mode 100644 index 0000000000000000000000000000000000000000..fa1a781ae4dcf3e50081769df32d00584e8abe59 --- /dev/null +++ b/routes/audio_mixing.py @@ -0,0 +1,73 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.audio_mixing import process_audio_mixing +from services.authentication import authenticate +from services.cloud_storage import upload_file + +audio_mixing_bp = Blueprint('audio_mixing', __name__) +logger = logging.getLogger(__name__) + +@audio_mixing_bp.route('/audio-mixing', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"}, + "audio_url": {"type": "string", "format": "uri"}, + "video_vol": {"type": "number", "minimum": 0, "maximum": 100}, + "audio_vol": {"type": "number", "minimum": 0, "maximum": 100}, + "output_length": {"type": "string", "enum": ["video", "audio"]}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_url", "audio_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def audio_mixing(job_id, data): + video_url = data.get('video_url') + audio_url = data.get('audio_url') + video_vol = data.get('video_vol', 100) + audio_vol = data.get('audio_vol', 100) + output_length = data.get('output_length', 'video') + webhook_url = data.get('webhook_url') + id = data.get('id') + + logger.info(f"Job {job_id}: Received audio mixing request for {video_url} and {audio_url}") + + try: + # Process audio and video mixing + output_filename = process_audio_mixing( + video_url, audio_url, video_vol, audio_vol, output_length, job_id, webhook_url + ) + + # Upload the mixed file using the unified upload_file() method + cloud_url = upload_file(output_filename) + + logger.info(f"Job {job_id}: Mixed media uploaded to cloud storage: {cloud_url}") + + # Return the cloud URL for the uploaded file + return cloud_url, "/audio-mixing", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during audio mixing process - {str(e)}") + return str(e), "/audio-mixing", 500 diff --git a/routes/authenticate.py b/routes/authenticate.py new file mode 100644 index 0000000000000000000000000000000000000000..f8df31241622e4614ede286b4c3b4680ae17ff29 --- /dev/null +++ b/routes/authenticate.py @@ -0,0 +1,35 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint, request, jsonify, current_app +from app_utils import * +from functools import wraps +import os + +auth_bp = Blueprint('auth', __name__) + +API_KEY = os.environ.get('API_KEY') + +@auth_bp.route('/authenticate', methods=['GET']) +@queue_task_wrapper(bypass_queue=True) +def authenticate_endpoint(**kwargs): + api_key = request.headers.get('X-API-Key') + if api_key == API_KEY: + return "Authorized", "/authenticate", 200 + else: + return "Unauthorized", "/authenticate", 401 diff --git a/routes/caption_video.py b/routes/caption_video.py new file mode 100644 index 0000000000000000000000000000000000000000..8e886b20a00b832f55afb7e13b834b02b70b6034 --- /dev/null +++ b/routes/caption_video.py @@ -0,0 +1,92 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint, current_app +from app_utils import * +import logging +from services.caption_video import process_captioning +from services.authentication import authenticate +from services.cloud_storage import upload_file +import os + +caption_bp = Blueprint('caption', __name__) +logger = logging.getLogger(__name__) + +@caption_bp.route('/caption-video', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"}, + "srt": {"type": "string"}, + "ass": {"type": "string"}, + "options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "option": {"type": "string"}, + "value": {} # Allow any type for value + }, + "required": ["option", "value"] + } + }, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_url"], + "oneOf": [ + {"required": ["srt"]}, + {"required": ["ass"]} + ], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def caption_video(job_id, data): + video_url = data['video_url'] + caption_srt = data.get('srt') + caption_ass = data.get('ass') + options = data.get('options', []) + webhook_url = data.get('webhook_url') + id = data.get('id') + + logger.info(f"Job {job_id}: Received captioning request for {video_url}") + logger.info(f"Job {job_id}: Options received: {options}") + + if caption_ass is not None: + captions = caption_ass + caption_type = "ass" + else: + captions = caption_srt + caption_type = "srt" + + try: + output_filename = process_captioning(video_url, captions, caption_type, options, job_id) + logger.info(f"Job {job_id}: Captioning process completed successfully") + + # Upload the captioned video using the unified upload_file() method + cloud_url = upload_file(output_filename) + + logger.info(f"Job {job_id}: Captioned video uploaded to cloud storage: {cloud_url}") + + # Return the cloud URL for the uploaded file + return cloud_url, "/caption-video", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during captioning process - {str(e)}", exc_info=True) + return str(e), "/caption-video", 500 diff --git a/routes/combine_videos.py b/routes/combine_videos.py new file mode 100644 index 0000000000000000000000000000000000000000..0952179920e674681fde7d132047893c4d5f1b66 --- /dev/null +++ b/routes/combine_videos.py @@ -0,0 +1,70 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.ffmpeg_toolkit import process_video_combination +from services.authentication import authenticate +from services.cloud_storage import upload_file + +combine_bp = Blueprint('combine', __name__) +logger = logging.getLogger(__name__) + +@combine_bp.route('/combine-videos', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_urls": { + "type": "array", + "items": { + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"} + }, + "required": ["video_url"] + }, + "minItems": 1 + }, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_urls"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def combine_videos(job_id, data): + media_urls = data['video_urls'] + webhook_url = data.get('webhook_url') + id = data.get('id') + + logger.info(f"Job {job_id}: Received combine-videos request for {len(media_urls)} videos") + + try: + output_file = process_video_combination(media_urls, job_id) + logger.info(f"Job {job_id}: Video combination process completed successfully") + + cloud_url = upload_file(output_file) + logger.info(f"Job {job_id}: Combined video uploaded to cloud storage: {cloud_url}") + + return cloud_url, "/combine-videos", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during video combination process - {str(e)}") + return str(e), "/combine-videos", 500 \ No newline at end of file diff --git a/routes/extract_keyframes.py b/routes/extract_keyframes.py new file mode 100644 index 0000000000000000000000000000000000000000..764f7b1c54093040ce28b3a00eed402940e4a67b --- /dev/null +++ b/routes/extract_keyframes.py @@ -0,0 +1,66 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.extract_keyframes import process_keyframe_extraction +from services.authentication import authenticate +from services.cloud_storage import upload_file + +extract_keyframes_bp = Blueprint('extract_keyframes', __name__) +logger = logging.getLogger(__name__) + +@extract_keyframes_bp.route('/extract-keyframes', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def extract_keyframes(job_id, data): + video_url = data.get('video_url') + webhook_url = data.get('webhook_url') + id = data.get('id') + + logger.info(f"Job {job_id}: Received keyframe extraction request for {video_url}") + + try: + # Process keyframe extraction + image_paths = process_keyframe_extraction(video_url, job_id) + + # Upload each extracted keyframe and collect the cloud URLs + image_urls = [] + for image_path in image_paths: + cloud_url = upload_file(image_path) + image_urls.append({"image_url": cloud_url}) + + logger.info(f"Job {job_id}: Keyframes uploaded to cloud storage") + + # Return the URLs of the uploaded keyframes + return {"image_urls": image_urls}, "/extract-keyframes", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during keyframe extraction - {str(e)}") + return str(e), "/extract-keyframes", 500 diff --git a/routes/gdrive_upload.py b/routes/gdrive_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a42a23e5818af556ae454b46ff2adc8036be55 --- /dev/null +++ b/routes/gdrive_upload.py @@ -0,0 +1,265 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import logging +from flask import Blueprint, request, jsonify +import threading +import requests +import uuid +import json +from google.oauth2.service_account import Credentials +from google.auth.transport.requests import Request +from datetime import datetime +import time +import psutil +from services.authentication import authenticate +from app_utils import validate_payload, queue_task_wrapper + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Define the blueprint +gdrive_upload_bp = Blueprint('gdrive_upload', __name__) + +# Environment variables +GCP_SA_CREDENTIALS = os.getenv('GCP_SA_CREDENTIALS') +GDRIVE_USER = os.getenv('GDRIVE_USER') + +# Class to track upload progress +class UploadProgress: + def __init__(self, job_id, total_size): + self.job_id = job_id + self.total_size = total_size + self.bytes_uploaded = 0 + self.start_time = time.time() + self.lock = threading.Lock() + self.last_logged_percentage = 0 + self.last_logged_resource_percentage = 0 # For memory/disk logging every 5% + +# Global list to keep track of active uploads +active_uploads = [] +uploads_lock = threading.Lock() + +def get_access_token(): + """ + Retrieves an access token for Google APIs using service account credentials. + """ + credentials_info = json.loads(GCP_SA_CREDENTIALS) + credentials = Credentials.from_service_account_info( + credentials_info, + scopes=['https://www.googleapis.com/auth/drive'] + ) + delegated_credentials = credentials.with_subject(GDRIVE_USER) + if not delegated_credentials.valid or delegated_credentials.expired: + delegated_credentials.refresh(Request()) + access_token = delegated_credentials.token + return access_token + +def initiate_resumable_upload(filename, folder_id, mime_type='application/octet-stream'): + """ + Initiates a resumable upload session with Google Drive and returns the upload URL. + """ + url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable' + headers = { + 'Authorization': f'Bearer {get_access_token()}', + 'Content-Type': 'application/json; charset=UTF-8', + 'X-Upload-Content-Type': mime_type + } + metadata = { + 'name': filename, + 'parents': [folder_id] + } + response = requests.post(url, headers=headers, data=json.dumps(metadata)) + response.raise_for_status() + upload_url = response.headers['Location'] + return upload_url + +def upload_file_in_chunks(file_url, upload_url, total_size, job_id, chunk_size): + """ + Uploads the file to Google Drive in chunks by streaming data directly from the source URL. + """ + bytes_uploaded = 0 + max_retries = 5 + retry_delay = 5 # seconds + + progress = UploadProgress(job_id, total_size) + + # Add progress to active_uploads + with uploads_lock: + active_uploads.append(progress) + + try: + with requests.get(file_url, stream=True) as r: + r.raise_for_status() + iterator = r.iter_content(chunk_size=chunk_size) + for chunk in iterator: + if chunk: + for attempt in range(max_retries): + start = bytes_uploaded + end = bytes_uploaded + len(chunk) - 1 + content_range = f'bytes {start}-{end}/{total_size}' + headers = { + 'Content-Length': str(len(chunk)), + 'Content-Range': content_range, + } + try: + upload_response = requests.put( + upload_url, + headers=headers, + data=chunk + ) + if upload_response.status_code in (200, 201): + # Upload complete + logger.info(f"Job {job_id}: Upload complete.") + with progress.lock: + progress.bytes_uploaded = end + 1 + return upload_response.json()['id'] + elif upload_response.status_code == 308: + # Resumable upload incomplete + bytes_uploaded = end + 1 + with progress.lock: + progress.bytes_uploaded = bytes_uploaded + break # Break retry loop and continue with next chunk + else: + # Handle unexpected status codes + logger.error(f"Job {job_id}: Unexpected status code: {upload_response.status_code}") + raise Exception(f"Upload failed with status code {upload_response.status_code}") + except requests.exceptions.RequestException as e: + logger.error(f"Job {job_id}: Network error during upload: {e}") + if attempt < max_retries - 1: + logger.info(f"Job {job_id}: Retrying upload chunk after {retry_delay} seconds...") + time.sleep(retry_delay) + continue + else: + logger.error(f"Job {job_id}: Max retries reached. Upload failed.") + raise + else: + # If we exhausted retries, exit the function + raise Exception("Failed to upload chunk after multiple retries.") + finally: + # Remove progress from active_uploads + with uploads_lock: + if progress in active_uploads: + active_uploads.remove(progress) + +@gdrive_upload_bp.route('/gdrive-upload', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "file_url": {"type": "string", "format": "uri"}, + "filename": {"type": "string"}, + "folder_id": {"type": "string"}, + "mime_type": {"type": "string"}, + "chunk_size": {"type": "integer", "minimum": 1}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["file_url", "filename", "folder_id"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def gdrive_upload(job_id, data): + logger.info(f"Processing Job ID: {job_id}") + + if not GDRIVE_USER: + logger.error("GDRIVE_USER environment variable is not set") + return "GDRIVE_USER environment variable is not set", "/gdrive-upload", 400 + + try: + file_url = data['file_url'] + filename = data['filename'] + folder_id = data['folder_id'] + mime_type = data.get('mime_type', 'application/octet-stream') + chunk_size = data.get('chunk_size', 5 * 1024 * 1024) # Default to 5 MB + + # Get the total size of the file + try: + head_response = requests.head(file_url, allow_redirects=True, timeout=30) + head_response.raise_for_status() + total_size = int(head_response.headers.get('Content-Length', 0)) + + get_response = requests.get(file_url, stream=True, timeout=30) + get_response.raise_for_status() + total_size = int(get_response.headers.get('Content-Length', 0)) + if total_size == 0: + raise ValueError("Content-Length header is missing or zero") + except requests.exceptions.RequestException as e: + logger.error(f"Job {job_id}: Error accessing file URL: {str(e)}") + return f"Error accessing file URL: {str(e)}", "/gdrive-upload", 500 + except ValueError as e: + logger.error(f"Job {job_id}: {str(e)}") + return f"Unable to determine file size: {str(e)}", "/gdrive-upload", 500 + + logger.info(f"Job {job_id}: File size determined: {total_size} bytes") + + # Initiate upload session + upload_url = initiate_resumable_upload(filename, folder_id, mime_type) + logger.info(f"Job {job_id}: Resumable upload session initiated with chunk size {chunk_size} bytes.") + + # Upload file in chunks + file_id = upload_file_in_chunks(file_url, upload_url, total_size, job_id, chunk_size) + + return file_id, "/gdrive-upload", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during processing - {str(e)}") + return str(e), "/gdrive-upload", 500 + +def log_system_resources(): + """ + Logs system resource usage and upload progress at regular intervals. + """ + while True: + # Get memory and disk usage + memory_info = psutil.virtual_memory() + disk_info = psutil.disk_usage('/') + + with uploads_lock: + for progress in active_uploads: + with progress.lock: + # Calculate the percentage uploaded + percentage = (progress.bytes_uploaded / progress.total_size) * 100 if progress.total_size > 0 else 0 + elapsed_time = time.time() - progress.start_time + + # Log upload progress every 1% + if int(percentage) >= progress.last_logged_percentage + 1: + progress.last_logged_percentage = int(percentage) + logger.info( + f"Job {progress.job_id}: Uploaded {progress.bytes_uploaded} of {progress.total_size} bytes " + f"({percentage:.2f}%), Elapsed Time: {int(elapsed_time)} seconds" + ) + + # Log system resource usage every 5% + if int(percentage) >= progress.last_logged_resource_percentage + 5: + progress.last_logged_resource_percentage = int(percentage) + current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + logger.info(f"[{current_time}] Memory Usage: {memory_info.percent}% used") + logger.info(f"[{current_time}] Disk Usage: {disk_info.percent}% used") + + # Sleep for 1 second before the next update + time.sleep(1) + +# Start the resource logging in a separate thread +resource_logging_thread = threading.Thread( + target=log_system_resources, + daemon=True +) +resource_logging_thread.start() \ No newline at end of file diff --git a/routes/image_to_video.py b/routes/image_to_video.py new file mode 100644 index 0000000000000000000000000000000000000000..5a22372036827a4ebf2961d40c3a3861c7873b3d --- /dev/null +++ b/routes/image_to_video.py @@ -0,0 +1,72 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.image_to_video import process_image_to_video +from services.authentication import authenticate +from services.cloud_storage import upload_file + +image_to_video_bp = Blueprint('image_to_video', __name__) +logger = logging.getLogger(__name__) + +@image_to_video_bp.route('/image-to-video', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "image_url": {"type": "string", "format": "uri"}, + "length": {"type": "number", "minimum": 1, "maximum": 60}, + "frame_rate": {"type": "integer", "minimum": 15, "maximum": 60}, + "zoom_speed": {"type": "number", "minimum": 0, "maximum": 100}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["image_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def image_to_video(job_id, data): + image_url = data.get('image_url') + length = data.get('length', 5) + frame_rate = data.get('frame_rate', 30) + zoom_speed = data.get('zoom_speed', 3) / 100 + webhook_url = data.get('webhook_url') + id = data.get('id') + + logger.info(f"Job {job_id}: Received image to video request for {image_url}") + + try: + # Process image to video conversion + output_filename = process_image_to_video( + image_url, length, frame_rate, zoom_speed, job_id, webhook_url + ) + + # Upload the resulting file using the unified upload_file() method + cloud_url = upload_file(output_filename) + + # Log the successful upload + logger.info(f"Job {job_id}: Converted video uploaded to cloud storage: {cloud_url}") + + # Return the cloud URL for the uploaded file + return cloud_url, "/image-to-video", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error processing image to video: {str(e)}", exc_info=True) + return str(e), "/image-to-video", 500 diff --git a/routes/media_to_mp3.py b/routes/media_to_mp3.py new file mode 100644 index 0000000000000000000000000000000000000000..8513c6966e4e00f9bce0806410f3da442b8a1f79 --- /dev/null +++ b/routes/media_to_mp3.py @@ -0,0 +1,64 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +# routes/media_to_mp3.py +from flask import Blueprint, current_app +from app_utils import * +import logging +from services.ffmpeg_toolkit import process_conversion +from services.authentication import authenticate +from services.cloud_storage import upload_file +import os + +convert_bp = Blueprint('convert', __name__) +logger = logging.getLogger(__name__) + +@convert_bp.route('/media-to-mp3', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"}, + "bitrate": {"type": "string", "pattern": "^[0-9]+k$"} + }, + "required": ["media_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def convert_media_to_mp3(job_id, data): + media_url = data['media_url'] + webhook_url = data.get('webhook_url') + id = data.get('id') + bitrate = data.get('bitrate', '128k') + + logger.info(f"Job {job_id}: Received media-to-mp3 request for media URL: {media_url}") + + try: + output_file = process_conversion(media_url, job_id, bitrate) + logger.info(f"Job {job_id}: Media conversion process completed successfully") + + cloud_url = upload_file(output_file) + logger.info(f"Job {job_id}: Converted media uploaded to cloud storage: {cloud_url}") + + return cloud_url, "/media-to-mp3", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during media conversion process - {str(e)}") + return str(e), "/media-to-mp3", 500 \ No newline at end of file diff --git a/routes/transcribe_media.py b/routes/transcribe_media.py new file mode 100644 index 0000000000000000000000000000000000000000..78f839f51a49506825e65e4f6fe307ed5ca0ff4b --- /dev/null +++ b/routes/transcribe_media.py @@ -0,0 +1,68 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +import os +from services.transcription import process_transcription +from services.authentication import authenticate +from services.cloud_storage import upload_file + +transcribe_bp = Blueprint('transcribe', __name__) +logger = logging.getLogger(__name__) + +@transcribe_bp.route('/transcribe-media', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "output": {"type": "string", "enum": ["transcript", "srt", "vtt", "ass"]}, + "webhook_url": {"type": "string", "format": "uri"}, + "max_chars": {"type": "integer"}, + "id": {"type": "string"} + }, + "required": ["media_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def transcribe(job_id, data): + media_url = data['media_url'] + output = data.get('output', 'transcript') + webhook_url = data.get('webhook_url') + max_chars = data.get('max_chars', 56) + id = data.get('id') + + logger.info(f"Job {job_id}: Received transcription request for {media_url}") + + try: + result = process_transcription(media_url, output, max_chars) + logger.info(f"Job {job_id}: Transcription process completed successfully") + + # If the result is a file path, upload it using the unified upload_file() method + if output in ['srt', 'vtt', 'ass']: + cloud_url = upload_file(result) + os.remove(result) # Remove the temporary file after uploading + return cloud_url, "/transcribe-media", 200 + else: + return result, "/transcribe-media", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during transcription process - {str(e)}") + return str(e), "/transcribe-media", 500 diff --git a/routes/v1/audio/concatenate.py b/routes/v1/audio/concatenate.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5565a2b8c851792a786fd23615440ae7390b9f --- /dev/null +++ b/routes/v1/audio/concatenate.py @@ -0,0 +1,57 @@ +from flask import Blueprint +from app_utils import * +import logging +from services.v1.audio.concatenate import process_audio_concatenate +from services.authentication import authenticate +from services.cloud_storage import upload_file + +v1_audio_concatenate_bp = Blueprint("v1_audio_concatenate", __name__) +logger = logging.getLogger(__name__) + + +@v1_audio_concatenate_bp.route("/v1/audio/concatenate", methods=["POST"]) +@authenticate +@validate_payload( + { + "type": "object", + "properties": { + "audio_urls": { + "type": "array", + "items": { + "type": "object", + "properties": {"audio_url": {"type": "string", "format": "uri"}}, + "required": ["audio_url"], + }, + "minItems": 1, + }, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"}, + }, + "required": ["audio_urls"], + "additionalProperties": False, + } +) +@queue_task_wrapper(bypass_queue=False) +def combine_audio(job_id, data): + media_urls = data["audio_urls"] + webhook_url = data.get("webhook_url") + id = data.get("id") + + logger.info( + f"Job {job_id}: Received combine-audio request for {len(media_urls)} audio files" + ) + + try: + output_file = process_audio_concatenate(media_urls, job_id) + logger.info(f"Job {job_id}: Audio combination process completed successfully") + + cloud_url = upload_file(output_file) + logger.info( + f"Job {job_id}: Combined audio uploaded to cloud storage: {cloud_url}" + ) + + return cloud_url, "/v1/audio/concatenate", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during audio combination process - {str(e)}") + return str(e), "/v1/audio/concatenate", 500 diff --git a/routes/v1/code/execute/execute_python.py b/routes/v1/code/execute/execute_python.py new file mode 100644 index 0000000000000000000000000000000000000000..13dc07574776658a5d8a2e1b48efab3524355d13 --- /dev/null +++ b/routes/v1/code/execute/execute_python.py @@ -0,0 +1,140 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import logging +from flask import Blueprint, request +from services.authentication import authenticate +from app_utils import validate_payload, queue_task_wrapper +import subprocess +import tempfile +import json +import textwrap + +v1_code_execute_bp = Blueprint('v1_code_execute', __name__) +logger = logging.getLogger(__name__) + +@v1_code_execute_bp.route('/v1/code/execute/python', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "code": {"type": "string"}, + "timeout": {"type": "integer", "minimum": 1, "maximum": 300}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["code"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def execute_python(job_id, data): + logger.info(f"Job {job_id}: Received Python code execution request") + + try: + code = data['code'] + timeout = data.get('timeout', 30) + + # Indent user code + indented_code = textwrap.indent(code, ' ') + + with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as temp_file: + template = '''import sys +import json +from io import StringIO +import contextlib + +@contextlib.contextmanager +def capture_output(): + stdout, stderr = StringIO(), StringIO() + old_out, old_err = sys.stdout, sys.stderr + try: + sys.stdout, sys.stderr = stdout, stderr + yield stdout, stderr + finally: + sys.stdout, sys.stderr = old_out, old_err + +def execute_code(): +{} + +with capture_output() as (stdout, stderr): + try: + result_value = execute_code() + except Exception as e: + print(f"Error: {{str(e)}}", file=sys.stderr) + result_value = None + +result = {{ + 'stdout': stdout.getvalue(), + 'stderr': stderr.getvalue(), + 'return_value': result_value +}} +print(json.dumps(result)) +''' + + final_code = template.format(indented_code) + temp_file.write(final_code) + temp_file.flush() + + # Log the generated code for debugging + logger.debug(f"Generated code:\n{final_code}") + + try: + result = subprocess.run( + ['python3', temp_file.name], + capture_output=True, + text=True, + timeout=timeout + ) + + try: + output = json.loads(result.stdout) + if result.returncode != 0 or output['stderr']: + return { + 'error': output['stderr'] or 'Execution failed', + 'stdout': output['stdout'], + 'exit_code': result.returncode + }, '/v1/code/execute/python', 400 + + return { + 'result': output['return_value'], + 'stdout': output['stdout'], + 'stderr': output['stderr'], + 'exit_code': result.returncode + }, '/v1/code/execute/python', 200 + + except json.JSONDecodeError: + return { + 'error': 'Failed to parse execution result', + 'stdout': result.stdout, + 'stderr': result.stderr, + 'exit_code': result.returncode + }, '/v1/code/execute/python', 500 + + except subprocess.TimeoutExpired: + return {"error": f"Execution timed out after {timeout} seconds"}, '/v1/code/execute/python', 408 + except subprocess.SubprocessError as e: + return {"error": f"Execution failed: {str(e)}"}, '/v1/code/execute/python', 500 + + except Exception as e: + logger.error(f"Job {job_id}: Error executing Python code: {str(e)}") + return {"error": str(e)}, '/v1/code/execute/python', 500 + + finally: + if 'temp_file' in locals(): + os.unlink(temp_file.name) \ No newline at end of file diff --git a/routes/v1/ffmpeg/ffmpeg_compose.py b/routes/v1/ffmpeg/ffmpeg_compose.py new file mode 100644 index 0000000000000000000000000000000000000000..ce08752b5af4b52940215ebe95fb42917808c367 --- /dev/null +++ b/routes/v1/ffmpeg/ffmpeg_compose.py @@ -0,0 +1,149 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import logging +from flask import Blueprint, request, jsonify +from app_utils import * +from services.v1.ffmpeg.ffmpeg_compose import process_ffmpeg_compose +from services.authentication import authenticate +from services.cloud_storage import upload_file + +v1_ffmpeg_compose_bp = Blueprint('v1_ffmpeg_compose', __name__) +logger = logging.getLogger(__name__) + +@v1_ffmpeg_compose_bp.route('/v1/ffmpeg/compose', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "inputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "file_url": {"type": "string", "format": "uri"}, + "options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "option": {"type": "string"}, + "argument": {"type": ["string", "number", "null"]} + }, + "required": ["option"] + } + } + }, + "required": ["file_url"] + }, + "minItems": 1 + }, + "filters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "filter": {"type": "string"} + }, + "required": ["filter"] + } + }, + "outputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "option": {"type": "string"}, + "argument": {"type": ["string", "number", "null"]} + }, + "required": ["option"] + } + } + }, + "required": ["options"] + }, + "minItems": 1 + }, + "global_options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "option": {"type": "string"}, + "argument": {"type": ["string", "number", "null"]} + }, + "required": ["option"] + } + }, + "metadata": { + "type": "object", + "properties": { + "thumbnail": {"type": "boolean"}, + "filesize": {"type": "boolean"}, + "duration": {"type": "boolean"}, + "bitrate": {"type": "boolean"}, + "encoder": {"type": "boolean"} + } + }, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["inputs", "outputs"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def ffmpeg_api(job_id, data): + logger.info(f"Job {job_id}: Received flexible FFmpeg request") + + try: + output_filenames, metadata = process_ffmpeg_compose(data, job_id) + + # Upload output files to GCP and create result array + output_urls = [] + for i, output_filename in enumerate(output_filenames): + if os.path.exists(output_filename): + upload_url = upload_file(output_filename) + output_info = {"file_url": upload_url} + + if metadata and i < len(metadata): + output_metadata = metadata[i] + if 'thumbnail' in output_metadata: + thumbnail_path = output_metadata['thumbnail'] + if os.path.exists(thumbnail_path): + thumbnail_url = upload_file(thumbnail_path) + del output_metadata['thumbnail'] + output_metadata['thumbnail_url'] = thumbnail_url + os.remove(thumbnail_path) # Clean up local thumbnail file + output_info.update(output_metadata) + + output_urls.append(output_info) + os.remove(output_filename) # Clean up local output file after upload + else: + raise Exception(f"Expected output file {output_filename} not found") + + return output_urls, "/v1/ffmpeg/compose", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error processing FFmpeg request - {str(e)}") + return str(e), "/v1/ffmpeg/compose", 500 \ No newline at end of file diff --git a/routes/v1/image/convert/image_to_video.py b/routes/v1/image/convert/image_to_video.py new file mode 100644 index 0000000000000000000000000000000000000000..85fe42da8ec31f76b051826284199a33f95d915f --- /dev/null +++ b/routes/v1/image/convert/image_to_video.py @@ -0,0 +1,73 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.v1.image.convert.image_to_video import process_image_to_video +from services.authentication import authenticate +from services.cloud_storage import upload_file + +v1_image_convert_video_bp = Blueprint('v1_image_convert_video', __name__) +logger = logging.getLogger(__name__) + +@v1_image_convert_video_bp.route('/v1/image/convert/video', methods=['POST']) +@v1_image_convert_video_bp.route('/v1/image/transform/video', methods=['POST']) #depleft for backwards compatibility, do not use. +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "image_url": {"type": "string", "format": "uri"}, + "length": {"type": "number", "minimum": 0.1, "maximum": 400}, + "frame_rate": {"type": "integer", "minimum": 15, "maximum": 60}, + "zoom_speed": {"type": "number", "minimum": 0, "maximum": 100}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["image_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def image_to_video(job_id, data): + image_url = data.get('image_url') + length = data.get('length', 5) + frame_rate = data.get('frame_rate', 30) + zoom_speed = data.get('zoom_speed', 3) / 100 + webhook_url = data.get('webhook_url') + id = data.get('id') + + logger.info(f"Job {job_id}: Received image to video request for {image_url}") + + try: + # Process image to video conversion + output_filename = process_image_to_video( + image_url, length, frame_rate, zoom_speed, job_id, webhook_url + ) + + # Upload the resulting file using the unified upload_file() method + cloud_url = upload_file(output_filename) + + # Log the successful upload + logger.info(f"Job {job_id}: Converted video uploaded to cloud storage: {cloud_url}") + + # Return the cloud URL for the uploaded file + return cloud_url, "/v1/image/convert/video", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error processing image to video: {str(e)}", exc_info=True) + return str(e), "/v1/image/convert/video", 500 diff --git a/routes/v1/image/screenshot_webpage.py b/routes/v1/image/screenshot_webpage.py new file mode 100644 index 0000000000000000000000000000000000000000..63d4469688b85bbece9025806e54130bce148432 --- /dev/null +++ b/routes/v1/image/screenshot_webpage.py @@ -0,0 +1,125 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + +# Author: Harrison Fisher (https://github.com/HarrisonFisher) +# Date: April 2025 +# Created new route: /v1/playwright/screenshot + +from flask import Blueprint, request, jsonify +from app_utils import * +from app_utils import validate_payload, queue_task_wrapper +import logging +import os +from services.v1.image.screenshot_webpage import take_screenshot +from services.authentication import authenticate +from services.cloud_storage import upload_file +from playwright.sync_api import sync_playwright +from io import BytesIO + + +v1_image_screenshot_webpage_bp = Blueprint('v1_image_screenshot_webpage', __name__) +logger = logging.getLogger(__name__) + + +@v1_image_screenshot_webpage_bp.route('/v1/image/screenshot/webpage', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "url": {"type": "string", "format": "uri"}, + "html": {"type": "string"}, + "viewport_width": {"type": "integer", "minimum": 1}, + "viewport_height": {"type": "integer", "minimum": 1}, + "full_page": {"type": "boolean", "default": False}, + "format": {"type": "string", "enum": ["png", "jpeg"], "default": "png"}, + "delay": {"type": "integer", "minimum": 0}, + "device_scale_factor": {"type": "number", "minimum": 0.1}, + "user_agent": {"type": "string"}, + "cookies": { + "type": "array", + "items": { + "type": "object", + "required": ["name", "value", "domain"], + "properties": { + "name": {"type": "string"}, + "value": {"type": "string"}, + "domain": {"type": "string"}, + "path": {"type": "string", "default": "/"}, + }, + "additionalProperties": True + } + }, + "headers": { + "type": "object", + "additionalProperties": {"type": "string"} + }, + "quality": {"type": "integer", "minimum": 0, "maximum": 100}, + "clip": { + "type": "object", + "required": ["x", "y", "width", "height"], + "properties": { + "x": {"type": "number"}, + "y": {"type": "number"}, + "width": {"type": "number", "exclusiveMinimum": 0}, + "height": {"type": "number", "exclusiveMinimum": 0} + } + }, + "timeout": {"type": "integer", "minimum": 100}, + "wait_until": {"type": "string", "enum": ["load", "domcontentloaded", "networkidle", "networkidle2"], "default": "load"}, + "wait_for_selector": {"type": "string"}, + "emulate": { + "type": "object", + "properties": { + "color_scheme": { + "type": "string", + "enum": ["light", "dark"] + } + } + }, + "omit_background": {"type": "boolean", "default": False}, + "selector": {"type": "string"}, + "js": {"type": "string"}, + "css": {"type": "string"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "oneOf": [ + {"required": ["url"]}, + {"required": ["html"]} + ], + "not": {"required": ["url", "html"]}, + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def screenshot(job_id, data): + logger.info(f"Job {job_id}: Received screenshot request for {data.get('url')}") + try: + screenshot_io = take_screenshot(data, job_id) + if isinstance(screenshot_io, dict) and 'error' in screenshot_io: + logger.error(f"Job {job_id}: Screenshot error: {screenshot_io['error']}") + return {"error": screenshot_io['error']}, "/v1/image/screenshot/webpage", 400 + format = data.get("format", "png") + temp_file_path = f"{job_id}_screenshot.{format}" + with open(temp_file_path, "wb") as temp_file: + temp_file.write(screenshot_io.read()) + cloud_url = upload_file(temp_file_path) + os.remove(temp_file_path) + logger.info(f"Job {job_id}: Screenshot successfully processed and uploaded.") + return cloud_url, "/v1/image/screenshot/webpage", 200 + except Exception as e: + logger.error(f"Job {job_id}: Error processing screenshot: {str(e)}", exc_info=True) + return {"error": str(e)}, "/v1/image/screenshot/webpage", 500 \ No newline at end of file diff --git a/routes/v1/media/convert/media_convert.py b/routes/v1/media/convert/media_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..02a184c0aaf58e032489c9223f575ecf347bfc20 --- /dev/null +++ b/routes/v1/media/convert/media_convert.py @@ -0,0 +1,81 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from flask import Blueprint, jsonify +from app_utils import validate_payload, queue_task_wrapper +import logging +from services.v1.media.convert.media_convert import process_media_convert +from services.authentication import authenticate +from services.cloud_storage import upload_file +import os + +v1_media_convert_bp = Blueprint('v1_media_convert', __name__) +logger = logging.getLogger(__name__) + +@v1_media_convert_bp.route('/v1/media/convert', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "format": {"type": "string"}, + "video_codec": {"type": "string"}, + "video_preset": {"type": "string"}, + "video_crf": {"type": "number", "minimum": 0, "maximum": 51}, + "audio_codec": {"type": "string"}, + "audio_bitrate": {"type": "string"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["media_url", "format"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def convert_media_format(job_id, data): + media_url = data['media_url'] + output_format = data['format'] + video_codec = data.get('video_codec', 'libx264') + video_preset = data.get('video_preset', 'medium') + video_crf = data.get('video_crf', 23) + audio_codec = data.get('audio_codec', 'aac') + audio_bitrate = data.get('audio_bitrate', '128k') + webhook_url = data.get('webhook_url') + id = data.get('id') + + logger.info(f"Job {job_id}: Received media conversion request for media URL: {media_url} to format: {output_format}") + + try: + output_file = process_media_convert( + media_url, + job_id, + output_format, + video_codec, + video_preset, + video_crf, + audio_codec, + audio_bitrate, + webhook_url + ) + logger.info(f"Job {job_id}: Media format conversion completed successfully") + + cloud_url = upload_file(output_file) + logger.info(f"Job {job_id}: Converted media uploaded to cloud storage: {cloud_url}") + + return cloud_url, "/v1/media/convert", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during media conversion process - {str(e)}") + return {"error": str(e)}, "/v1/media/convert", 500 \ No newline at end of file diff --git a/routes/v1/media/convert/media_to_mp3.py b/routes/v1/media/convert/media_to_mp3.py new file mode 100644 index 0000000000000000000000000000000000000000..6a84ac90010fa8ea1016b0e2ce2c6cfddf4fcc92 --- /dev/null +++ b/routes/v1/media/convert/media_to_mp3.py @@ -0,0 +1,67 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +# routes/media_to_mp3.py +from flask import Blueprint, current_app +from app_utils import * +import logging +from services.v1.media.convert.media_to_mp3 import process_media_to_mp3 +from services.authentication import authenticate +from services.cloud_storage import upload_file +import os + +v1_media_convert_mp3_bp = Blueprint('v1_media_convert_mp3', __name__) +logger = logging.getLogger(__name__) + +@v1_media_convert_mp3_bp.route('/v1/media/convert/mp3', methods=['POST']) +@v1_media_convert_mp3_bp.route('/v1/media/transform/mp3', methods=['POST']) #depleft for backwards compatibility, do not use. +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"}, + "bitrate": {"type": "string", "pattern": "^[0-9]+k$"}, + "sample_rate": {"type": "number"} + }, + "required": ["media_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def convert_media_to_mp3(job_id, data): + media_url = data['media_url'] + webhook_url = data.get('webhook_url') + id = data.get('id') + bitrate = data.get('bitrate', '128k') + sample_rate = data.get('sample_rate') + + logger.info(f"Job {job_id}: Received media-to-mp3 request for media URL: {media_url}") + + try: + output_file = process_media_to_mp3(media_url, job_id, bitrate, sample_rate) + logger.info(f"Job {job_id}: Media conversion process completed successfully") + + cloud_url = upload_file(output_file) + logger.info(f"Job {job_id}: Converted media uploaded to cloud storage: {cloud_url}") + + return cloud_url, "/v1/media/transform/mp3", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during media conversion process - {str(e)}") + return str(e), "/v1/media/transform/mp3", 500 \ No newline at end of file diff --git a/routes/v1/media/download.py b/routes/v1/media/download.py new file mode 100644 index 0000000000000000000000000000000000000000..55e417da28d91c56282263de0d56b622d1fdc2f5 --- /dev/null +++ b/routes/v1/media/download.py @@ -0,0 +1,289 @@ +from flask import Blueprint +from app_utils import * +import logging +import os +import yt_dlp +import tempfile +from werkzeug.utils import secure_filename +import uuid +from services.cloud_storage import upload_file +from services.authentication import authenticate +from services.file_management import download_file +from urllib.parse import quote, urlparse +import requests + +v1_media_download_bp = Blueprint('v1_media_download', __name__) +logger = logging.getLogger(__name__) + +@v1_media_download_bp.route('/v1/BETA/media/download', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"}, + "cookie": {"type": "string", "description": "Path to cookie file, URL to cookie file, or cookie string in Netscape format"}, + "cloud_upload": {"type": "boolean"}, + "format": { + "type": "object", + "properties": { + "quality": {"type": "string"}, + "format_id": {"type": "string"}, + "resolution": {"type": "string"}, + "video_codec": {"type": "string"}, + "audio_codec": {"type": "string"} + } + }, + "audio": { + "type": "object", + "properties": { + "extract": {"type": "boolean"}, + "format": {"type": "string"}, + "quality": {"type": "string"} + } + }, + "thumbnails": { + "type": "object", + "properties": { + "download": {"type": "boolean"}, + "download_all": {"type": "boolean"}, + "formats": {"type": "array", "items": {"type": "string"}}, + "convert": {"type": "boolean"}, + "embed_in_audio": {"type": "boolean"} + } + }, + "subtitles": { + "type": "object", + "properties": { + "download": {"type": "boolean"}, + "languages": {"type": "array", "items": {"type": "string"}}, + "format": { + "type": "string", + "enum": [ + "srt", # SubRip Subtitle (most common) + "vtt", # Web Video Text Tracks + "json3" # YouTube's JSON format + ] + }, + "cloud_upload": {"type": "boolean"} + } + }, + "download": { + "type": "object", + "properties": { + "max_filesize": {"type": "integer"}, + "rate_limit": {"type": "string"}, + "retries": {"type": "integer"} + } + } + }, + "required": ["media_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def download_media(job_id, data): + media_url = data['media_url'] + cookie = data.get('cookie') + + format_options = data.get('format', {}) + audio_options = data.get('audio', {}) + thumbnail_options = data.get('thumbnails', {}) + subtitle_options = data.get('subtitles', {}) + download_options = data.get('download', {}) + + logger.info(f"Job {job_id}: Received download request for {media_url}") + + try: + # Create a temporary directory for downloads + with tempfile.TemporaryDirectory() as temp_dir: + # Configure yt-dlp options + ydl_opts = { + 'format': 'best', # Download best quality + 'outtmpl': os.path.join(temp_dir, '%(title)s.%(ext)s'), + 'quiet': True, + 'no_warnings': True, + 'download': data.get('cloud_upload', True) + } + + # Add cookies if provided + if cookie: + if os.path.isfile(cookie): + ydl_opts['cookiefile'] = cookie + elif urlparse(cookie).scheme in ('http', 'https'): + # If cookie is a URL, download it first + ydl_opts['cookiefile'] = download_file(cookie, temp_dir) + else: + # If cookie is a string, write it to a temporary file + cookie_file = os.path.join(temp_dir, 'cookies.txt') + with open(cookie_file, 'w') as f: + f.write(cookie) + ydl_opts['cookiefile'] = cookie_file + + # Add format options if specified + if format_options: + format_str = [] + if format_options.get('quality'): + format_str.append(format_options['quality']) + if format_options.get('format_id'): + format_str.append(format_options['format_id']) + if format_options.get('resolution'): + format_str.append(format_options['resolution']) + if format_options.get('video_codec'): + format_str.append(format_options['video_codec']) + if format_options.get('audio_codec'): + format_str.append(format_options['audio_codec']) + if format_str: + ydl_opts['format'] = '+'.join(format_str) + + # Add audio options if specified + if audio_options: + if audio_options.get('extract'): + ydl_opts['extract_audio'] = True + if audio_options.get('format'): + ydl_opts['audio_format'] = audio_options['format'] + if audio_options.get('quality'): + ydl_opts['audio_quality'] = audio_options['quality'] + + # Add thumbnail options if specified + if thumbnail_options: + ydl_opts['writesubtitles'] = thumbnail_options.get('download', False) + ydl_opts['writeallsubtitles'] = thumbnail_options.get('download_all', False) + if thumbnail_options.get('formats'): + ydl_opts['subtitleslangs'] = thumbnail_options['formats'] + ydl_opts['convert_thumbnails'] = thumbnail_options.get('convert', False) + ydl_opts['embed_thumbnail_in_audio'] = thumbnail_options.get('embed_in_audio', False) + + # Add subtitle options if specified + if subtitle_options: + ydl_opts['writesubtitles'] = subtitle_options.get('download', False) + if subtitle_options.get('languages'): + ydl_opts['subtitleslangs'] = subtitle_options['languages'] + if subtitle_options.get('format'): + ydl_opts['subtitlesformat'] = subtitle_options['format'] + + # Add download options if specified + if download_options: + if download_options.get('max_filesize'): + ydl_opts['max_filesize'] = download_options['max_filesize'] + if download_options.get('rate_limit'): + ydl_opts['limit_rate'] = download_options['rate_limit'] + if download_options.get('retries'): + ydl_opts['retries'] = download_options['retries'] + + # Download the media + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(media_url, download=data.get('cloud_upload', True)) + + if not data.get('cloud_upload', True): + media_url = info['url'] + else: + filename = ydl.prepare_filename(info) + # Upload to cloud storage + media_url = upload_file(filename) + # Clean up the temporary file + os.remove(filename) + + # Prepare response + response = { + "media": { + "media_url": media_url, + "title": info.get('title'), + "format_id": info.get('format_id'), + "ext": info.get('ext'), + "resolution": info.get('resolution'), + "filesize": info.get('filesize'), + "width": info.get('width'), + "height": info.get('height'), + "fps": info.get('fps'), + "video_codec": info.get('vcodec'), + "audio_codec": info.get('acodec'), + "upload_date": info.get('upload_date'), + "duration": info.get('duration'), + "view_count": info.get('view_count'), + "uploader": info.get('uploader'), + "uploader_id": info.get('uploader_id'), + "description": info.get('description') + } + } + + # Add thumbnails if available and requested + if info.get('thumbnails') and thumbnail_options.get('download', False): + response["thumbnails"] = [] + for thumbnail in info['thumbnails']: + if thumbnail.get('url'): + try: + # Download the thumbnail first + thumbnail_path = download_file(thumbnail['url'], temp_dir) + # Upload to cloud storage + thumbnail_url = upload_file(thumbnail_path) + # Clean up the temporary thumbnail file + os.remove(thumbnail_path) + + response["thumbnails"].append({ + "id": thumbnail.get('id', 'default'), + "image_url": thumbnail_url, + "width": thumbnail.get('width'), + "height": thumbnail.get('height'), + "original_format": thumbnail.get('ext'), + "converted": thumbnail.get('converted', False) + }) + except Exception as e: + logger.error(f"Error processing thumbnail: {str(e)}") + continue + + # Process subtitles if available + if 'subtitles' in info and subtitle_options.get('download', False): + logger.info(f"Job {job_id}: Found subtitles in info: {info['subtitles']}") + response["subtitles"] = {} # Changed from array to object + requested_languages = subtitle_options.get('languages', []) + requested_format = subtitle_options.get('format', 'srt') + subtitle_cloud_upload = subtitle_options.get('cloud_upload', True) # Default to True + + # If no languages specified, use all available languages + if not requested_languages: + requested_languages = list(info['subtitles'].keys()) + logger.info(f"Job {job_id}: No languages specified, using all available: {requested_languages}") + + for lang, subtitle_list in info['subtitles'].items(): + # Skip if language not in requested list + if lang not in requested_languages: + continue + + try: + logger.info(f"Job {job_id}: Processing subtitle for language {lang}") + # Find the requested format + subtitle_data = None + for subtitle in subtitle_list: + if subtitle['ext'] == requested_format: + subtitle_data = subtitle + break + + if not subtitle_data: + logger.warning(f"Job {job_id}: Requested format {requested_format} not available for {lang}") + continue + + # If cloud upload is requested, download and upload the subtitle + if subtitle_cloud_upload: + try: + subtitle_path = download_file(subtitle_data['url'], temp_dir) + cloud_url = upload_file(subtitle_path) + subtitle_data['url'] = cloud_url + except Exception as e: + logger.warning(f"Job {job_id}: Failed to download subtitle for {lang}: {str(e)}") + continue + + # Add subtitle data to response using language code as key + response["subtitles"][lang] = subtitle_data + logger.info(f"Job {job_id}: Successfully processed subtitle for {lang}") + except Exception as e: + logger.error(f"Job {job_id}: Error processing subtitle: {str(e)}") + continue + else: + logger.info(f"Job {job_id}: No subtitles found in info or download not requested") + + return response, "/v1/media/download", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during download process - {str(e)}") + return str(e), "/v1/media/download", 500 \ No newline at end of file diff --git a/routes/v1/media/feedback.py b/routes/v1/media/feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..dbadfaabc7adb2b3658498ee78ab1451cbd673f1 --- /dev/null +++ b/routes/v1/media/feedback.py @@ -0,0 +1,185 @@ +from flask import Blueprint, send_from_directory, current_app, request, redirect, url_for, make_response +import os +import mimetypes +import re +from services.v1.media.feedback.feedback import get_feedback_path + +# Ensure correct MIME types for Next.js assets +mimetypes.add_type('application/javascript', '.js') +mimetypes.add_type('text/css', '.css') +mimetypes.add_type('font/woff2', '.woff2') + +# Base URL path for assets +BASE_PATH = '/v1/media/feedback' + +v1_media_feedback_bp = Blueprint('v1_media_feedback', __name__, url_prefix='/v1/media/feedback', static_folder=None) + +def create_root_next_routes(app): + """ + Create routes at the application root level to handle Next.js asset paths + This helps with client-side navigation and dynamic asset loading + """ + @app.route('/_next/') + def root_next_static(path): + """Redirect root-level Next.js requests to our namespaced route""" + return redirect(f'{BASE_PATH}/_next/{path}') + + @app.route('/favicon.ico') + def root_favicon(): + """Redirect favicon requests to our namespaced route""" + return redirect(f'{BASE_PATH}/favicon.ico') + + @app.route('/logo.png') + def root_logo(): + """Redirect logo requests to our namespaced route""" + return redirect(f'{BASE_PATH}/logo.png') + +@v1_media_feedback_bp.route('', methods=['GET']) +def serve_feedback_page(): + """ + Serve the feedback HTML page with path corrections + """ + try: + # Get the feedback static files directory path + feedback_path = get_feedback_path() + + # Read the HTML file content + with open(os.path.join(feedback_path, 'index.html'), 'r') as f: + content = f.read() + + # Fix paths in the HTML content to include the base path + # Replace resource paths + content = content.replace('href="/_next/', f'href="{BASE_PATH}/_next/') + content = content.replace('src="/_next/', f'src="{BASE_PATH}/_next/') + content = content.replace('href="/favicon.ico', f'href="{BASE_PATH}/favicon.ico') + content = content.replace('href="/logo.png', f'href="{BASE_PATH}/logo.png') + content = content.replace('src="/logo.png', f'src="{BASE_PATH}/logo.png') + + # Create response with modified content + response = make_response(content) + response.headers['Content-Type'] = 'text/html' + return response + except Exception as e: + current_app.logger.error(f"Error serving index.html: {str(e)}") + return str(e), 'serve_feedback_page', 500 + +@v1_media_feedback_bp.route('/_next/', methods=['GET']) +def serve_next_static(path): + """ + Serve Next.js static files from _next directory + """ + try: + feedback_path = get_feedback_path() + file_path = os.path.join('_next', path) + full_path = os.path.join(feedback_path, file_path) + + # Get the file extension for MIME type detection + _, ext = os.path.splitext(path) + + # Handle special case for JS files to fix paths + if ext == '.js': + if os.path.exists(full_path): + try: + with open(full_path, 'r') as f: + content = f.read() + + # Fix paths in JS files that might reference other assets + if '/_next/' in content: + content = content.replace('href:"/_next/', f'href:"{BASE_PATH}/_next/') + content = content.replace('src:"/_next/', f'src:"{BASE_PATH}/_next/') + + # Create response with modified content + response = make_response(content) + response.headers['Content-Type'] = 'application/javascript' + return response + except UnicodeDecodeError: + # If we can't read as text, serve as binary + pass + + # Handle special case for font files + if ext == '.woff2' or ext == '.woff' or ext == '.ttf' or ext == '.eot': + response = send_from_directory(feedback_path, file_path) + if ext == '.woff2': + response.headers['Content-Type'] = 'font/woff2' + elif ext == '.woff': + response.headers['Content-Type'] = 'font/woff' + elif ext == '.ttf': + response.headers['Content-Type'] = 'font/ttf' + elif ext == '.eot': + response.headers['Content-Type'] = 'application/vnd.ms-fontobject' + + # Add CORS headers for font files + response.headers['Access-Control-Allow-Origin'] = '*' + return response + + # For other files, serve directly + mime_type = mimetypes.types_map.get(ext, 'application/octet-stream') + + response = send_from_directory(feedback_path, file_path) + response.headers['Content-Type'] = mime_type + + # Add CORS headers for font files + if ext == '.woff2' or ext == '.woff' or ext == '.ttf' or ext == '.eot': + response.headers['Access-Control-Allow-Origin'] = '*' + + return response + except Exception as e: + current_app.logger.error(f"Error serving Next.js static file {path}: {str(e)}") + return str(e), 'serve_next_static', 500 + +@v1_media_feedback_bp.route('/', methods=['GET']) +def serve_feedback_static(filename): + """ + Serve static files for the feedback page (CSS, JS, images, etc.) + """ + try: + # Get the feedback static files directory path + feedback_path = get_feedback_path() + + # Special handling for CSS files that might need path rewriting + _, ext = os.path.splitext(filename) + if ext == '.css': + full_path = os.path.join(feedback_path, filename) + if os.path.exists(full_path): + with open(full_path, 'r') as f: + content = f.read() + + # Rewrite paths in CSS if needed + if 'url(/_next/' in content: + content = content.replace('url(/_next/', f'url({BASE_PATH}/_next/') + + # Create response with modified content + response = make_response(content) + response.headers['Content-Type'] = 'text/css' + return response + + # Handle JavaScript files + if ext == '.js': + full_path = os.path.join(feedback_path, filename) + if os.path.exists(full_path): + with open(full_path, 'r') as f: + content = f.read() + + # Rewrite paths in JS if needed + if '/_next/' in content: + content = content.replace('href:"/_next/', f'href:"{BASE_PATH}/_next/') + content = content.replace('src:"/_next/', f'src:"{BASE_PATH}/_next/') + + # Create response with modified content + response = make_response(content) + response.headers['Content-Type'] = 'application/javascript' + return response + + # For image and other static files + mime_type = mimetypes.types_map.get(ext, 'application/octet-stream') + + # Serve the requested static file + response = send_from_directory(feedback_path, filename) + response.headers['Content-Type'] = mime_type + return response + except FileNotFoundError: + current_app.logger.error(f"Static file not found: {filename}") + return "File not found", 404 + except Exception as e: + current_app.logger.error(f"Error serving static file {filename}: {str(e)}") + return str(e), 500 diff --git a/routes/v1/media/generate_ass.py b/routes/v1/media/generate_ass.py new file mode 100644 index 0000000000000000000000000000000000000000..72a67f819a0dbc3e79fcc0d9a5c82cb933c13f41 --- /dev/null +++ b/routes/v1/media/generate_ass.py @@ -0,0 +1,144 @@ +from flask import Blueprint, jsonify, request +from app_utils import validate_payload, queue_task_wrapper +import logging +from services.ass_toolkit import generate_ass_captions_v1 +from services.authentication import authenticate +from services.cloud_storage import upload_file +import os +import requests + +v1_media_generate_ass_bp = Blueprint('v1_media_generate_ass', __name__) +logger = logging.getLogger(__name__) + +@v1_media_generate_ass_bp.route('/v1/media/generate/ass', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "canvas_width": {"type": "integer", "minimum": 1}, + "canvas_height": {"type": "integer", "minimum": 1}, + "settings": { + "type": "object", + "properties": { + "line_color": {"type": "string"}, + "word_color": {"type": "string"}, + "outline_color": {"type": "string"}, + "all_caps": {"type": "boolean"}, + "max_words_per_line": {"type": "integer"}, + "x": {"type": "integer"}, + "y": {"type": "integer"}, + "position": { + "type": "string", + "enum": [ + "bottom_left", "bottom_center", "bottom_right", + "middle_left", "middle_center", "middle_right", + "top_left", "top_center", "top_right" + ] + }, + "alignment": { + "type": "string", + "enum": ["left", "center", "right"] + }, + "font_family": {"type": "string"}, + "font_size": {"type": "integer"}, + "bold": {"type": "boolean"}, + "italic": {"type": "boolean"}, + "underline": {"type": "boolean"}, + "strikeout": {"type": "boolean"}, + "style": { + "type": "string", + "enum": ["classic", "karaoke", "highlight", "underline", "word_by_word"] + }, + "outline_width": {"type": "integer"}, + "spacing": {"type": "integer"}, + "angle": {"type": "integer"}, + "shadow_offset": {"type": "integer"} + }, + "additionalProperties": False + }, + "replace": { + "type": "array", + "items": { + "type": "object", + "properties": { + "find": {"type": "string"}, + "replace": {"type": "string"} + }, + "required": ["find", "replace"] + } + }, + "exclude_time_ranges": { + "type": "array", + "items": { + "type": "object", + "properties": { + "start": { "type": "string" }, + "end": { "type": "string" } + }, + "required": ["start", "end"], + "additionalProperties": False + } + }, + "language": {"type": "string"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "additionalProperties": False, + "required": ["media_url"], + "oneOf": [ + { "required": ["canvas_width", "canvas_height"] }, + { "not": { "anyOf": [ { "required": ["canvas_width"] }, { "required": ["canvas_height"] } ] } } + ] + +}) + +@queue_task_wrapper(bypass_queue=False) +def generate_ass_v1(job_id, data): + media_url = data['media_url'] + settings = data.get('settings', {}) + replace = data.get('replace', []) + exclude_time_ranges = data.get('exclude_time_ranges', []) + webhook_url = data.get('webhook_url') + id = data.get('id') + language = data.get('language', 'auto') + canvas_width = data.get('canvas_width') + canvas_height = data.get('canvas_height') + + logger.info(f"Job {job_id}: Received ASS generation request for {media_url}") + logger.info(f"Job {job_id}: Settings received: {settings}") + logger.info(f"Job {job_id}: Replace rules received: {replace}") + logger.info(f"Job {job_id}: Exclude time ranges received: {exclude_time_ranges}") + + try: + output = generate_ass_captions_v1( + media_url, + captions=None, + settings=settings, + replace=replace, + exclude_time_ranges=exclude_time_ranges, + job_id=job_id, + language=language, + PlayResX=canvas_width, + PlayResY=canvas_height + ) + if isinstance(output, dict) and 'error' in output: + if 'available_fonts' in output: + return {"error": output['error'], "available_fonts": output['available_fonts']}, "/v1/media/generate/ass", 400 + else: + return {"error": output['error']}, "/v1/media/generate/ass", 400 + + ass_path = output + logger.info(f"Job {job_id}: ASS file generated at {ass_path}") + + cloud_url = upload_file(ass_path) + logger.info(f"Job {job_id}: ASS file uploaded to cloud storage: {cloud_url}") + + os.remove(ass_path) + logger.info(f"Job {job_id}: Cleaned up local ASS file") + + return cloud_url, "/v1/media/generate/ass", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during ASS generation process - {str(e)}", exc_info=True) + return {"error": str(e)}, "/v1/media/generate/ass", 500 diff --git a/routes/v1/media/media_transcribe.py b/routes/v1/media/media_transcribe.py new file mode 100644 index 0000000000000000000000000000000000000000..9609210bc9aec4b1b8434ecc62235919a21868b5 --- /dev/null +++ b/routes/v1/media/media_transcribe.py @@ -0,0 +1,108 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +import os +from services.v1.media.media_transcribe import process_transcribe_media +from services.authentication import authenticate +from services.cloud_storage import upload_file + +v1_media_transcribe_bp = Blueprint('v1_media_transcribe', __name__) +logger = logging.getLogger(__name__) + +@v1_media_transcribe_bp.route('/v1/media/transcribe', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "task": {"type": "string", "enum": ["transcribe", "translate"]}, + "include_text": {"type": "boolean"}, + "include_srt": {"type": "boolean"}, + "include_segments": {"type": "boolean"}, + "word_timestamps": {"type": "boolean"}, + "response_type": {"type": "string", "enum": ["direct", "cloud"]}, + "language": {"type": "string"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"}, + "words_per_line": {"type": "integer", "minimum": 1} + }, + "required": ["media_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def transcribe(job_id, data): + media_url = data['media_url'] + task = data.get('task', 'transcribe') + include_text = data.get('include_text', True) + include_srt = data.get('include_srt', False) + include_segments = data.get('include_segments', False) + word_timestamps = data.get('word_timestamps', False) + response_type = data.get('response_type', 'direct') + language = data.get('language', None) + webhook_url = data.get('webhook_url') + id = data.get('id') + words_per_line = data.get('words_per_line', None) + + logger.info(f"Job {job_id}: Received transcription request for {media_url}") + + try: + result = process_transcribe_media(media_url, task, include_text, include_srt, include_segments, word_timestamps, response_type, language, job_id, words_per_line) + logger.info(f"Job {job_id}: Transcription process completed successfully") + + # If the result is a file path, upload it using the unified upload_file() method + if response_type == "direct": + + result_json = { + "text": result[0], + "srt": result[1], + "segments": result[2], + "text_url": None, + "srt_url": None, + "segments_url": None, + } + + return result_json, "/v1/transcribe/media", 200 + + else: + + cloud_urls = { + "text": None, + "srt": None, + "segments": None, + "text_url": upload_file(result[0]) if include_text is True else None, + "srt_url": upload_file(result[1]) if include_srt is True else None, + "segments_url": upload_file(result[2]) if include_segments is True else None, + } + + if include_text is True: + os.remove(result[0]) # Remove the temporary file after uploading + + if include_srt is True: + os.remove(result[1]) + + if include_segments is True: + os.remove(result[2]) + + return cloud_urls, "/v1/transcribe/media", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during transcription process - {str(e)}") + return str(e), "/v1/transcribe/media", 500 diff --git a/routes/v1/media/metadata.py b/routes/v1/media/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ee861730632bf31850fce613208b6d26dd7f21 --- /dev/null +++ b/routes/v1/media/metadata.py @@ -0,0 +1,72 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint, request, jsonify +from app_utils import validate_payload, queue_task_wrapper +import logging +from services.v1.media.metadata import get_media_metadata +from services.authentication import authenticate + +# Set up logger +logger = logging.getLogger(__name__) + +# Create blueprint +v1_media_metadata_bp = Blueprint('v1_media_metadata', __name__) + +@v1_media_metadata_bp.route('/v1/media/metadata', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["media_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=True) # Set to execute immediately instead of queueing +def media_metadata(job_id, data): + """ + Extract metadata from a media file, including video and audio properties. + + Expected input: + { + "media_url": "https://example.com/media.mp4", + "webhook_url": "https://example.com/webhook" (optional), + "id": "custom-id" (optional) + } + + Returns metadata including filesize, duration, video/audio codec info, + resolution, frame rate, and bitrates. + """ + media_url = data['media_url'] + logger.info(f"Job {job_id}: Received metadata request for {media_url}") + + try: + # Extract metadata from the media file + metadata = get_media_metadata(media_url, job_id) + logger.info(f"Job {job_id}: Successfully extracted metadata") + + # Return the metadata directly + return metadata, "/v1/media/metadata", 200 + + except Exception as e: + error_message = str(e) + logger.error(f"Job {job_id}: Error extracting metadata - {error_message}") + return error_message, "/v1/media/metadata", 500 \ No newline at end of file diff --git a/routes/v1/media/silence.py b/routes/v1/media/silence.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4acc1158fa9ab9b7ee33e1138650611ec853e0 --- /dev/null +++ b/routes/v1/media/silence.py @@ -0,0 +1,73 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.v1.media.silence import detect_silence +from services.authentication import authenticate + +v1_media_silence_bp = Blueprint('v1_media_silence', __name__) +logger = logging.getLogger(__name__) + +@v1_media_silence_bp.route('/v1/media/silence', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "media_url": {"type": "string", "format": "uri"}, + "start": {"type": "string"}, + "end": {"type": "string"}, + "noise": {"type": "string"}, + "duration": {"type": "number", "minimum": 0.1}, + "mono": {"type": "boolean"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["media_url", "duration"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def silence(job_id, data): + """Detect silence in a media file and return the silence intervals.""" + media_url = data['media_url'] + start_time = data.get('start', None) # None = start from beginning + end_time = data.get('end', None) # None = process until end + noise_threshold = data.get('noise', '-30dB') + min_duration = data['duration'] # Required parameter + mono = data.get('mono', True) # Default to True + + logger.info(f"Job {job_id}: Received silence detection request for {media_url}") + + try: + silence_intervals = detect_silence( + media_url=media_url, + start_time=start_time, + end_time=end_time, + noise_threshold=noise_threshold, + min_duration=min_duration, + mono=mono, + job_id=job_id + ) + + logger.info(f"Job {job_id}: Silence detection completed successfully") + return silence_intervals, "/v1/media/silence", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during silence detection process - {str(e)}") + return str(e), "/v1/media/silence", 500 \ No newline at end of file diff --git a/routes/v1/s3/upload.py b/routes/v1/s3/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..8d4a4369e669b26e3abd651800025b9ebf36a648 --- /dev/null +++ b/routes/v1/s3/upload.py @@ -0,0 +1,61 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint, request, jsonify +from services.authentication import authenticate +from app_utils import validate_payload, queue_task_wrapper +from services.v1.s3.upload import stream_upload_to_s3 +import os +import json +import logging + +logger = logging.getLogger(__name__) +v1_s3_upload_bp = Blueprint('v1_s3_upload', __name__) + +@v1_s3_upload_bp.route('/v1/s3/upload', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "file_url": {"type": "string", "format": "uri"}, + "filename": {"type": "string"}, + "public": {"type": "boolean"}, + "download_headers": {"type": "object"} + }, + "required": ["file_url"] +}) +@queue_task_wrapper(bypass_queue=False) +def s3_upload_endpoint(job_id, data): + try: + file_url = data.get('file_url') + filename = data.get('filename') # Optional, will default to original filename if not provided + make_public = data.get('public', False) # Default to private + download_headers = data.get('download_headers') # Optional headers for authentication + + logger.info(f"Job {job_id}: Starting S3 streaming upload from {file_url}") + + # Call the service function to handle the upload + result = stream_upload_to_s3(file_url, filename, make_public, download_headers) + + logger.info(f"Job {job_id}: Successfully uploaded to S3") + + return result, "/v1/s3/upload", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error streaming upload to S3 - {str(e)}") + return str(e), "/v1/s3/upload", 500 \ No newline at end of file diff --git a/routes/v1/toolkit/authenticate.py b/routes/v1/toolkit/authenticate.py new file mode 100644 index 0000000000000000000000000000000000000000..b38533437fee379c000de8c3657e5120258f63db --- /dev/null +++ b/routes/v1/toolkit/authenticate.py @@ -0,0 +1,35 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint, request, jsonify, current_app +from app_utils import * +from functools import wraps +import os + +v1_toolkit_auth_bp = Blueprint('v1_toolkit_auth', __name__) + +API_KEY = os.environ.get('API_KEY') + +@v1_toolkit_auth_bp.route('/v1/toolkit/authenticate', methods=['GET']) +@queue_task_wrapper(bypass_queue=True) +def authenticate_endpoint(**kwargs): + api_key = request.headers.get('X-API-Key') + if api_key == API_KEY: + return "Authorized", "/authenticate", 200 + else: + return "Unauthorized", "/authenticate", 401 diff --git a/routes/v1/toolkit/job_status.py b/routes/v1/toolkit/job_status.py new file mode 100644 index 0000000000000000000000000000000000000000..aebf7ec92b17cd51e80bcd65f80db5f24a5949ec --- /dev/null +++ b/routes/v1/toolkit/job_status.py @@ -0,0 +1,65 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import json +import logging +from flask import Blueprint, request +from config import LOCAL_STORAGE_PATH +from services.authentication import authenticate +from app_utils import queue_task_wrapper, validate_payload + +v1_toolkit_job_status_bp = Blueprint('v1_toolkit_job_status', __name__) +logger = logging.getLogger(__name__) + +@v1_toolkit_job_status_bp.route('/v1/toolkit/job/status', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "job_id": { + "type": "string" + } + }, + "required": ["job_id"], +}) +@queue_task_wrapper(bypass_queue=True) +def get_job_status(job_id, data): + + get_job_id = data.get('job_id') + + logger.info(f"Retrieving status for job {get_job_id}") + + try: + # Construct the path to the job status file + job_file_path = os.path.join(LOCAL_STORAGE_PATH, 'jobs', f"{get_job_id}.json") + + # Check if the job file exists + if not os.path.exists(job_file_path): + return {"error": "Job not found", "job_id": get_job_id}, endpoint, 404 + + # Read the job status file + with open(job_file_path, 'r') as file: + job_status = json.load(file) + + # Return the job status file content directly + return job_status, "/v1/toolkit/job/status", 200 + + except Exception as e: + logger.error(f"Error retrieving status for job {get_job_id}: {str(e)}") + return {"error": f"Failed to retrieve job status: {str(e)}"}, endpoint, 500 \ No newline at end of file diff --git a/routes/v1/toolkit/jobs_status.py b/routes/v1/toolkit/jobs_status.py new file mode 100644 index 0000000000000000000000000000000000000000..75ef18eac533083061ffe6acc4b007f5fe3ede74 --- /dev/null +++ b/routes/v1/toolkit/jobs_status.py @@ -0,0 +1,89 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import json +import logging +import time +from flask import Blueprint, request +from config import LOCAL_STORAGE_PATH +from services.authentication import authenticate +from app_utils import queue_task_wrapper, validate_payload + +v1_toolkit_jobs_status_bp = Blueprint('v1_toolkit_jobs_status', __name__) +logger = logging.getLogger(__name__) + +@v1_toolkit_jobs_status_bp.route('/v1/toolkit/jobs/status', methods=['POST']) +@authenticate +@queue_task_wrapper(bypass_queue=True) +def get_all_jobs_status(job_id, data): + """ + Get the status of all jobs within a specified time range + + Args: + job_id (str): Job ID assigned by queue_task_wrapper (unused) + data (dict): Request data containing optional since_seconds parameter + + Returns: + Tuple of (jobs_status_data, endpoint_string, status_code) + """ + logger.info("Retrieving status for all jobs") + endpoint = "/v1/toolkit/jobs/status" + + try: + # Get time range parameter (default to 600 seconds/10 minutes if not provided) + since_seconds = 600 + if data and "since_seconds" in data: + since_seconds = data.get("since_seconds") + + cutoff_time = time.time() - since_seconds + + # Construct the path to the jobs directory + jobs_dir = os.path.join(LOCAL_STORAGE_PATH, 'jobs') + + # Check if the jobs directory exists + if not os.path.exists(jobs_dir): + return {"error": "Jobs directory not found"}, endpoint, 404 + + # Dictionary to store job statuses + jobs_status = {} + + # Iterate through job files in the directory + for filename in os.listdir(jobs_dir): + if filename.endswith('.json'): + job_file_path = os.path.join(jobs_dir, filename) + file_mod_time = os.path.getmtime(job_file_path) + + # Check if the file was modified within the time range + if file_mod_time >= cutoff_time: + job_id = filename.split('.')[0] # Remove .json extension to get job_id + + # Read the job status file + with open(job_file_path, 'r') as file: + job_data = json.load(file) + + # Only include the job_status field, not the response + if "job_status" in job_data: + jobs_status[job_id] = job_data["job_status"] + + # Return the job statuses + return jobs_status, endpoint, 200 + + except Exception as e: + logger.error(f"Error retrieving status for jobs: {str(e)}") + return {"error": f"Failed to retrieve job statuses: {str(e)}"}, endpoint, 500 \ No newline at end of file diff --git a/routes/v1/toolkit/test.py b/routes/v1/toolkit/test.py new file mode 100644 index 0000000000000000000000000000000000000000..1442b676c3a387ee554112897abc716af5ef7285 --- /dev/null +++ b/routes/v1/toolkit/test.py @@ -0,0 +1,52 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import logging +from flask import Blueprint +from services.authentication import authenticate +from services.cloud_storage import upload_file +from app_utils import queue_task_wrapper +from config import LOCAL_STORAGE_PATH + +v1_toolkit_test_bp = Blueprint('v1_toolkit_test', __name__) +logger = logging.getLogger(__name__) + +@v1_toolkit_test_bp.route('/v1/toolkit/test', methods=['GET']) +@authenticate +@queue_task_wrapper(bypass_queue=True) +def test_api(job_id, data): + logger.info(f"Job {job_id}: Testing NCA Toolkit API setup") + + try: + # Create test file + test_filename = os.path.join(LOCAL_STORAGE_PATH, "success.txt") + with open(test_filename, 'w') as f: + f.write("You have successfully installed the NCA Toolkit API, great job!") + + # Upload file to cloud storage + upload_url = upload_file(test_filename) + + # Clean up local file + os.remove(test_filename) + + return upload_url, "/v1/toolkit/test", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error testing API setup - {str(e)}") + return str(e), "/v1/toolkit/test", 500 \ No newline at end of file diff --git a/routes/v1/video/caption_video.py b/routes/v1/video/caption_video.py new file mode 100644 index 0000000000000000000000000000000000000000..599b9c77e907ba2019a171c412c3d8ee93980e92 --- /dev/null +++ b/routes/v1/video/caption_video.py @@ -0,0 +1,187 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint, jsonify +from app_utils import validate_payload, queue_task_wrapper +import logging +from services.ass_toolkit import generate_ass_captions_v1 +from services.authentication import authenticate +from services.cloud_storage import upload_file +import os +import requests # Ensure requests is imported for webhook handling + +v1_video_caption_bp = Blueprint('v1_video/caption', __name__) +logger = logging.getLogger(__name__) + +@v1_video_caption_bp.route('/v1/video/caption', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"}, + "captions": {"type": "string"}, + "settings": { + "type": "object", + "properties": { + "line_color": {"type": "string"}, + "word_color": {"type": "string"}, + "outline_color": {"type": "string"}, + "all_caps": {"type": "boolean"}, + "max_words_per_line": {"type": "integer"}, + "x": {"type": "integer"}, + "y": {"type": "integer"}, + "position": { + "type": "string", + "enum": [ + "bottom_left", "bottom_center", "bottom_right", + "middle_left", "middle_center", "middle_right", + "top_left", "top_center", "top_right" + ] + }, + "alignment": { + "type": "string", + "enum": ["left", "center", "right"] + }, + "font_family": {"type": "string"}, + "font_size": {"type": "integer"}, + "bold": {"type": "boolean"}, + "italic": {"type": "boolean"}, + "underline": {"type": "boolean"}, + "strikeout": {"type": "boolean"}, + "style": { + "type": "string", + "enum": ["classic", "karaoke", "highlight", "underline", "word_by_word"] + }, + "outline_width": {"type": "integer"}, + "spacing": {"type": "integer"}, + "angle": {"type": "integer"}, + "shadow_offset": {"type": "integer"} + }, + "additionalProperties": False + }, + "replace": { + "type": "array", + "items": { + "type": "object", + "properties": { + "find": {"type": "string"}, + "replace": {"type": "string"} + }, + "required": ["find", "replace"] + } + }, + "exclude_time_ranges": { + "type": "array", + "items": { + "type": "object", + "properties": { + "start": { "type": "string" }, + "end": { "type": "string" } + }, + "required": ["start", "end"], + "additionalProperties": False + } + }, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"}, + "language": {"type": "string"} + }, + "required": ["video_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def caption_video_v1(job_id, data): + video_url = data['video_url'] + captions = data.get('captions') + settings = data.get('settings', {}) + replace = data.get('replace', []) + exclude_time_ranges = data.get('exclude_time_ranges', []) + webhook_url = data.get('webhook_url') + id = data.get('id') + language = data.get('language', 'auto') + + logger.info(f"Job {job_id}: Received v1 captioning request for {video_url}") + logger.info(f"Job {job_id}: Settings received: {settings}") + logger.info(f"Job {job_id}: Replace rules received: {replace}") + logger.info(f"Job {job_id}: Exclude time ranges received: {exclude_time_ranges}") + + try: + # Do NOT combine position and alignment. Keep them separate. + # Just pass settings directly to process_captioning_v1. + # This ensures position and alignment remain independent keys. + + # Process video with the enhanced v1 service + output = generate_ass_captions_v1(video_url, captions, settings, replace, exclude_time_ranges, job_id, language) + + if isinstance(output, dict) and 'error' in output: + # Check if this is a font-related error by checking for 'available_fonts' key + if 'available_fonts' in output: + # Font error scenario + return {"error": output['error'], "available_fonts": output['available_fonts']}, "/v1/video/caption", 400 + else: + # Non-font error scenario, do not return available_fonts + return {"error": output['error']}, "/v1/video/caption", 400 + + # If processing was successful, output is the ASS file path + ass_path = output + logger.info(f"Job {job_id}: ASS file generated at {ass_path}") + + # Prepare output filename and path for the rendered video + output_filename = f"{job_id}_captioned.mp4" + output_path = os.path.join(os.path.dirname(ass_path), output_filename) + + # Download the video (if not already local) + video_path = None + try: + from services.file_management import download_file + from config import LOCAL_STORAGE_PATH + video_path = download_file(video_url, LOCAL_STORAGE_PATH) + logger.info(f"Job {job_id}: Video downloaded to {video_path}") + except Exception as e: + logger.error(f"Job {job_id}: Video download error: {str(e)}") + return {"error": str(e)}, "/v1/video/caption", 500 + + # Render the video with subtitles using FFmpeg + try: + import ffmpeg + ffmpeg.input(video_path).output( + output_path, + vf=f"subtitles='{ass_path}'", + acodec='copy' + ).run(overwrite_output=True) + logger.info(f"Job {job_id}: FFmpeg processing completed. Output saved to {output_path}") + except Exception as e: + logger.error(f"Job {job_id}: FFmpeg error: {str(e)}") + return {"error": f"FFmpeg error: {str(e)}"}, "/v1/video/caption", 500 + + # Clean up the ASS file after use + os.remove(ass_path) + + # Upload the captioned video + cloud_url = upload_file(output_path) + logger.info(f"Job {job_id}: Captioned video uploaded to cloud storage: {cloud_url}") + + # Clean up the output file after upload + os.remove(output_path) + logger.info(f"Job {job_id}: Cleaned up local output file") + + return cloud_url, "/v1/video/caption", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during captioning process - {str(e)}", exc_info=True) + return {"error": str(e)}, "/v1/video/caption", 500 diff --git a/routes/v1/video/concatenate.py b/routes/v1/video/concatenate.py new file mode 100644 index 0000000000000000000000000000000000000000..4d542287691277e2311dc3a609e4369e7122bb7b --- /dev/null +++ b/routes/v1/video/concatenate.py @@ -0,0 +1,70 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.v1.video.concatenate import process_video_concatenate +from services.authentication import authenticate +from services.cloud_storage import upload_file + +v1_video_concatenate_bp = Blueprint('v1_video_concatenate', __name__) +logger = logging.getLogger(__name__) + +@v1_video_concatenate_bp.route('/v1/video/concatenate', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_urls": { + "type": "array", + "items": { + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"} + }, + "required": ["video_url"] + }, + "minItems": 1 + }, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_urls"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def combine_videos(job_id, data): + media_urls = data['video_urls'] + webhook_url = data.get('webhook_url') + id = data.get('id') + + logger.info(f"Job {job_id}: Received combine-videos request for {len(media_urls)} videos") + + try: + output_file = process_video_concatenate(media_urls, job_id) + logger.info(f"Job {job_id}: Video combination process completed successfully") + + cloud_url = upload_file(output_file) + logger.info(f"Job {job_id}: Combined video uploaded to cloud storage: {cloud_url}") + + return cloud_url, "/v1/video/concatenate", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during video combination process - {str(e)}") + return str(e), "/v1/video/concatenate", 500 \ No newline at end of file diff --git a/routes/v1/video/cut.py b/routes/v1/video/cut.py new file mode 100644 index 0000000000000000000000000000000000000000..343b4bfe68ba67224476629ad86d4b1d51ef308a --- /dev/null +++ b/routes/v1/video/cut.py @@ -0,0 +1,102 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.v1.video.cut import cut_media +from services.authentication import authenticate + +v1_video_cut_bp = Blueprint('v1_video_cut', __name__) +logger = logging.getLogger(__name__) + +@v1_video_cut_bp.route('/v1/video/cut', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"}, + "cuts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "start": {"type": "string"}, + "end": {"type": "string"} + }, + "required": ["start", "end"], + "additionalProperties": False + }, + "minItems": 1 + }, + "video_codec": {"type": "string"}, + "video_preset": {"type": "string"}, + "video_crf": {"type": "number", "minimum": 0, "maximum": 51}, + "audio_codec": {"type": "string"}, + "audio_bitrate": {"type": "string"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_url", "cuts"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def video_cut(job_id, data): + """Cut specified segments from a video file with optional encoding settings.""" + video_url = data['video_url'] + cuts = data['cuts'] + + # Extract encoding settings with defaults + video_codec = data.get('video_codec', 'libx264') + video_preset = data.get('video_preset', 'medium') + video_crf = data.get('video_crf', 23) + audio_codec = data.get('audio_codec', 'aac') + audio_bitrate = data.get('audio_bitrate', '128k') + + logger.info(f"Job {job_id}: Received video cut request for {video_url}") + + try: + # Process the video file and get local file paths + output_filename, input_filename = cut_media( + video_url=video_url, + cuts=cuts, + job_id=job_id, + video_codec=video_codec, + video_preset=video_preset, + video_crf=video_crf, + audio_codec=audio_codec, + audio_bitrate=audio_bitrate + ) + + # Upload the processed file to cloud storage + from services.cloud_storage import upload_file + cloud_url = upload_file(output_filename) + logger.info(f"Job {job_id}: Uploaded output to cloud: {cloud_url}") + + # Clean up temporary files + import os + os.remove(input_filename) + os.remove(output_filename) + logger.info(f"Job {job_id}: Removed temporary files") + + logger.info(f"Job {job_id}: Video cut operation completed successfully") + return cloud_url, "/v1/video/cut", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during video cut process - {str(e)}") + return str(e), "/v1/video/cut", 500 \ No newline at end of file diff --git a/routes/v1/video/split.py b/routes/v1/video/split.py new file mode 100644 index 0000000000000000000000000000000000000000..7417497ef8b6f6ddc30efb6d9912bc9f06281d3b --- /dev/null +++ b/routes/v1/video/split.py @@ -0,0 +1,115 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.v1.video.split import split_video +from services.authentication import authenticate + +v1_video_split_bp = Blueprint('v1_video_split', __name__) +logger = logging.getLogger(__name__) + +@v1_video_split_bp.route('/v1/video/split', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"}, + "splits": { + "type": "array", + "items": { + "type": "object", + "properties": { + "start": {"type": "string"}, + "end": {"type": "string"} + }, + "required": ["start", "end"], + "additionalProperties": False + }, + "minItems": 1 + }, + "video_codec": {"type": "string"}, + "video_preset": {"type": "string"}, + "video_crf": {"type": "number", "minimum": 0, "maximum": 51}, + "audio_codec": {"type": "string"}, + "audio_bitrate": {"type": "string"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_url", "splits"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def video_split(job_id, data): + """Split a video file into multiple segments with optional encoding settings.""" + video_url = data['video_url'] + splits = data['splits'] + + # Extract encoding settings with defaults + video_codec = data.get('video_codec', 'libx264') + video_preset = data.get('video_preset', 'medium') + video_crf = data.get('video_crf', 23) + audio_codec = data.get('audio_codec', 'aac') + audio_bitrate = data.get('audio_bitrate', '128k') + + logger.info(f"Job {job_id}: Received video split request for {video_url}") + + try: + # Process the video file and get list of output files + output_files, input_filename = split_video( + video_url=video_url, + splits=splits, + job_id=job_id, + video_codec=video_codec, + video_preset=video_preset, + video_crf=video_crf, + audio_codec=audio_codec, + audio_bitrate=audio_bitrate + ) + + # Upload all output files to cloud storage + from services.cloud_storage import upload_file + result_files = [] + + for i, output_file in enumerate(output_files): + cloud_url = upload_file(output_file) + result_files.append({ + "file_url": cloud_url, + "start": splits[i]["start"], + "end": splits[i]["end"] + }) + # Remove the local file after upload + import os + os.remove(output_file) + logger.info(f"Job {job_id}: Uploaded and removed split file {i+1}") + + # Clean up input file + import os + os.remove(input_filename) + logger.info(f"Job {job_id}: Removed input file") + + # Prepare the response with only file URLs + response = [{"file_url": item["file_url"]} for item in result_files] + + logger.info(f"Job {job_id}: Video split operation completed successfully") + return response, "/v1/video/split", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during video split process - {str(e)}") + return str(e), "/v1/video/split", 500 \ No newline at end of file diff --git a/routes/v1/video/thumbnail.py b/routes/v1/video/thumbnail.py new file mode 100644 index 0000000000000000000000000000000000000000..08fe587d53b64553b0843e4eea880b9476de22c5 --- /dev/null +++ b/routes/v1/video/thumbnail.py @@ -0,0 +1,64 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint, jsonify +from app_utils import * +import logging +from services.v1.video.thumbnail import extract_thumbnail +from services.authentication import authenticate +from services.cloud_storage import upload_file + +v1_video_thumbnail_bp = Blueprint('v1_video_thumbnail', __name__) +logger = logging.getLogger(__name__) + +@v1_video_thumbnail_bp.route('/v1/video/thumbnail', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"}, + "second": {"type": "number", "minimum": 0}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def generate_thumbnail(job_id, data): + video_url = data.get('video_url') + second = data.get('second', 0) # Default to 0 if not provided + webhook_url = data.get('webhook_url') + + logger.info(f"Job {job_id}: Received thumbnail extraction request for {video_url} at {second} seconds") + + try: + # Process thumbnail extraction + thumbnail_path = extract_thumbnail(video_url, job_id, second) + + # Upload the thumbnail to cloud storage + file_url = upload_file(thumbnail_path) + + logger.info(f"Job {job_id}: Thumbnail uploaded to cloud storage at {file_url}") + + # Return the URL of the uploaded thumbnail + return file_url, "/v1/video/thumbnail", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during thumbnail extraction - {str(e)}") + return str(e), "/v1/video/thumbnail", 500 diff --git a/routes/v1/video/trim.py b/routes/v1/video/trim.py new file mode 100644 index 0000000000000000000000000000000000000000..10f039456547952b29a8bcad4e7e574d3a8ab38f --- /dev/null +++ b/routes/v1/video/trim.py @@ -0,0 +1,93 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from flask import Blueprint +from app_utils import * +import logging +from services.v1.video.trim import trim_video +from services.authentication import authenticate + +v1_video_trim_bp = Blueprint('v1_video_trim', __name__) +logger = logging.getLogger(__name__) + +@v1_video_trim_bp.route('/v1/video/trim', methods=['POST']) +@authenticate +@validate_payload({ + "type": "object", + "properties": { + "video_url": {"type": "string", "format": "uri"}, + "start": {"type": "string"}, + "end": {"type": "string"}, + "video_codec": {"type": "string"}, + "video_preset": {"type": "string"}, + "video_crf": {"type": "number", "minimum": 0, "maximum": 51}, + "audio_codec": {"type": "string"}, + "audio_bitrate": {"type": "string"}, + "webhook_url": {"type": "string", "format": "uri"}, + "id": {"type": "string"} + }, + "required": ["video_url"], + "additionalProperties": False +}) +@queue_task_wrapper(bypass_queue=False) +def video_trim(job_id, data): + """Trim a video by removing specified portions from the beginning and/or end with optional encoding settings.""" + video_url = data['video_url'] + start = data.get('start') + end = data.get('end') + + # Extract encoding settings with defaults + video_codec = data.get('video_codec', 'libx264') + video_preset = data.get('video_preset', 'medium') + video_crf = data.get('video_crf', 23) + audio_codec = data.get('audio_codec', 'aac') + audio_bitrate = data.get('audio_bitrate', '128k') + + logger.info(f"Job {job_id}: Received video trim request for {video_url}") + + try: + # Process the video file and get local file paths + output_filename, input_filename = trim_video( + video_url=video_url, + start=start, + end=end, + job_id=job_id, + video_codec=video_codec, + video_preset=video_preset, + video_crf=video_crf, + audio_codec=audio_codec, + audio_bitrate=audio_bitrate + ) + + # Upload the processed file to cloud storage + from services.cloud_storage import upload_file + cloud_url = upload_file(output_filename) + logger.info(f"Job {job_id}: Uploaded output to cloud: {cloud_url}") + + # Clean up temporary files + import os + os.remove(input_filename) + os.remove(output_filename) + logger.info(f"Job {job_id}: Removed temporary files") + + logger.info(f"Job {job_id}: Video trim operation completed successfully") + return cloud_url, "/v1/video/trim", 200 + + except Exception as e: + logger.error(f"Job {job_id}: Error during video trim process - {str(e)}") + return str(e), "/v1/video/trim", 500 \ No newline at end of file diff --git a/services/ass_toolkit.py b/services/ass_toolkit.py new file mode 100644 index 0000000000000000000000000000000000000000..9b88376df74c2bb19e38b46bf0220a556cac9e19 --- /dev/null +++ b/services/ass_toolkit.py @@ -0,0 +1,879 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import ffmpeg +import logging +import subprocess +import whisper +from datetime import timedelta +import srt +import re +from services.file_management import download_file +from services.cloud_storage import upload_file # Ensure this import is present +import requests # Ensure requests is imported for webhook handling +from urllib.parse import urlparse +from config import LOCAL_STORAGE_PATH + +# Initialize logger +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +if not logger.hasHandlers(): + handler = logging.StreamHandler() + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + handler.setFormatter(formatter) + logger.addHandler(handler) + +POSITION_ALIGNMENT_MAP = { + "bottom_left": 1, + "bottom_center": 2, + "bottom_right": 3, + "middle_left": 4, + "middle_center": 5, + "middle_right": 6, + "top_left": 7, + "top_center": 8, + "top_right": 9 +} + +def rgb_to_ass_color(rgb_color): + """Convert RGB hex to ASS (&HAABBGGRR).""" + if isinstance(rgb_color, str): + rgb_color = rgb_color.lstrip('#') + if len(rgb_color) == 6: + r = int(rgb_color[0:2], 16) + g = int(rgb_color[2:4], 16) + b = int(rgb_color[4:6], 16) + return f"&H00{b:02X}{g:02X}{r:02X}" + return "&H00FFFFFF" + +def generate_transcription(video_path, language='auto'): + try: + model = whisper.load_model("base") + transcription_options = { + 'word_timestamps': True, + 'verbose': True, + } + if language != 'auto': + transcription_options['language'] = language + result = model.transcribe(video_path, **transcription_options) + logger.info(f"Transcription generated successfully for video: {video_path}") + return result + except Exception as e: + logger.error(f"Error in transcription: {str(e)}") + raise + +def get_video_resolution(video_path): + try: + probe = ffmpeg.probe(video_path) + video_streams = [s for s in probe['streams'] if s['codec_type'] == 'video'] + if video_streams: + width = int(video_streams[0]['width']) + height = int(video_streams[0]['height']) + logger.info(f"Video resolution determined: {width}x{height}") + return width, height + else: + logger.warning(f"No video streams found for {video_path}. Using default resolution 384x288.") + return 384, 288 + except Exception as e: + logger.error(f"Error getting video resolution: {str(e)}. Using default resolution 384x288.") + return 384, 288 + +def get_available_fonts(): + """Get the list of available fonts on the system.""" + try: + import matplotlib.font_manager as fm + except ImportError: + logger.error("matplotlib not installed. Install via 'pip install matplotlib'.") + return [] + font_list = fm.findSystemFonts(fontpaths=None, fontext='ttf') + font_names = set() + for font in font_list: + try: + font_prop = fm.FontProperties(fname=font) + font_name = font_prop.get_name() + font_names.add(font_name) + except Exception: + continue + logger.info(f"Available fonts retrieved: {font_names}") + return list(font_names) + +def format_ass_time(seconds): + """Convert float seconds to ASS time format H:MM:SS.cc""" + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + secs = int(seconds % 60) + centiseconds = int(round((seconds - int(seconds)) * 100)) + return f"{hours}:{minutes:02}:{secs:02}.{centiseconds:02}" + +def process_subtitle_text(text, replace_dict, all_caps, max_words_per_line): + """Apply text transformations: replacements, all caps, and optional line splitting.""" + for old_word, new_word in replace_dict.items(): + text = re.sub(re.escape(old_word), new_word, text, flags=re.IGNORECASE) + if all_caps: + text = text.upper() + if max_words_per_line > 0: + words = text.split() + lines = [' '.join(words[i:i+max_words_per_line]) for i in range(0, len(words), max_words_per_line)] + text = '\\N'.join(lines) + return text + +def srt_to_transcription_result(srt_content): + """Convert SRT content into a transcription-like structure for uniform processing.""" + subtitles = list(srt.parse(srt_content)) + segments = [] + for sub in subtitles: + segments.append({ + 'start': sub.start.total_seconds(), + 'end': sub.end.total_seconds(), + 'text': sub.content.strip(), + 'words': [] # SRT does not provide word-level timestamps + }) + logger.info("Converted SRT content to transcription result.") + return {'segments': segments} + +def split_lines(text, max_words_per_line): + """Split text into multiple lines if max_words_per_line > 0.""" + if max_words_per_line <= 0: + return [text] + words = text.split() + lines = [' '.join(words[i:i+max_words_per_line]) for i in range(0, len(words), max_words_per_line)] + return lines + +def is_url(string): + """Check if the given string is a valid HTTP/HTTPS URL.""" + try: + result = urlparse(string) + return result.scheme in ('http', 'https') + except: + return False + +def download_captions(captions_url): + """Download captions from the given URL.""" + try: + logger.info(f"Downloading captions from URL: {captions_url}") + response = requests.get(captions_url) + response.raise_for_status() + logger.info("Captions downloaded successfully.") + return response.text + except Exception as e: + logger.error(f"Error downloading captions: {str(e)}") + raise + +def determine_alignment_code(position_str, alignment_str, x, y, video_width, video_height): + """ + Determine the final \an alignment code and (x,y) position based on: + - x,y (if provided) + - position_str (one of top_left, top_center, ...) + - alignment_str (left, center, right) + - If x,y not provided, divide the video into a 3x3 grid and position accordingly. + """ + logger.info(f"[determine_alignment_code] Inputs: position_str={position_str}, alignment_str={alignment_str}, x={x}, y={y}, video_width={video_width}, video_height={video_height}") + + horizontal_map = { + 'left': 1, + 'center': 2, + 'right': 3 + } + + # If x and y are provided, use them directly and set \an based on alignment_str + if x is not None and y is not None: + logger.info("[determine_alignment_code] x and y provided, ignoring position and alignment for grid.") + vertical_code = 4 # Middle row + horiz_code = horizontal_map.get(alignment_str, 2) # Default to center + an_code = vertical_code + (horiz_code - 1) + logger.info(f"[determine_alignment_code] Using provided x,y. an_code={an_code}") + return an_code, True, x, y + + # No x,y provided: determine position and alignment based on grid + pos_lower = position_str.lower() + if 'top' in pos_lower: + vertical_base = 7 # Top row an codes start at 7 + vertical_center = video_height / 6 + elif 'middle' in pos_lower: + vertical_base = 4 # Middle row an codes start at 4 + vertical_center = video_height / 2 + else: + vertical_base = 1 # Bottom row an codes start at 1 + vertical_center = (5 * video_height) / 6 + + if 'left' in pos_lower: + left_boundary = 0 + right_boundary = video_width / 3 + center_line = video_width / 6 + elif 'right' in pos_lower: + left_boundary = (2 * video_width) / 3 + right_boundary = video_width + center_line = (5 * video_width) / 6 + else: + # Center column + left_boundary = video_width / 3 + right_boundary = (2 * video_width) / 3 + center_line = video_width / 2 + + # Alignment affects horizontal position within the cell + if alignment_str == 'left': + final_x = left_boundary + horiz_code = 1 + elif alignment_str == 'right': + final_x = right_boundary + horiz_code = 3 + else: + final_x = center_line + horiz_code = 2 + + final_y = vertical_center + an_code = vertical_base + (horiz_code - 1) + + logger.info(f"[determine_alignment_code] Computed final_x={final_x}, final_y={final_y}, an_code={an_code}") + return an_code, True, int(final_x), int(final_y) + +def create_style_line(style_options, video_resolution): + """ + Create the style line for ASS subtitles. + """ + font_family = style_options.get('font_family', 'Arial') + available_fonts = get_available_fonts() + if font_family not in available_fonts: + logger.warning(f"Font '{font_family}' not found.") + return {'error': f"Font '{font_family}' not available.", 'available_fonts': available_fonts} + + line_color = rgb_to_ass_color(style_options.get('line_color', '#FFFFFF')) + secondary_color = line_color + outline_color = rgb_to_ass_color(style_options.get('outline_color', '#000000')) + box_color = rgb_to_ass_color(style_options.get('box_color', '#000000')) + + font_size = style_options.get('font_size', int(video_resolution[1] * 0.05)) + bold = '1' if style_options.get('bold', False) else '0' + italic = '1' if style_options.get('italic', False) else '0' + underline = '1' if style_options.get('underline', False) else '0' + strikeout = '1' if style_options.get('strikeout', False) else '0' + scale_x = style_options.get('scale_x', '100') + scale_y = style_options.get('scale_y', '100') + spacing = style_options.get('spacing', '0') + angle = style_options.get('angle', '0') + border_style = style_options.get('border_style', '1') + outline_width = style_options.get('outline_width', '2') + shadow_offset = style_options.get('shadow_offset', '0') + + margin_l = style_options.get('margin_l', '20') + margin_r = style_options.get('margin_r', '20') + margin_v = style_options.get('margin_v', '20') + + # Default alignment in style (we override per event) + alignment = 5 + + style_line = ( + f"Style: Default,{font_family},{font_size},{line_color},{secondary_color}," + f"{outline_color},{box_color},{bold},{italic},{underline},{strikeout}," + f"{scale_x},{scale_y},{spacing},{angle},{border_style},{outline_width}," + f"{shadow_offset},{alignment},{margin_l},{margin_r},{margin_v},0" + ) + logger.info(f"Created ASS style line: {style_line}") + return style_line + +def generate_ass_header(style_options, video_resolution): + """ + Generate the ASS file header with the Default style. + """ + ass_header = f"""[Script Info] +ScriptType: v4.00+ +PlayResX: {video_resolution[0]} +PlayResY: {video_resolution[1]} +ScaledBorderAndShadow: yes + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +""" + style_line = create_style_line(style_options, video_resolution) + if isinstance(style_line, dict) and 'error' in style_line: + # Font-related error + return style_line + + ass_header += style_line + "\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n" + logger.info("Generated ASS header.") + return ass_header + +### STYLE HANDLERS ### + +def handle_classic(transcription_result, style_options, replace_dict, video_resolution): + """ + Classic style handler: Centers the text based on position and alignment. + """ + max_words_per_line = int(style_options.get('max_words_per_line', 0)) + all_caps = style_options.get('all_caps', False) + if style_options['font_size'] is None: + style_options['font_size'] = int(video_resolution[1] * 0.05) + + position_str = style_options.get('position', 'middle_center') + alignment_str = style_options.get('alignment', 'center') + x = style_options.get('x') + y = style_options.get('y') + + an_code, use_pos, final_x, final_y = determine_alignment_code( + position_str, alignment_str, x, y, + video_width=video_resolution[0], + video_height=video_resolution[1] + ) + + logger.info(f"[Classic] position={position_str}, alignment={alignment_str}, x={final_x}, y={final_y}, an_code={an_code}") + + events = [] + for segment in transcription_result['segments']: + text = segment['text'].strip().replace('\n', ' ') + lines = split_lines(text, max_words_per_line) + processed_text = '\\N'.join(process_subtitle_text(line, replace_dict, all_caps, 0) for line in lines) + start_time = format_ass_time(segment['start']) + end_time = format_ass_time(segment['end']) + position_tag = f"{{\\an{an_code}\\pos({final_x},{final_y})}}" + events.append(f"Dialogue: 0,{start_time},{end_time},Default,,0,0,0,,{position_tag}{processed_text}") + logger.info(f"Handled {len(events)} dialogues in classic style.") + return "\n".join(events) + +def handle_karaoke(transcription_result, style_options, replace_dict, video_resolution): + """ + Karaoke style handler: Highlights words as they are spoken. + """ + max_words_per_line = int(style_options.get('max_words_per_line', 0)) + all_caps = style_options.get('all_caps', False) + if style_options['font_size'] is None: + style_options['font_size'] = int(video_resolution[1] * 0.05) + + position_str = style_options.get('position', 'middle_center') + alignment_str = style_options.get('alignment', 'center') + x = style_options.get('x') + y = style_options.get('y') + + an_code, use_pos, final_x, final_y = determine_alignment_code( + position_str, alignment_str, x, y, + video_width=video_resolution[0], + video_height=video_resolution[1] + ) + word_color = rgb_to_ass_color(style_options.get('word_color', '#FFFF00')) + + logger.info(f"[Karaoke] position={position_str}, alignment={alignment_str}, x={final_x}, y={final_y}, an_code={an_code}") + + events = [] + for segment in transcription_result['segments']: + words = segment.get('words', []) + if not words: + continue + + if max_words_per_line > 0: + lines_content = [] + current_line = [] + current_line_words = 0 + for w_info in words: + w = process_subtitle_text(w_info.get('word', ''), replace_dict, all_caps, 0) + duration_cs = int(round((w_info['end'] - w_info['start']) * 100)) + highlighted_word = f"{{\\k{duration_cs}}}{w} " + current_line.append(highlighted_word) + current_line_words += 1 + if current_line_words >= max_words_per_line: + lines_content.append(''.join(current_line).strip()) + current_line = [] + current_line_words = 0 + if current_line: + lines_content.append(''.join(current_line).strip()) + else: + line_content = [] + for w_info in words: + w = process_subtitle_text(w_info.get('word', ''), replace_dict, all_caps, 0) + duration_cs = int(round((w_info['end'] - w_info['start']) * 100)) + highlighted_word = f"{{\\k{duration_cs}}}{w} " + line_content.append(highlighted_word) + lines_content = [''.join(line_content).strip()] + + dialogue_text = '\\N'.join(lines_content) + start_time = format_ass_time(words[0]['start']) + end_time = format_ass_time(words[-1]['end']) + position_tag = f"{{\\an{an_code}\\pos({final_x},{final_y})}}" + events.append(f"Dialogue: 0,{start_time},{end_time},Default,,0,0,0,,{position_tag}{{\\c{word_color}}}{dialogue_text}") + logger.info(f"Handled {len(events)} dialogues in karaoke style.") + return "\n".join(events) + +def handle_highlight(transcription_result, style_options, replace_dict, video_resolution): + """ + Highlight style handler: Highlights words sequentially. + """ + max_words_per_line = int(style_options.get('max_words_per_line', 0)) + all_caps = style_options.get('all_caps', False) + if style_options['font_size'] is None: + style_options['font_size'] = int(video_resolution[1] * 0.05) + + position_str = style_options.get('position', 'middle_center') + alignment_str = style_options.get('alignment', 'center') + x = style_options.get('x') + y = style_options.get('y') + + an_code, use_pos, final_x, final_y = determine_alignment_code( + position_str, alignment_str, x, y, + video_width=video_resolution[0], + video_height=video_resolution[1] + ) + + word_color = rgb_to_ass_color(style_options.get('word_color', '#FFFF00')) + line_color = rgb_to_ass_color(style_options.get('line_color', '#FFFFFF')) + events = [] + + logger.info(f"[Highlight] position={position_str}, alignment={alignment_str}, x={final_x}, y={final_y}, an_code={an_code}") + + for segment in transcription_result['segments']: + words = segment.get('words', []) + if not words: + continue + + # Process all words in the segment + processed_words = [] + for w_info in words: + w = process_subtitle_text(w_info.get('word', ''), replace_dict, all_caps, 0) + if w: + processed_words.append((w, w_info['start'], w_info['end'])) + + if not processed_words: + continue + + # Split into lines if max_words_per_line is specified + if max_words_per_line > 0: + line_sets = [processed_words[i:i+max_words_per_line] for i in range(0, len(processed_words), max_words_per_line)] + else: + line_sets = [processed_words] + + for line_set in line_sets: + # Get the start time of the first word and end time of the last word + line_start = line_set[0][1] + line_end = line_set[-1][2] + + # Create a persistent line that stays visible during the entire segment + base_text = ' '.join(word for word, _, _ in line_set) + start_time = format_ass_time(line_start) + end_time = format_ass_time(line_end) + position_tag = f"{{\\an{an_code}\\pos({final_x},{final_y})}}" + events.append(f"Dialogue: 0,{start_time},{end_time},Default,,0,0,0,,{position_tag}{{\\c{line_color}}}{base_text}") + + # Add individual highlighting for each word + for idx, (word, w_start, w_end) in enumerate(line_set): + # Create the highlighted version of this word within the line + highlighted_words = [] + + for i, (w, _, _) in enumerate(line_set): + if i == idx: + # This is the current word - highlight it + highlighted_words.append(f"{{\\c{word_color}}}{w}{{\\c{line_color}}}") + else: + # Add the word without highlighting + highlighted_words.append(w) + + highlighted_text = ' '.join(highlighted_words) + word_start_time = format_ass_time(w_start) + word_end_time = format_ass_time(w_end) + events.append(f"Dialogue: 1,{word_start_time},{word_end_time},Default,,0,0,0,,{position_tag}{{\\c{line_color}}}{highlighted_text}") + + logger.info(f"Handled {len(events)} dialogues in highlight style.") + return "\n".join(events) + +def handle_underline(transcription_result, style_options, replace_dict, video_resolution): + """ + Underline style handler: Underlines the current word. + """ + max_words_per_line = int(style_options.get('max_words_per_line', 0)) + all_caps = style_options.get('all_caps', False) + if style_options['font_size'] is None: + style_options['font_size'] = int(video_resolution[1] * 0.05) + + position_str = style_options.get('position', 'middle_center') + alignment_str = style_options.get('alignment', 'center') + x = style_options.get('x') + y = style_options.get('y') + + an_code, use_pos, final_x, final_y = determine_alignment_code( + position_str, alignment_str, x, y, + video_width=video_resolution[0], + video_height=video_resolution[1] + ) + line_color = rgb_to_ass_color(style_options.get('line_color', '#FFFFFF')) + events = [] + + logger.info(f"[Underline] position={position_str}, alignment={alignment_str}, x={final_x}, y={final_y}, an_code={an_code}") + + for segment in transcription_result['segments']: + words = segment.get('words', []) + if not words: + continue + processed_words = [] + for w_info in words: + w = process_subtitle_text(w_info.get('word', ''), replace_dict, all_caps, 0) + if w: + processed_words.append((w, w_info['start'], w_info['end'])) + + if not processed_words: + continue + + if max_words_per_line > 0: + line_sets = [processed_words[i:i+max_words_per_line] for i in range(0, len(processed_words), max_words_per_line)] + else: + line_sets = [processed_words] + + for line_set in line_sets: + for idx, (word, w_start, w_end) in enumerate(line_set): + line_words = [] + for w_idx, (w_text, _, _) in enumerate(line_set): + if w_idx == idx: + line_words.append(f"{{\\u1}}{w_text}{{\\u0}}") + else: + line_words.append(w_text) + full_text = ' '.join(line_words) + start_time = format_ass_time(w_start) + end_time = format_ass_time(w_end) + position_tag = f"{{\\an{an_code}\\pos({final_x},{final_y})}}" + events.append(f"Dialogue: 0,{start_time},{end_time},Default,,0,0,0,,{position_tag}{{\\c{line_color}}}{full_text}") + logger.info(f"Handled {len(events)} dialogues in underline style.") + return "\n".join(events) + +def handle_word_by_word(transcription_result, style_options, replace_dict, video_resolution): + """ + Word-by-Word style handler: Displays each word individually. + """ + max_words_per_line = int(style_options.get('max_words_per_line', 0)) + all_caps = style_options.get('all_caps', False) + if style_options['font_size'] is None: + style_options['font_size'] = int(video_resolution[1] * 0.05) + + position_str = style_options.get('position', 'middle_center') + alignment_str = style_options.get('alignment', 'center') + x = style_options.get('x') + y = style_options.get('y') + + an_code, use_pos, final_x, final_y = determine_alignment_code( + position_str, alignment_str, x, y, + video_width=video_resolution[0], + video_height=video_resolution[1] + ) + word_color = rgb_to_ass_color(style_options.get('word_color', '#FFFF00')) + events = [] + + logger.info(f"[Word-by-Word] position={position_str}, alignment={alignment_str}, x={final_x}, y={final_y}, an_code={an_code}") + + for segment in transcription_result['segments']: + words = segment.get('words', []) + if not words: + continue + + if max_words_per_line > 0: + grouped_words = [words[i:i+max_words_per_line] for i in range(0, len(words), max_words_per_line)] + else: + grouped_words = [words] + + for word_group in grouped_words: + for w_info in word_group: + w = process_subtitle_text(w_info.get('word', ''), replace_dict, all_caps, 0) + if not w: + continue + start_time = format_ass_time(w_info['start']) + end_time = format_ass_time(w_info['end']) + position_tag = f"{{\\an{an_code}\\pos({final_x},{final_y})}}" + events.append(f"Dialogue: 0,{start_time},{end_time},Default,,0,0,0,,{position_tag}{{\\c{word_color}}}{w}") + logger.info(f"Handled {len(events)} dialogues in word-by-word style.") + return "\n".join(events) + +STYLE_HANDLERS = { + 'classic': handle_classic, + 'karaoke': handle_karaoke, + 'highlight': handle_highlight, + 'underline': handle_underline, + 'word_by_word': handle_word_by_word +} + +def srt_to_ass(transcription_result, style_type, settings, replace_dict, video_resolution): + """ + Convert transcription result to ASS based on the specified style. + """ + default_style_settings = { + 'line_color': '#FFFFFF', + 'word_color': '#FFFF00', + 'box_color': '#000000', + 'outline_color': '#000000', + 'all_caps': False, + 'max_words_per_line': 0, + 'font_size': None, + 'font_family': 'Arial', + 'bold': False, + 'italic': False, + 'underline': False, + 'strikeout': False, + 'outline_width': 2, + 'shadow_offset': 0, + 'border_style': 1, + 'x': None, + 'y': None, + 'position': 'middle_center', + 'alignment': 'center' # default alignment + } + style_options = {**default_style_settings, **settings} + + if style_options['font_size'] is None: + style_options['font_size'] = int(video_resolution[1] * 0.05) + + ass_header = generate_ass_header(style_options, video_resolution) + if isinstance(ass_header, dict) and 'error' in ass_header: + # Font-related error + return ass_header + + handler = STYLE_HANDLERS.get(style_type.lower()) + if not handler: + logger.warning(f"Unknown style '{style_type}', defaulting to 'classic'.") + handler = handle_classic + + dialogue_lines = handler(transcription_result, style_options, replace_dict, video_resolution) + logger.info("Converted transcription result to ASS format.") + return ass_header + dialogue_lines + "\n" + +def process_subtitle_events(transcription_result, style_type, settings, replace_dict, video_resolution): + """ + Process transcription results into ASS subtitle format. + """ + return srt_to_ass(transcription_result, style_type, settings, replace_dict, video_resolution) + +def parse_time_string(time_str): + """Parse a time string in hh:mm:ss.ms or mm:ss.ms or ss.ms format to seconds (float).""" + import re + if not isinstance(time_str, str): + raise ValueError("Time value must be a string in hh:mm:ss.ms format.") + pattern = r"^(?:(\d+):)?(\d{1,2}):(\d{2}(?:\.\d{1,3})?)$" + match = re.match(pattern, time_str) + if not match: + # Try ss.ms only + try: + return float(time_str) + except Exception: + raise ValueError(f"Invalid time string: {time_str}") + h, m, s = match.groups(default="0") + total_seconds = int(h) * 3600 + int(m) * 60 + float(s) + return total_seconds + +def filter_subtitle_lines(sub_content, exclude_time_ranges, subtitle_type): + """ + Remove subtitle lines/blocks that overlap with exclude_time_ranges. + Supports 'ass' and 'srt' subtitle_type. + """ + + def parse_ass_time(ass_time): + try: + h, m, rest = ass_time.split(":") + s, cs = rest.split(".") + return int(h) * 3600 + int(m) * 60 + int(s) + int(cs) / 100 + except Exception: + return 0 + def parse_time_range(rng): + start = parse_time_string(rng['start']) + end = parse_time_string(rng['end']) + return {'start': start, 'end': end} + parsed_ranges = [parse_time_range(rng) for rng in exclude_time_ranges] + if not exclude_time_ranges: + return sub_content + if subtitle_type == 'ass': + lines = sub_content.splitlines() + filtered_lines = [] + for line in lines: + if line.startswith("Dialogue:"): + parts = line.split(",", 10) + if len(parts) > 3: + start = parse_ass_time(parts[1]) + end = parse_ass_time(parts[2]) + overlap = False + for rng in parsed_ranges: + if start < rng['end'] and end > rng['start']: + overlap = True + break + if overlap: + continue + filtered_lines.append(line) + return "\n".join(filtered_lines) + elif subtitle_type == 'srt': + subtitles = list(srt.parse(sub_content)) + filtered = [] + for sub in subtitles: + start = sub.start.total_seconds() + end = sub.end.total_seconds() + overlap = False + for rng in parsed_ranges: + if start < rng['end'] and end > rng['start']: + overlap = True + break + if not overlap: + filtered.append(sub) + return srt.compose(filtered) + else: + return sub_content + +def normalize_exclude_time_ranges(exclude_time_ranges): + norm = [] + for rng in exclude_time_ranges: + start = rng.get("start") + end = rng.get("end") + if not isinstance(start, str) or not isinstance(end, str): + raise ValueError("exclude_time_ranges start/end must be strings in hh:mm:ss.ms format.") + start_sec = parse_time_string(start) + end_sec = parse_time_string(end) + if start_sec < 0 or end_sec < 0: + raise ValueError("exclude_time_ranges start/end must be non-negative.") + if end_sec <= start_sec: + raise ValueError("exclude_time_ranges end must be strictly greater than start.") + norm.append({"start": start, "end": end}) + return norm + +def generate_ass_captions_v1(video_url, captions, settings, replace, exclude_time_ranges, job_id, language='auto', PlayResX=None, PlayResY=None): + """ + Captioning process with transcription fallback and multiple styles. + Integrates with the updated logic for positioning and alignment. + If PlayResX and PlayResY are provided, use them for ASS generation; otherwise, get from video. + """ + try: + # Normalize exclude_time_ranges to ensure start/end are floats + if exclude_time_ranges: + exclude_time_ranges = normalize_exclude_time_ranges(exclude_time_ranges) + + if not isinstance(settings, dict): + logger.error(f"Job {job_id}: 'settings' should be a dictionary.") + return {"error": "'settings' should be a dictionary."} + + # Normalize keys by replacing hyphens with underscores + style_options = {k.replace('-', '_'): v for k, v in settings.items()} + + if not isinstance(replace, list): + logger.error(f"Job {job_id}: 'replace' should be a list of objects with 'find' and 'replace' keys.") + return {"error": "'replace' should be a list of objects with 'find' and 'replace' keys."} + + # Convert 'replace' list to dictionary + replace_dict = {} + for item in replace: + if 'find' in item and 'replace' in item: + replace_dict[item['find']] = item['replace'] + else: + logger.warning(f"Job {job_id}: Invalid replace item {item}. Skipping.") + + # Handle deprecated 'highlight_color' by merging it into 'word_color' + if 'highlight_color' in style_options: + logger.warning(f"Job {job_id}: 'highlight_color' is deprecated; merging into 'word_color'.") + style_options['word_color'] = style_options.pop('highlight_color') + + # Check font availability + font_family = style_options.get('font_family', 'Arial') + available_fonts = get_available_fonts() + if font_family not in available_fonts: + logger.warning(f"Job {job_id}: Font '{font_family}' not found.") + # Return font error with available_fonts + return {"error": f"Font '{font_family}' not available.", "available_fonts": available_fonts} + + logger.info(f"Job {job_id}: Font '{font_family}' is available.") + + # Determine if captions is a URL or raw content + if captions and is_url(captions): + logger.info(f"Job {job_id}: Captions provided as URL. Downloading captions.") + try: + captions_content = download_captions(captions) + except Exception as e: + logger.error(f"Job {job_id}: Failed to download captions: {str(e)}") + return {"error": f"Failed to download captions: {str(e)}"} + elif captions: + logger.info(f"Job {job_id}: Captions provided as raw content.") + captions_content = captions + else: + captions_content = None + + # Download the video + try: + video_path = download_file(video_url, LOCAL_STORAGE_PATH) + logger.info(f"Job {job_id}: Video downloaded to {video_path}") + except Exception as e: + logger.error(f"Job {job_id}: Video download error: {str(e)}") + # For non-font errors, do NOT include available_fonts + return {"error": str(e)} + + # Get video resolution, unless provided + if PlayResX is not None and PlayResY is not None: + video_resolution = (PlayResX, PlayResY) + logger.info(f"Job {job_id}: Using provided PlayResX/PlayResY = {PlayResX}x{PlayResY}") + else: + video_resolution = get_video_resolution(video_path) + logger.info(f"Job {job_id}: Video resolution detected = {video_resolution[0]}x{video_resolution[1]}") + + # Determine style type + style_type = style_options.get('style', 'classic').lower() + logger.info(f"Job {job_id}: Using style '{style_type}' for captioning.") + + # Determine subtitle content + if captions_content: + # Check if it's ASS by looking for '[Script Info]' + if '[Script Info]' in captions_content: + # It's ASS directly + subtitle_content = captions_content + subtitle_type = 'ass' + logger.info(f"Job {job_id}: Detected ASS formatted captions.") + else: + # Treat as SRT + logger.info(f"Job {job_id}: Detected SRT formatted captions.") + # Validate style for SRT + if style_type != 'classic': + error_message = "Only 'classic' style is supported for SRT captions." + logger.error(f"Job {job_id}: {error_message}") + return {"error": error_message} + transcription_result = srt_to_transcription_result(captions_content) + # Generate ASS based on chosen style + subtitle_content = process_subtitle_events(transcription_result, style_type, style_options, replace_dict, video_resolution) + subtitle_type = 'ass' + else: + # No captions provided, generate transcription + logger.info(f"Job {job_id}: No captions provided, generating transcription.") + transcription_result = generate_transcription(video_path, language=language) + # Generate ASS based on chosen style + subtitle_content = process_subtitle_events(transcription_result, style_type, style_options, replace_dict, video_resolution) + subtitle_type = 'ass' + + # Check for subtitle processing errors + if isinstance(subtitle_content, dict) and 'error' in subtitle_content: + logger.error(f"Job {job_id}: {subtitle_content['error']}") + # Only include 'available_fonts' if it's a font-related error + if 'available_fonts' in subtitle_content: + return {"error": subtitle_content['error'], "available_fonts": subtitle_content.get('available_fonts', [])} + else: + return {"error": subtitle_content['error']} + + # After subtitle_content is generated and before saving to file: + if exclude_time_ranges: + subtitle_content = filter_subtitle_lines(subtitle_content, exclude_time_ranges, subtitle_type) + if subtitle_type == 'ass': + logger.info(f"Job {job_id}: Filtered ASS Dialogue lines due to exclude_time_ranges.") + elif subtitle_type == 'srt': + logger.info(f"Job {job_id}: Filtered SRT subtitle blocks due to exclude_time_ranges.") + + # Save the subtitle content + subtitle_filename = f"{job_id}.{subtitle_type}" + subtitle_path = os.path.join(LOCAL_STORAGE_PATH, subtitle_filename) + try: + with open(subtitle_path, 'w', encoding='utf-8') as f: + f.write(subtitle_content) + logger.info(f"Job {job_id}: Subtitle file saved to {subtitle_path}") + except Exception as e: + logger.error(f"Job {job_id}: Failed to save subtitle file: {str(e)}") + return {"error": f"Failed to save subtitle file: {str(e)}"} + + return subtitle_path + except Exception as e: + logger.error(f"Job {job_id}: Error in generate_ass_captions_v1: {str(e)}", exc_info=True) + return {"error": str(e)} diff --git a/services/audio_mixing.py b/services/audio_mixing.py new file mode 100644 index 0000000000000000000000000000000000000000..f8553d61a3c539d966cddfed0b6a62a33ff48558 --- /dev/null +++ b/services/audio_mixing.py @@ -0,0 +1,84 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import subprocess +from services.file_management import download_file + +STORAGE_PATH = "/tmp/" + +def get_duration(file_path): + cmd = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path] + result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + return float(result.stdout) + +def process_audio_mixing(video_url, audio_url, video_vol, audio_vol, output_length, job_id, webhook_url=None): + video_path = download_file(video_url, STORAGE_PATH) + audio_path = download_file(audio_url, STORAGE_PATH) + output_path = os.path.join(STORAGE_PATH, f"{job_id}.mp4") + + video_duration = get_duration(video_path) + audio_duration = get_duration(audio_path) + + # Explicitly set output duration based on output_length + output_duration = video_duration if output_length == 'video' else audio_duration + + # Prepare FFmpeg command + cmd = ['ffmpeg', '-y'] + + # Input video + cmd.extend(['-i', video_path]) + + # Input audio + cmd.extend(['-i', audio_path]) + + # Video settings + if output_length == 'audio' and audio_duration > video_duration: + cmd.extend(['-stream_loop', '-1']) # Loop video only if output_length is 'audio' and audio is longer + + # Audio settings + audio_filter = f'[1:a]volume={audio_vol/100}' + if output_length == 'video': + audio_filter += f',atrim=duration={video_duration}' + audio_filter += '[a]' + cmd.extend(['-filter_complex', audio_filter]) + + # Output settings + cmd.extend(['-map', '0:v']) # Map video from first input + cmd.extend(['-map', '[a]']) # Map processed audio + + if output_length == 'audio' and audio_duration > video_duration: + cmd.extend(['-c:v', 'libx264']) # Re-encode video if looping + else: + cmd.extend(['-c:v', 'copy']) # Copy video codec otherwise + + cmd.extend(['-c:a', 'aac']) # Always encode audio to AAC + + # Explicitly set output duration + cmd.extend(['-t', str(output_duration)]) + + cmd.append(output_path) + + # Run FFmpeg command + subprocess.run(cmd, check=True) + + # Clean up input files + os.remove(video_path) + os.remove(audio_path) + + return output_path \ No newline at end of file diff --git a/services/authentication.py b/services/authentication.py new file mode 100644 index 0000000000000000000000000000000000000000..2b546dc0f4723915752309d791850697ef04bb12 --- /dev/null +++ b/services/authentication.py @@ -0,0 +1,31 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +from functools import wraps +from flask import request, jsonify +from config import API_KEY + +def authenticate(func): + @wraps(func) + def wrapper(*args, **kwargs): + api_key = request.headers.get('X-API-Key') + + if api_key != API_KEY: + return jsonify({"message": "Unauthorized"}), 401 + return func(*args, **kwargs) + return wrapper diff --git a/services/caption_video.py b/services/caption_video.py new file mode 100644 index 0000000000000000000000000000000000000000..8a93cb07d42f5ba5bf73ee0e65689f9c00b5168d --- /dev/null +++ b/services/caption_video.py @@ -0,0 +1,237 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import ffmpeg +import logging +import requests +import subprocess +from services.file_management import download_file + +# Set the default local storage directory +STORAGE_PATH = "/tmp/" + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Define the path to the fonts directory +FONTS_DIR = '/usr/share/fonts/custom' + +# Create the FONT_PATHS dictionary by reading the fonts directory +FONT_PATHS = {} +for font_file in os.listdir(FONTS_DIR): + if font_file.endswith('.ttf') or font_file.endswith('.TTF'): + font_name = os.path.splitext(font_file)[0] + FONT_PATHS[font_name] = os.path.join(FONTS_DIR, font_file) +# logger.info(f"Available fonts: {FONT_PATHS}") + +# Create a list of acceptable font names +ACCEPTABLE_FONTS = list(FONT_PATHS.keys()) +#logger.info(f"Acceptable font names: {ACCEPTABLE_FONTS}") + +# Match font files with fontconfig names +def match_fonts(): + try: + result = subprocess.run(['fc-list', ':family'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + if result.returncode == 0: + fontconfig_fonts = result.stdout.split('\n') + fontconfig_fonts = list(set(fontconfig_fonts)) # Remove duplicates + matched_fonts = {} + for font_file in FONT_PATHS.keys(): + for fontconfig_font in fontconfig_fonts: + if font_file.lower() in fontconfig_font.lower(): + matched_fonts[font_file] = fontconfig_font.strip() + + # Parse and output the matched font names + unique_font_names = set() + for font in matched_fonts.values(): + font_name = font.split(':')[1].strip() + unique_font_names.add(font_name) + + # Remove duplicates from font_name and sort them alphabetically + unique_font_names = sorted(list(set(unique_font_names))) + + # for font_name in unique_font_names: + # print(font_name) + else: + logger.error(f"Error matching fonts: {result.stderr}") + except Exception as e: + logger.error(f"Exception while matching fonts: {str(e)}") + +match_fonts() + +def generate_style_line(options): + """Generate ASS style line from options.""" + style_options = { + 'Name': 'Default', + 'Fontname': options.get('font_name', 'Arial'), + 'Fontsize': options.get('font_size', 12), + 'PrimaryColour': options.get('primary_color', '&H00FFFFFF'), + 'OutlineColour': options.get('outline_color', '&H00000000'), + 'BackColour': options.get('back_color', '&H00000000'), + 'Bold': options.get('bold', 0), + 'Italic': options.get('italic', 0), + 'Underline': options.get('underline', 0), + 'StrikeOut': options.get('strikeout', 0), + 'ScaleX': 100, + 'ScaleY': 100, + 'Spacing': 0, + 'Angle': 0, + 'BorderStyle': 1, + 'Outline': options.get('outline', 1), + 'Shadow': options.get('shadow', 0), + 'Alignment': options.get('alignment', 2), + 'MarginL': options.get('margin_l', 10), + 'MarginR': options.get('margin_r', 10), + 'MarginV': options.get('margin_v', 10), + 'Encoding': options.get('encoding', 1) + } + return f"Style: {','.join(str(v) for v in style_options.values())}" + +def process_captioning(file_url, caption_srt, caption_type, options, job_id): + """Process video captioning using FFmpeg.""" + try: + logger.info(f"Job {job_id}: Starting download of file from {file_url}") + video_path = download_file(file_url, STORAGE_PATH) + logger.info(f"Job {job_id}: File downloaded to {video_path}") + + subtitle_extension = '.' + caption_type + srt_path = os.path.join(STORAGE_PATH, f"{job_id}{subtitle_extension}") + options = convert_array_to_collection(options) + caption_style = "" + + if caption_type == 'ass': + style_string = generate_style_line(options) + caption_style = f""" +[Script Info] +Title: Highlight Current Word +ScriptType: v4.00+ +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +{style_string} +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +""" + logger.info(f"Job {job_id}: Generated ASS style string: {style_string}") + + if caption_srt.startswith("https"): + # Download the file if caption_srt is a URL + logger.info(f"Job {job_id}: Downloading caption file from {caption_srt}") + response = requests.get(caption_srt) + response.raise_for_status() # Raise an exception for bad status codes + if caption_type in ['srt','vtt']: + with open(srt_path, 'wb') as srt_file: + srt_file.write(response.content) + else: + subtitle_content = caption_style + response.text + with open(srt_path, 'w') as srt_file: + srt_file.write(subtitle_content) + logger.info(f"Job {job_id}: Caption file downloaded to {srt_path}") + else: + # Write caption_srt content directly to file + subtitle_content = caption_style + caption_srt + with open(srt_path, 'w') as srt_file: + srt_file.write(subtitle_content) + logger.info(f"Job {job_id}: SRT file created at {srt_path}") + + output_path = os.path.join(STORAGE_PATH, f"{job_id}_captioned.mp4") + logger.info(f"Job {job_id}: Output path set to {output_path}") + + # Ensure font_name is converted to the full font path + font_name = options.get('font_name', 'Arial') + if font_name in FONT_PATHS: + selected_font = FONT_PATHS[font_name] + logger.info(f"Job {job_id}: Font path set to {selected_font}") + else: + selected_font = FONT_PATHS.get('Arial') + logger.warning(f"Job {job_id}: Font {font_name} not found. Using default font Arial.") + + # For ASS subtitles, we should avoid overriding styles + if subtitle_extension == '.ass': + # Use the subtitles filter without force_style + subtitle_filter = f"subtitles='{srt_path}'" + logger.info(f"Job {job_id}: Using ASS subtitle filter: {subtitle_filter}") + else: + # Construct FFmpeg filter options for subtitles with detailed styling + subtitle_filter = f"subtitles={srt_path}:force_style='" + style_options = { + 'FontName': font_name, # Use the font name instead of the font file path + 'FontSize': options.get('font_size', 24), + 'PrimaryColour': options.get('primary_color', '&H00FFFFFF'), + 'SecondaryColour': options.get('secondary_color', '&H00000000'), + 'OutlineColour': options.get('outline_color', '&H00000000'), + 'BackColour': options.get('back_color', '&H00000000'), + 'Bold': options.get('bold', 0), + 'Italic': options.get('italic', 0), + 'Underline': options.get('underline', 0), + 'StrikeOut': options.get('strikeout', 0), + 'Alignment': options.get('alignment', 2), + 'MarginV': options.get('margin_v', 10), + 'MarginL': options.get('margin_l', 10), + 'MarginR': options.get('margin_r', 10), + 'Outline': options.get('outline', 1), + 'Shadow': options.get('shadow', 0), + 'Blur': options.get('blur', 0), + 'BorderStyle': options.get('border_style', 1), + 'Encoding': options.get('encoding', 1), + 'Spacing': options.get('spacing', 0), + 'Angle': options.get('angle', 0), + 'UpperCase': options.get('uppercase', 0) + } + + # Add only populated options to the subtitle filter + subtitle_filter += ','.join(f"{k}={v}" for k, v in style_options.items() if v is not None) + subtitle_filter += "'" + logger.info(f"Job {job_id}: Using subtitle filter: {subtitle_filter}") + + try: + # Log the FFmpeg command for debugging + logger.info(f"Job {job_id}: Running FFmpeg with filter: {subtitle_filter}") + + # Run FFmpeg to add subtitles to the video + ffmpeg.input(video_path).output( + output_path, + vf=subtitle_filter, + acodec='copy' + ).run() + logger.info(f"Job {job_id}: FFmpeg processing completed, output file at {output_path}") + except ffmpeg.Error as e: + # Log the FFmpeg stderr output + if e.stderr: + error_message = e.stderr.decode('utf8') + else: + error_message = 'Unknown FFmpeg error' + logger.error(f"Job {job_id}: FFmpeg error: {error_message}") + raise + + # The upload process will be handled by the calling function + return output_path + + # Clean up local files + os.remove(video_path) + os.remove(srt_path) + os.remove(output_path) + logger.info(f"Job {job_id}: Local files cleaned up") + except Exception as e: + logger.error(f"Job {job_id}: Error in process_captioning: {str(e)}") + raise + +def convert_array_to_collection(options): + logger.info(f"Converting options array to dictionary: {options}") + return {item["option"]: item["value"] for item in options} diff --git a/services/cloud_storage.py b/services/cloud_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..936572d2555cfbd6f3cceff3199f2edec796e466 --- /dev/null +++ b/services/cloud_storage.py @@ -0,0 +1,118 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import logging +from abc import ABC, abstractmethod +from services.gcp_toolkit import upload_to_gcs +from services.s3_toolkit import upload_to_s3 +from config import validate_env_vars +from urllib.parse import urlparse + +logger = logging.getLogger(__name__) + +def parse_s3_url(s3_url): + """Parse S3 URL to extract bucket name, region, and endpoint URL.""" + parsed_url = urlparse(s3_url) + + # Extract bucket name from the host + bucket_name = parsed_url.hostname.split('.')[0] + + # Extract region from the host + region = parsed_url.hostname.split('.')[1] + + return bucket_name, region + +class CloudStorageProvider(ABC): + @abstractmethod + def upload_file(self, file_path: str) -> str: + pass + +class GCPStorageProvider(CloudStorageProvider): + def __init__(self): + self.bucket_name = os.getenv('GCP_BUCKET_NAME') + + def upload_file(self, file_path: str) -> str: + return upload_to_gcs(file_path, self.bucket_name) + +class S3CompatibleProvider(CloudStorageProvider): + def __init__(self): + + self.endpoint_url = os.getenv('S3_ENDPOINT_URL') + self.access_key = os.getenv('S3_ACCESS_KEY') + self.secret_key = os.getenv('S3_SECRET_KEY') + self.bucket_name = os.environ.get('S3_BUCKET_NAME', '') + self.region = os.environ.get('S3_REGION', '') + + # Check if endpoint is Digital Ocean and bucket name or region is missing + if (self.endpoint_url and + 'digitalocean' in self.endpoint_url.lower() and + (not self.bucket_name or not self.region)): + + logger.info("Digital Ocean endpoint detected with missing bucket or region. Extracting from URL.") + try: + # Extract bucket name and region from URL like https://sgp-labs.nyc3.digitaloceanspaces.com + parsed_url = urlparse(self.endpoint_url) + hostname_parts = parsed_url.hostname.split('.') + + # The first part is the bucket name (sgp-labs) + if not self.bucket_name: + self.bucket_name = hostname_parts[0] + logger.info(f"Extracted bucket name from URL: {self.bucket_name}") + + # The second part is the region (nyc3) + if not self.region: + self.region = hostname_parts[1] + logger.info(f"Extracted region from URL: {self.region}") + + except Exception as e: + logger.warning(f"Failed to parse Digital Ocean URL: {e}. Using provided values.") + + def upload_file(self, file_path: str) -> str: + return upload_to_s3(file_path, self.endpoint_url, self.access_key, self.secret_key, self.bucket_name, self.region) + +def get_storage_provider() -> CloudStorageProvider: + + if os.getenv('S3_ENDPOINT_URL'): + + if ('digitalocean' in os.getenv('S3_ENDPOINT_URL').lower()): + + validate_env_vars('S3_DO') + else: + validate_env_vars('S3') + + return S3CompatibleProvider() + + if os.getenv('GCP_BUCKET_NAME'): + + validate_env_vars('GCP') + return GCPStorageProvider() + + raise ValueError(f"No cloud storage settings provided.") + +def upload_file(file_path: str) -> str: + provider = get_storage_provider() + try: + logger.info(f"Uploading file to cloud storage: {file_path}") + url = provider.upload_file(file_path) + logger.info(f"File uploaded successfully: {url}") + return url + except Exception as e: + logger.error(f"Error uploading file to cloud storage: {e}") + raise + \ No newline at end of file diff --git a/services/extract_keyframes.py b/services/extract_keyframes.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e32492a5459c33c90f3a1c42b1b1ad34aedcba --- /dev/null +++ b/services/extract_keyframes.py @@ -0,0 +1,53 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import subprocess +import json +from services.file_management import download_file + +STORAGE_PATH = "/tmp/" + +def process_keyframe_extraction(video_url, job_id): + video_path = download_file(video_url, STORAGE_PATH) + + # Extract keyframes + output_pattern = os.path.join(STORAGE_PATH, f"{job_id}_%03d.jpg") + cmd = [ + 'ffmpeg', + '-i', video_path, + '-vf', f"select='eq(pict_type,I)',scale=iw*sar:ih,setsar=1", + '-vsync', 'vfr', + output_pattern + ] + + print(f"Images: {cmd}") + + subprocess.run(cmd, check=True) + + # Upload keyframes to GCS and get URLs + output_filenames = [] + for filename in sorted(os.listdir(STORAGE_PATH)): + if filename.startswith(f"{job_id}_") and filename.endswith(".jpg"): + file_path = os.path.join(STORAGE_PATH, filename) + output_filenames.append(file_path) + + # Clean up input file + os.remove(video_path) + + return output_filenames \ No newline at end of file diff --git a/services/ffmpeg_toolkit.py b/services/ffmpeg_toolkit.py new file mode 100644 index 0000000000000000000000000000000000000000..3b4564315c7c9fb4bb714dfe20d8f42546738d9b --- /dev/null +++ b/services/ffmpeg_toolkit.py @@ -0,0 +1,97 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import ffmpeg +import requests +from services.file_management import download_file + +# Set the default local storage directory +STORAGE_PATH = "/tmp/" + +def process_conversion(media_url, job_id, bitrate='128k', webhook_url=None): + """Convert media to MP3 format with specified bitrate.""" + input_filename = download_file(media_url, os.path.join(STORAGE_PATH, f"{job_id}_input")) + output_filename = f"{job_id}.mp3" + output_path = os.path.join(STORAGE_PATH, output_filename) + + try: + # Convert media file to MP3 with specified bitrate + ( + ffmpeg + .input(input_filename) + .output(output_path, acodec='libmp3lame', audio_bitrate=bitrate) + .overwrite_output() + .run(capture_stdout=True, capture_stderr=True) + ) + os.remove(input_filename) + print(f"Conversion successful: {output_path} with bitrate {bitrate}") + + # Ensure the output file exists locally before attempting upload + if not os.path.exists(output_path): + raise FileNotFoundError(f"Output file {output_path} does not exist after conversion.") + + return output_path + + except Exception as e: + print(f"Conversion failed: {str(e)}") + raise + +def process_video_combination(media_urls, job_id, webhook_url=None): + """Combine multiple videos into one.""" + input_files = [] + output_filename = f"{job_id}.mp4" + output_path = os.path.join(STORAGE_PATH, output_filename) + + try: + # Download all media files + for i, media_item in enumerate(media_urls): + url = media_item['video_url'] + input_filename = download_file(url, os.path.join(STORAGE_PATH, f"{job_id}_input_{i}")) + input_files.append(input_filename) + + # Generate an absolute path concat list file for FFmpeg + concat_file_path = os.path.join(STORAGE_PATH, f"{job_id}_concat_list.txt") + with open(concat_file_path, 'w') as concat_file: + for input_file in input_files: + # Write absolute paths to the concat list + concat_file.write(f"file '{os.path.abspath(input_file)}'\n") + + # Use the concat demuxer to concatenate the videos + ( + ffmpeg.input(concat_file_path, format='concat', safe=0). + output(output_path, c='copy'). + run(overwrite_output=True) + ) + + # Clean up input files + for f in input_files: + os.remove(f) + + os.remove(concat_file_path) # Remove the concat list file after the operation + + print(f"Video combination successful: {output_path}") + + # Check if the output file exists locally before upload + if not os.path.exists(output_path): + raise FileNotFoundError(f"Output file {output_path} does not exist after combination.") + + return output_path + except Exception as e: + print(f"Video combination failed: {str(e)}") + raise diff --git a/services/file_management.py b/services/file_management.py new file mode 100644 index 0000000000000000000000000000000000000000..256c299edf32235633e4752f92b4b33a68b89237 --- /dev/null +++ b/services/file_management.py @@ -0,0 +1,81 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import uuid +import requests +from urllib.parse import urlparse, parse_qs +import mimetypes + +def get_extension_from_url(url): + """Extract file extension from URL or content type. + + Args: + url (str): The URL to extract the extension from + + Returns: + str: The file extension including the dot (e.g., '.jpg') + + Raises: + ValueError: If no valid extension can be determined from the URL or content type + """ + # First try to get extension from URL + parsed_url = urlparse(url) + path = parsed_url.path + if path: + ext = os.path.splitext(path)[1].lower() + if ext: + return ext + + # If no extension in URL, try to determine from content type + try: + response = requests.head(url, allow_redirects=True) + content_type = response.headers.get('content-type', '').split(';')[0] + ext = mimetypes.guess_extension(content_type) + if ext: + return ext.lower() + except: + pass + + # If we can't determine the extension, raise an error + raise ValueError(f"Could not determine file extension from URL: {url}") + +def download_file(url, storage_path="/tmp/"): + """Download a file from URL to local storage.""" + # Create storage directory if it doesn't exist + os.makedirs(storage_path, exist_ok=True) + + file_id = str(uuid.uuid4()) + extension = get_extension_from_url(url) + local_filename = os.path.join(storage_path, f"{file_id}{extension}") + + try: + response = requests.get(url, stream=True) + response.raise_for_status() + + with open(local_filename, 'wb') as f: + for chunk in response.iter_content(chunk_size=8192): + if chunk: + f.write(chunk) + + return local_filename + except Exception as e: + if os.path.exists(local_filename): + os.remove(local_filename) + raise e + diff --git a/services/gcp_toolkit.py b/services/gcp_toolkit.py new file mode 100644 index 0000000000000000000000000000000000000000..30229a7ca8017c1322c46cdad72cd91b3779ef3a --- /dev/null +++ b/services/gcp_toolkit.py @@ -0,0 +1,71 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import json +import logging +from google.oauth2 import service_account +from google.cloud import storage + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# GCS environment variables +GCP_BUCKET_NAME = os.getenv('GCP_BUCKET_NAME') +STORAGE_PATH = "/tmp/" +gcs_client = None + +def initialize_gcp_client(): + GCP_SA_CREDENTIALS = os.getenv('GCP_SA_CREDENTIALS') + + if not GCP_SA_CREDENTIALS: + #logger.warning("GCP credentials not found. Skipping GCS client initialization.") + return None # Skip client initialization if credentials are missing + + # Define the required scopes for Google Cloud Storage + GCS_SCOPES = ['https://www.googleapis.com/auth/devstorage.full_control'] + + try: + credentials_info = json.loads(GCP_SA_CREDENTIALS) + gcs_credentials = service_account.Credentials.from_service_account_info( + credentials_info, + scopes=GCS_SCOPES + ) + return storage.Client(credentials=gcs_credentials) + except Exception as e: + logger.error(f"Failed to initialize GCS client: {e}") + return None + +# Initialize the GCS client +gcs_client = initialize_gcp_client() + +def upload_to_gcs(file_path, bucket_name=GCP_BUCKET_NAME): + if not gcs_client: + raise ValueError("GCS client is not initialized. Skipping file upload.") + + try: + logger.info(f"Uploading file to Google Cloud Storage: {file_path}") + bucket = gcs_client.bucket(bucket_name) + blob = bucket.blob(os.path.basename(file_path)) + blob.upload_from_filename(file_path) + logger.info(f"File uploaded successfully to GCS: {blob.public_url}") + return blob.public_url + except Exception as e: + logger.error(f"Error uploading file to GCS: {e}") + raise diff --git a/services/image_to_video.py b/services/image_to_video.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c8c22e6f5fa3a82bacc0abe8a7623127fb6a2d --- /dev/null +++ b/services/image_to_video.py @@ -0,0 +1,81 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import subprocess +import logging +from services.file_management import download_file +from PIL import Image + +STORAGE_PATH = "/tmp/" +logger = logging.getLogger(__name__) + +def process_image_to_video(image_url, length, frame_rate, zoom_speed, job_id, webhook_url=None): + try: + # Download the image file + image_path = download_file(image_url, STORAGE_PATH) + logger.info(f"Downloaded image to {image_path}") + + # Get image dimensions using Pillow + with Image.open(image_path) as img: + width, height = img.size + logger.info(f"Original image dimensions: {width}x{height}") + + # Prepare the output path + output_path = os.path.join(STORAGE_PATH, f"{job_id}.mp4") + + # Determine orientation and set appropriate dimensions + if width > height: + scale_dims = "7680:4320" + output_dims = "1920x1080" + else: + scale_dims = "4320:7680" + output_dims = "1080x1920" + + # Calculate total frames and zoom factor + total_frames = float(length * frame_rate) + zoom_factor = 1 + (zoom_speed * length) + + logger.info(f"Using scale dimensions: {scale_dims}, output dimensions: {output_dims}") + logger.info(f"Video length: {length}s, Frame rate: {frame_rate}fps, Total frames: {total_frames}") + logger.info(f"Zoom speed: {zoom_speed}/s, Final zoom factor: {zoom_factor}") + + # Prepare FFmpeg command + cmd = [ + 'ffmpeg', '-framerate', str(frame_rate), '-loop', '1', '-i', image_path, + '-vf', f"scale={scale_dims},zoompan=z='min(1+({zoom_speed}*{length})*on/{total_frames}, {zoom_factor})':d={total_frames}:x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':s={output_dims}", + '-c:v', 'libx264', '-t', str(length), '-pix_fmt', 'yuv420p', output_path + ] + + logger.info(f"Running FFmpeg command: {' '.join(cmd)}") + + # Run FFmpeg command + result = subprocess.run(cmd, capture_output=True, text=True) + if result.returncode != 0: + logger.error(f"FFmpeg command failed. Error: {result.stderr}") + raise subprocess.CalledProcessError(result.returncode, cmd, result.stdout, result.stderr) + + logger.info(f"Video created successfully: {output_path}") + + # Clean up input file + os.remove(image_path) + + return output_path + except Exception as e: + logger.error(f"Error in process_image_to_video: {str(e)}", exc_info=True) + raise \ No newline at end of file diff --git a/services/s3_toolkit.py b/services/s3_toolkit.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0dc9709730c8d0a127902989a6d3ab56ed59dd --- /dev/null +++ b/services/s3_toolkit.py @@ -0,0 +1,49 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import boto3 +import logging +from urllib.parse import urlparse, quote + +logger = logging.getLogger(__name__) + +def upload_to_s3(file_path, s3_url, access_key, secret_key, bucket_name, region): + # Parse the S3 URL into bucket, region, and endpoint + #bucket_name, region, endpoint_url = parse_s3_url(s3_url) + + session = boto3.Session( + aws_access_key_id=access_key, + aws_secret_access_key=secret_key, + region_name=region + ) + + client = session.client('s3', endpoint_url=s3_url) + + try: + # Upload the file to the specified S3 bucket + with open(file_path, 'rb') as data: + client.upload_fileobj(data, bucket_name, os.path.basename(file_path), ExtraArgs={'ACL': 'public-read'}) + + # URL encode the filename for the URL + encoded_filename = quote(os.path.basename(file_path)) + file_url = f"{s3_url}/{bucket_name}/{encoded_filename}" + return file_url + except Exception as e: + logger.error(f"Error uploading file to S3: {e}") + raise diff --git a/services/transcription.py b/services/transcription.py new file mode 100644 index 0000000000000000000000000000000000000000..0691be0d3795c570569d7dfdb966685e62babfd2 --- /dev/null +++ b/services/transcription.py @@ -0,0 +1,177 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import whisper +import srt +from datetime import timedelta +from whisper.utils import WriteSRT, WriteVTT +from services.file_management import download_file +import logging +import uuid + +# Set up logging +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +# Set the default local storage directory +STORAGE_PATH = "/tmp/" + +def process_transcription(media_url, output_type, max_chars=56, language=None,): + """Transcribe media and return the transcript, SRT or ASS file path.""" + logger.info(f"Starting transcription for media URL: {media_url} with output type: {output_type}") + input_filename = download_file(media_url, os.path.join(STORAGE_PATH, 'input_media')) + logger.info(f"Downloaded media to local file: {input_filename}") + + try: + model = whisper.load_model("base") + logger.info("Loaded Whisper model") + + # result = model.transcribe(input_filename) + # logger.info("Transcription completed") + + if output_type == 'transcript': + result = model.transcribe(input_filename, language=language) + output = result['text'] + logger.info("Generated transcript output") + elif output_type in ['srt', 'vtt']: + + result = model.transcribe(input_filename) + srt_subtitles = [] + for i, segment in enumerate(result['segments'], start=1): + start = timedelta(seconds=segment['start']) + end = timedelta(seconds=segment['end']) + text = segment['text'].strip() + srt_subtitles.append(srt.Subtitle(i, start, end, text)) + + output_content = srt.compose(srt_subtitles) + + # Write the output to a file + output_filename = os.path.join(STORAGE_PATH, f"{uuid.uuid4()}.{output_type}") + with open(output_filename, 'w') as f: + f.write(output_content) + + output = output_filename + logger.info(f"Generated {output_type.upper()} output: {output}") + + elif output_type == 'ass': + result = model.transcribe( + input_filename, + word_timestamps=True, + task='transcribe', + verbose=False + ) + logger.info("Transcription completed with word-level timestamps") + # Generate ASS subtitle content + ass_content = generate_ass_subtitle(result, max_chars) + logger.info("Generated ASS subtitle content") + + output_content = ass_content + + # Write the ASS content to a file + output_filename = os.path.join(STORAGE_PATH, f"{uuid.uuid4()}.{output_type}") + with open(output_filename, 'w') as f: + f.write(output_content) + output = output_filename + logger.info(f"Generated {output_type.upper()} output: {output}") + else: + raise ValueError("Invalid output type. Must be 'transcript', 'srt', or 'vtt'.") + + os.remove(input_filename) + logger.info(f"Removed local file: {input_filename}") + logger.info(f"Transcription successful, output type: {output_type}") + return output + except Exception as e: + logger.error(f"Transcription failed: {str(e)}") + raise + + +def generate_ass_subtitle(result, max_chars): + """Generate ASS subtitle content with highlighted current words, showing one line at a time.""" + logger.info("Generate ASS subtitle content with highlighted current words") + # ASS file header + ass_content = "" + + # Helper function to format time + def format_time(t): + hours = int(t // 3600) + minutes = int((t % 3600) // 60) + seconds = int(t % 60) + centiseconds = int(round((t - int(t)) * 100)) + return f"{hours}:{minutes:02d}:{seconds:02d}.{centiseconds:02d}" + + max_chars_per_line = max_chars # Maximum characters per line + + # Process each segment + for segment in result['segments']: + words = segment.get('words', []) + if not words: + continue # Skip if no word-level timestamps + + # Group words into lines + lines = [] + current_line = [] + current_line_length = 0 + for word_info in words: + word_length = len(word_info['word']) + 1 # +1 for space + if current_line_length + word_length > max_chars_per_line: + lines.append(current_line) + current_line = [word_info] + current_line_length = word_length + else: + current_line.append(word_info) + current_line_length += word_length + if current_line: + lines.append(current_line) + + # Generate events for each line + for line in lines: + line_start_time = line[0]['start'] + line_end_time = line[-1]['end'] + + # Generate events for highlighting each word + for i, word_info in enumerate(line): + start_time = word_info['start'] + end_time = word_info['end'] + current_word = word_info['word'] + + # Build the line text with highlighted current word + caption_parts = [] + for w in line: + word_text = w['word'] + if w == word_info: + # Highlight current word + caption_parts.append(r'{\c&H00FFFF&}' + word_text) + else: + # Default color + caption_parts.append(r'{\c&HFFFFFF&}' + word_text) + caption_with_highlight = ' '.join(caption_parts) + + # Format times + start = format_time(start_time) + # End the dialogue event when the next word starts or at the end of the line + if i + 1 < len(line): + end_time = line[i + 1]['start'] + else: + end_time = line_end_time + end = format_time(end_time) + + # Add the dialogue line + ass_content += f"Dialogue: 0,{start},{end},Default,,0,0,0,,{caption_with_highlight}\n" + + return ass_content \ No newline at end of file diff --git a/services/v1/audio/concatenate.py b/services/v1/audio/concatenate.py new file mode 100644 index 0000000000000000000000000000000000000000..1670eed05b367dc8d6c6a57ab812ef980bbe7853 --- /dev/null +++ b/services/v1/audio/concatenate.py @@ -0,0 +1,66 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import ffmpeg +from services.file_management import download_file +from config import LOCAL_STORAGE_PATH + +def process_audio_concatenate(media_urls, job_id, webhook_url=None): + """Combine multiple audio files into one.""" + input_files = [] + output_filename = f"{job_id}.mp3" + output_path = os.path.join(LOCAL_STORAGE_PATH, output_filename) + + try: + # Download all media files + for i, media_item in enumerate(media_urls): + url = media_item['audio_url'] + input_filename = download_file(url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input_{i}")) + input_files.append(input_filename) + + # Generate an absolute path concat list file for FFmpeg + concat_file_path = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_concat_list.txt") + with open(concat_file_path, 'w') as concat_file: + for input_file in input_files: + # Write absolute paths to the concat list + concat_file.write(f"file '{os.path.abspath(input_file)}'\n") + + # Use the concat demuxer to concatenate the audio files without re-encoding + ( + ffmpeg.input(concat_file_path, format='concat', safe=0). + output(output_path, c='copy'). + run(overwrite_output=True) + ) + + # Clean up input files + for f in input_files: + os.remove(f) + + os.remove(concat_file_path) # Remove the concat list file after the operation + + print(f"Audio combination successful: {output_path}") + + # Check if the output file exists locally before upload + if not os.path.exists(output_path): + raise FileNotFoundError(f"Output file {output_path} does not exist after combination.") + + return output_path + except Exception as e: + print(f"Audio combination failed: {str(e)}") + raise \ No newline at end of file diff --git a/services/v1/ffmpeg/ffmpeg_compose.py b/services/v1/ffmpeg/ffmpeg_compose.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6713a2aa685c39b65d1251cbeb5aba53bc6950 --- /dev/null +++ b/services/v1/ffmpeg/ffmpeg_compose.py @@ -0,0 +1,177 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import subprocess +import json +import re +from services.file_management import download_file +from config import LOCAL_STORAGE_PATH + +def get_extension_from_format(format_name): + # Mapping of common format names to file extensions + format_to_extension = { + 'mp4': 'mp4', + 'mov': 'mov', + 'avi': 'avi', + 'mkv': 'mkv', + 'webm': 'webm', + 'gif': 'gif', + 'apng': 'apng', + 'jpg': 'jpg', + 'jpeg': 'jpg', + 'png': 'png', + 'image2': 'png', # Assume png for image2 format + 'rawvideo': 'raw', + 'mp3': 'mp3', + 'wav': 'wav', + 'aac': 'aac', + 'flac': 'flac', + 'ogg': 'ogg' + } + return format_to_extension.get(format_name.lower(), 'mp4') # Default to mp4 if unknown + +def get_metadata(filename, metadata_requests, job_id): + metadata = {} + if metadata_requests.get('thumbnail'): + thumbnail_filename = f"{os.path.splitext(filename)[0]}_thumbnail.jpg" + thumbnail_command = [ + 'ffmpeg', + '-i', filename, + '-vf', 'select=eq(n\,0)', + '-vframes', '1', + thumbnail_filename + ] + try: + subprocess.run(thumbnail_command, check=True, capture_output=True, text=True) + if os.path.exists(thumbnail_filename): + metadata['thumbnail'] = thumbnail_filename # Return local path instead of URL + except subprocess.CalledProcessError as e: + print(f"Thumbnail generation failed: {e.stderr}") + + if metadata_requests.get('filesize'): + metadata['filesize'] = os.path.getsize(filename) + + if metadata_requests.get('encoder') or metadata_requests.get('duration') or metadata_requests.get('bitrate'): + ffprobe_command = [ + 'ffprobe', + '-v', 'quiet', + '-print_format', 'json', + '-show_format', + '-show_streams', + filename + ] + result = subprocess.run(ffprobe_command, capture_output=True, text=True) + probe_data = json.loads(result.stdout) + + if metadata_requests.get('duration'): + metadata['duration'] = float(probe_data['format']['duration']) + if metadata_requests.get('bitrate'): + metadata['bitrate'] = int(probe_data['format']['bit_rate']) + + if metadata_requests.get('encoder'): + metadata['encoder'] = {} + for stream in probe_data['streams']: + if stream['codec_type'] == 'video': + metadata['encoder']['video'] = stream.get('codec_name', 'unknown') + elif stream['codec_type'] == 'audio': + metadata['encoder']['audio'] = stream.get('codec_name', 'unknown') + + return metadata + +def process_ffmpeg_compose(data, job_id): + output_filenames = [] + + # Build FFmpeg command + command = ["ffmpeg"] + + # Add global options + for option in data.get("global_options", []): + command.append(option["option"]) + if "argument" in option and option["argument"] is not None: + command.append(str(option["argument"])) + + # Add inputs + input_paths = [] + for input_data in data["inputs"]: + if "options" in input_data: + for option in input_data["options"]: + command.append(option["option"]) + if "argument" in option and option["argument"] is not None: + command.append(str(option["argument"])) + input_path = download_file(input_data["file_url"], LOCAL_STORAGE_PATH) + input_paths.append(input_path) + command.extend(["-i", input_path]) + + # Add filters + subtitles_paths = [] # Track downloaded subtitles/filter files + if data.get("filters"): + new_filters = [] + for filter_obj in data["filters"]: + filter_str = filter_obj["filter"] + def replace_subtitles_url(match): + url = match.group(1) + local_path = download_file(url, LOCAL_STORAGE_PATH) + subtitles_paths.append(local_path) + fixed_path = local_path.replace('\\', '/') + return f"subtitles='{fixed_path}" # keep the opening quote + # Regex: subtitles='' or subtitles="" + filter_str = re.sub(r"subtitles=['\"]([^'\"]+)", replace_subtitles_url, filter_str) + new_filters.append(filter_str) + filter_complex = ";".join(new_filters) + command.extend(["-filter_complex", filter_complex]) + + # Add outputs + for i, output in enumerate(data["outputs"]): + format_name = None + for option in output["options"]: + if option["option"] == "-f": + format_name = option.get("argument") + break + + extension = get_extension_from_format(format_name) if format_name else 'mp4' + output_filename = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_output_{i}.{extension}") + output_filenames.append(output_filename) + + for option in output["options"]: + command.append(option["option"]) + if "argument" in option and option["argument"] is not None: + command.append(str(option["argument"])) + command.append(output_filename) + + # Execute FFmpeg command + try: + subprocess.run(command, check=True, capture_output=True, text=True) + except subprocess.CalledProcessError as e: + raise Exception(f"FFmpeg command failed: {e.stderr}") + + # Clean up input files + for input_path in input_paths: + if os.path.exists(input_path): + os.remove(input_path) + # Clean up subtitles/filter files + for subtitles_path in subtitles_paths: + if os.path.exists(subtitles_path): + os.remove(subtitles_path) + # Get metadata if requested + metadata = [] + if data.get("metadata"): + for output_filename in output_filenames: + metadata.append(get_metadata(output_filename, data["metadata"], job_id)) + + return output_filenames, metadata \ No newline at end of file diff --git a/services/v1/image/convert/image_to_video.py b/services/v1/image/convert/image_to_video.py new file mode 100644 index 0000000000000000000000000000000000000000..7bce0481b79ad66e68b5a3958b0224d43b7aca20 --- /dev/null +++ b/services/v1/image/convert/image_to_video.py @@ -0,0 +1,80 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import subprocess +import logging +from services.file_management import download_file +from PIL import Image +from config import LOCAL_STORAGE_PATH +logger = logging.getLogger(__name__) + +def process_image_to_video(image_url, length, frame_rate, zoom_speed, job_id, webhook_url=None): + try: + # Download the image file + image_path = download_file(image_url, LOCAL_STORAGE_PATH) + logger.info(f"Downloaded image to {image_path}") + + # Get image dimensions using Pillow + with Image.open(image_path) as img: + width, height = img.size + logger.info(f"Original image dimensions: {width}x{height}") + + # Prepare the output path + output_path = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}.mp4") + + # Determine orientation and set appropriate dimensions + if width > height: + scale_dims = "7680:4320" + output_dims = "1920x1080" + else: + scale_dims = "4320:7680" + output_dims = "1080x1920" + + # Calculate total frames and zoom factor + total_frames = int(length * frame_rate) + zoom_factor = 1 + (zoom_speed * length) + + logger.info(f"Using scale dimensions: {scale_dims}, output dimensions: {output_dims}") + logger.info(f"Video length: {length}s, Frame rate: {frame_rate}fps, Total frames: {total_frames}") + logger.info(f"Zoom speed: {zoom_speed}/s, Final zoom factor: {zoom_factor}") + + # Prepare FFmpeg command with fps filter to ensure correct frame rate + cmd = [ + 'ffmpeg', '-framerate', str(frame_rate), '-loop', '1', '-i', image_path, + '-vf', f"scale={scale_dims},zoompan=z='min(1+({zoom_speed}*{length})*on/{total_frames}, {zoom_factor})':d={total_frames}:x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':s={output_dims},fps={frame_rate}", + '-c:v', 'libx264', '-r', str(frame_rate), '-t', str(length), '-pix_fmt', 'yuv420p', output_path + ] + + logger.info(f"Running FFmpeg command: {' '.join(cmd)}") + + # Run FFmpeg command + result = subprocess.run(cmd, capture_output=True, text=True) + if result.returncode != 0: + logger.error(f"FFmpeg command failed. Error: {result.stderr}") + raise subprocess.CalledProcessError(result.returncode, cmd, result.stdout, result.stderr) + + logger.info(f"Video created successfully: {output_path}") + + # Clean up input file + os.remove(image_path) + + return output_path + except Exception as e: + logger.error(f"Error in process_image_to_video: {str(e)}", exc_info=True) + raise \ No newline at end of file diff --git a/services/v1/image/screenshot_webpage.py b/services/v1/image/screenshot_webpage.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3143be7d6d76a8c324e50953ebcb26dbc7d0af --- /dev/null +++ b/services/v1/image/screenshot_webpage.py @@ -0,0 +1,152 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + +# Author: Harrison Fisher (https://github.com/HarrisonFisher) +# Date: April 2025 +# Created new service: /v1/playwright/screenshot + +import os +import logging +from io import BytesIO +from playwright.sync_api import sync_playwright + +# Initialize logger +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +if not logger.hasHandlers(): + handler = logging.StreamHandler() + formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + handler.setFormatter(formatter) + logger.addHandler(handler) + +def take_screenshot(data: dict, job_id=None): + p = sync_playwright().start() + try: + browser = p.chromium.launch(headless=True) + try: + context = browser.new_context( + viewport={"width": data.get("viewport_width", 1280), "height": data.get("viewport_height", 720)}, + device_scale_factor=data.get("device_scale_factor", 1), + user_agent=data.get("user_agent") + ) + page = context.new_page() + + # Validate and set headers + if data.get("headers"): + page.set_extra_http_headers(data["headers"]) + + # Validate and set cookies + if data.get("cookies"): + from urllib.parse import urlparse + url_domain = None + if data.get("url"): + url_domain = urlparse(data["url"]).hostname + elif data.get("html"): + url_domain = None + for cookie in data["cookies"]: + cookie.setdefault("path", "/") + cookie_domain = cookie["domain"].lstrip(".") + if url_domain and not (url_domain == cookie_domain or url_domain.endswith(f".{cookie_domain}")): + raise Exception("COOKIE_DOMAIN_MISMATCH") + context.add_cookies(data["cookies"]) + + # Set page content from html or navigate to url + if data.get("html"): + page.set_content(data["html"]) + elif data.get("url"): + page.goto(data["url"], timeout=data.get("timeout", 30000), wait_until=data.get("wait_until", "load")) + else: + raise Exception("MISSING_URL_OR_HTML") + + # Wait for a selector if specified + if data.get("wait_for_selector"): + try: + page.wait_for_selector(data["wait_for_selector"]) + except Exception as e: + raise Exception("WAIT_FOR_SELECTOR_NOT_FOUND") + + # Emulate media features + if data.get("emulate"): + if "color_scheme" in data["emulate"]: + page.emulate_media(color_scheme=data["emulate"]["color_scheme"]) + + # Delay if specified + if data.get("delay"): + page.wait_for_timeout(data["delay"]) + + # Inject custom CSS if provided + if data.get("css"): + page.add_style_tag(content=data["css"]) + # Inject custom JS if provided + if data.get("js"): + page.add_script_tag(content=data["js"]) + + screenshot_io = BytesIO() + + # Ensure omit_background is only used with PNG + if data.get("omit_background", False) and data.get("format", "png") == "jpeg": + raise Exception("OMIT_BACKGROUND_JPEG_UNSUPPORTED") + + # and doesn't support quality settings - quality parameter only works with JPEG + if data.get("format", "png") == "png" and data.get("quality") is not None: + raise Exception("QUALITY_PNG_UNSUPPORTED") + + # Take a screenshot of a specific element or the full page + if data.get("selector"): + element = page.locator(data["selector"]) + if element.count() == 0: + raise Exception("ELEMENT_NOT_FOUND") + screenshot = element.screenshot( + type=data.get("format", "png"), + quality=data.get("quality"), + omit_background=data.get("omit_background") + ) + else: + # Validate clip dimensions if provided + if data.get("clip"): + clip = data["clip"] + if clip["x"] < 0 or clip["y"] < 0 or clip["width"] <= 0 or clip["height"] <= 0: + raise Exception("INVALID_CLIP_DIMENSIONS") + screenshot = page.screenshot( + full_page=data.get("full_page", False), + type=data.get("format", "png"), + quality=data.get("quality"), + clip=data.get("clip"), + omit_background=data.get("omit_background") + ) + + screenshot_io.write(screenshot) + screenshot_io.seek(0) + return screenshot_io + finally: + browser.close() + except Exception as e: + logger.error(f"Job {job_id}: Error taking screenshot: {str(e)}", exc_info=True) + error_message = str(e) + error_map = { + "ELEMENT_NOT_FOUND": f"The selector '{data.get('selector')}' was not found on the page. Please check your selector.", + "INVALID_CLIP_DIMENSIONS": "Clip dimensions must be positive and non-negative.", + "COOKIE_DOMAIN_MISMATCH": "A cookie domain does not match or is not a parent of the URL domain.", + "OMIT_BACKGROUND_JPEG_UNSUPPORTED": "'omit_background' is only supported for PNG format.", + "MISSING_URL_OR_HTML": "You must provide either a 'url' or 'html' field.", + "WAIT_FOR_SELECTOR_NOT_FOUND": "The selector specified in 'wait_for_selector' was not found on the page.", + "QUALITY_PNG_UNSUPPORTED": "'quality' is not supported for PNG (default format). Use JPEG format instead.", + } + error_message = error_map.get(error_message, str(e)) + return {"error": error_message} + finally: + p.stop() diff --git a/services/v1/media/convert/media_convert.py b/services/v1/media/convert/media_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..4a1816939654c4543e8c3db299ecff2d105bc183 --- /dev/null +++ b/services/v1/media/convert/media_convert.py @@ -0,0 +1,145 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +import os +import ffmpeg +import subprocess +import logging +from services.file_management import download_file +from config import LOCAL_STORAGE_PATH + +# Set up logging +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +def process_media_convert(media_url, job_id, output_format='mp4', video_codec='libx264', video_preset='medium', video_crf=23, audio_codec='aac', audio_bitrate='128k', webhook_url=None): + """ + Convert media to specified format with customizable encoding settings. + + Args: + media_url (str): URL of the media file to convert + job_id (str): Unique job identifier + output_format (str): Target format (e.g., 'mp4', 'mov', 'mp3', etc.) + video_codec (str): Video codec to use (default: 'libx264') + video_preset (str): Encoding preset for speed/quality tradeoff (default: 'medium') + video_crf (int): Constant Rate Factor for quality (0-51, default: 23) + audio_codec (str): Audio codec to use (default: 'aac') + audio_bitrate (str): Audio bitrate (default: '128k') + webhook_url (str, optional): URL to send completion webhook + + Returns: + str: Path to the converted output file + """ + input_filename = download_file(media_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input")) + output_filename = f"{job_id}.{output_format}" + output_path = os.path.join(LOCAL_STORAGE_PATH, output_filename) + + try: + # Set up the ffmpeg conversion + stream = ffmpeg.input(input_filename) + output_options = {} + + # Add format if specified + if output_format: + output_options['format'] = output_format + + # Handle audio-only formats + audio_only_formats = ['mp3', 'aac', 'wav', 'flac', 'ogg', 'opus'] + + if output_format in audio_only_formats: + # Always override the audio codec for audio-only formats + # to ensure format compatibility, regardless of what was requested + if output_format == 'mp3': + audio_codec = 'libmp3lame' + elif output_format == 'aac': + audio_codec = 'aac' + elif output_format == 'opus': + audio_codec = 'libopus' + elif output_format == 'flac': + audio_codec = 'flac' + elif output_format == 'ogg': + audio_codec = 'libvorbis' + elif output_format == 'wav': + audio_codec = 'pcm_s16le' + + # For audio-only output, we don't need video codec + output_options['acodec'] = audio_codec + + # Use the -vn flag to remove video stream + output_options['vn'] = None + else: + # For video formats, apply both video and audio codec settings + output_options['vcodec'] = video_codec + output_options['acodec'] = audio_codec + + # Apply additional video encoding options when not using copy + if video_codec != 'copy': + output_options['preset'] = video_preset + output_options['crf'] = str(video_crf) + + # Apply audio bitrate when not using copy + if audio_codec != 'copy': + output_options['b:a'] = audio_bitrate + + # Configure output + stream = ffmpeg.output(stream, output_path, **output_options) + + # Get the ffmpeg command for logging + cmd = ffmpeg.compile(stream) + logger.info(f"Running ffmpeg command: {' '.join(cmd)}") + + # Run the conversion + ffmpeg.run(stream, overwrite_output=True, capture_stdout=True, capture_stderr=True) + + # Clean up input file + os.remove(input_filename) + logger.info(f"Media conversion successful: {output_path} to format {output_format}") + + # Ensure the output file exists locally before attempting upload + if not os.path.exists(output_path): + raise FileNotFoundError(f"Output file {output_path} does not exist after conversion.") + + return output_path + + except Exception as e: + error_msg = f"Media conversion failed: {str(e)}" + logger.error(error_msg) + + # Handle ffmpeg errors specially to provide more context + if hasattr(e, 'stderr') and e.stderr: + stderr_output = e.stderr.decode('utf-8') if isinstance(e.stderr, bytes) else str(e.stderr) + detailed_error = f"FFmpeg error details: {stderr_output}" + logger.error(detailed_error) + # Raise with combined error info for better debugging + raise Exception(f"{error_msg} - {detailed_error}") + + # Clean up input file if it exists + if 'input_filename' in locals() and os.path.exists(input_filename): + try: + os.remove(input_filename) + logger.info(f"Cleaned up input file: {input_filename}") + except Exception as cleanup_error: + logger.error(f"Failed to clean up input file: {str(cleanup_error)}") + + # Clean up output file if it exists + if 'output_path' in locals() and os.path.exists(output_path): + try: + os.remove(output_path) + logger.info(f"Cleaned up output file: {output_path}") + except Exception as cleanup_error: + logger.error(f"Failed to clean up output file: {str(cleanup_error)}") + + raise \ No newline at end of file diff --git a/services/v1/media/convert/media_to_mp3.py b/services/v1/media/convert/media_to_mp3.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6488f0e39441598ed47b02d1cd55ff1014fe1c --- /dev/null +++ b/services/v1/media/convert/media_to_mp3.py @@ -0,0 +1,59 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import ffmpeg +import requests +from services.file_management import download_file +from config import LOCAL_STORAGE_PATH + +def process_media_to_mp3(media_url, job_id, bitrate='128k', sample_rate=None): + """Convert media to MP3 format with specified bitrate and sample rate.""" + input_filename = download_file(media_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input")) + output_filename = f"{job_id}.mp3" + output_path = os.path.join(LOCAL_STORAGE_PATH, output_filename) + + try: + # Build the ffmpeg command + stream = ffmpeg.input(input_filename) + output_options = {'acodec': 'libmp3lame', 'audio_bitrate': bitrate} + + # Only set sample rate if provided + if sample_rate is not None: + output_options['ar'] = sample_rate + + # Convert media file to MP3 with specified options + ( + stream + .output(output_path, **output_options) + .overwrite_output() + .run(capture_stdout=True, capture_stderr=True) + ) + os.remove(input_filename) + sample_rate_info = f" and sample rate {sample_rate}Hz" if sample_rate is not None else "" + print(f"Conversion successful: {output_path} with bitrate {bitrate}{sample_rate_info}") + + # Ensure the output file exists locally before attempting upload + if not os.path.exists(output_path): + raise FileNotFoundError(f"Output file {output_path} does not exist after conversion.") + + return output_path + + except Exception as e: + print(f"Conversion failed: {str(e)}") + raise diff --git a/services/v1/media/feedback/__init__.py b/services/v1/media/feedback/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b428a687502a4b00dcb5b935568db8b899237a6 --- /dev/null +++ b/services/v1/media/feedback/__init__.py @@ -0,0 +1 @@ +# Media feedback package \ No newline at end of file diff --git a/services/v1/media/feedback/feedback.py b/services/v1/media/feedback/feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..02c0cda610fd89f21e1b4678edf7cc87c9c0f541 --- /dev/null +++ b/services/v1/media/feedback/feedback.py @@ -0,0 +1,16 @@ +import os + +def get_feedback_path(): + """ + Returns the absolute path to the feedback static files directory + """ + # Define the path to the static feedback site files + # Keeping files isolated in the feedback module directory + base_dir = os.path.dirname(os.path.abspath(__file__)) + static_dir = os.path.join(base_dir, 'static') + + # Create the directory if it doesn't exist + if not os.path.exists(static_dir): + os.makedirs(static_dir) + + return static_dir diff --git a/services/v1/media/feedback/static/404.html b/services/v1/media/feedback/static/404.html new file mode 100644 index 0000000000000000000000000000000000000000..30962bf88549a6aa3fb77a8471f90c96b729c701 --- /dev/null +++ b/services/v1/media/feedback/static/404.html @@ -0,0 +1 @@ +404: This page could not be found.Feedback Magic v1.0

404

This page could not be found.

\ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/IKZmjEopX3I__YqoGlhxM/_buildManifest.js b/services/v1/media/feedback/static/_next/static/IKZmjEopX3I__YqoGlhxM/_buildManifest.js new file mode 100644 index 0000000000000000000000000000000000000000..9ed79f5438f09e3dc67b7286e35d895c358df009 --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/IKZmjEopX3I__YqoGlhxM/_buildManifest.js @@ -0,0 +1 @@ +self.__BUILD_MANIFEST=function(e,r,t){return{__rewrites:{afterFiles:[],beforeFiles:[],fallback:[]},__routerFilterStatic:{numItems:3,errorRate:1e-4,numBits:58,numHashes:14,bitArray:[1,1,0,e,0,e,e,r,e,e,r,e,e,e,r,e,r,r,e,r,r,r,e,r,r,r,r,r,e,r,e,e,e,e,r,e,e,r,e,e,e,r,e,r,e,r,r,e,e,e,r,r,e,e,e,r,e,e]},__routerFilterDynamic:{numItems:r,errorRate:1e-4,numBits:r,numHashes:null,bitArray:[]},"/_error":["static/chunks/pages/_error-5933f280f2bada68.js"],sortedPages:["/_app","/_error"]}}(1,0,1e-4),self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB(); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/IKZmjEopX3I__YqoGlhxM/_ssgManifest.js b/services/v1/media/feedback/static/_next/static/IKZmjEopX3I__YqoGlhxM/_ssgManifest.js new file mode 100644 index 0000000000000000000000000000000000000000..5b3ff592fd46c8736892a12864fdf3fed8775202 --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/IKZmjEopX3I__YqoGlhxM/_ssgManifest.js @@ -0,0 +1 @@ +self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB() \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/0b465130-17d112986620d03b.js b/services/v1/media/feedback/static/_next/static/chunks/0b465130-17d112986620d03b.js new file mode 100644 index 0000000000000000000000000000000000000000..125edd15be6a2186c8f40d63b7b5212ba65cd0ff --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/0b465130-17d112986620d03b.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[776],{4787:(t,e,i)=>{let r,s,n;function o(t,e,i){var r;return(e="symbol"==typeof(r=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(e,"string"))?r:r+"")in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function a(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,r)}return i}function l(t){for(var e=1;e=0)continue;i[r]=t[r]}return i}(t,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);for(r=0;r=0||({}).propertyIsEnumerable.call(t,i)&&(s[i]=t[i])}return s}function c(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}i.d(e,{Hl:()=>sw,mW:()=>sH});class u{constructor(){o(this,"browserShadowBlurConstant",1),o(this,"DPI",96),o(this,"devicePixelRatio","undefined"!=typeof window?window.devicePixelRatio:1),o(this,"perfLimitSizeTotal",2097152),o(this,"maxCacheSideLimit",4096),o(this,"minCacheSideLimit",256),o(this,"disableStyleCopyPaste",!1),o(this,"enableGLFiltering",!0),o(this,"textureSize",4096),o(this,"forceGLPutImageData",!1),o(this,"cachesBoundsOfCurve",!1),o(this,"fontPaths",{}),o(this,"NUM_FRACTION_DIGITS",4)}}let d=new class extends u{constructor(t){super(),this.configure(t)}configure(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,t)}addFonts(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.fontPaths=l(l({},this.fontPaths),t)}removeFonts(){(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).forEach(t=>{delete this.fontPaths[t]})}clearFonts(){this.fontPaths={}}restoreDefaults(t){let e=new u,i=(null==t?void 0:t.reduce((t,i)=>(t[i]=e[i],t),{}))||e;this.configure(i)}},g=function(t){for(var e=arguments.length,i=Array(e>1?e-1:0),r=1;rthis.testPrecision(e,t)),e.getExtension("WEBGL_lose_context").loseContext(),g("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}let _={},y=()=>r||(r={document:document,window:window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new v,dispose(){},copyPasteData:_}),x=()=>y().document,C=()=>y().window,b=()=>{var t;return Math.max(null!==(t=d.devicePixelRatio)&&void 0!==t?t:C().devicePixelRatio,1)},S=new class{constructor(){o(this,"charWidthsCache",{}),o(this,"boundsOfCurveCache",{})}getFontCache(t){let{fontFamily:e,fontStyle:i,fontWeight:r}=t;e=e.toLowerCase(),this.charWidthsCache[e]||(this.charWidthsCache[e]={});let s=this.charWidthsCache[e],n="".concat(i.toLowerCase(),"_").concat((r+"").toLowerCase());return s[n]||(s[n]={}),s[n]}clearFontCache(t){(t=(t||"").toLowerCase())?this.charWidthsCache[t]&&delete this.charWidthsCache[t]:this.charWidthsCache={}}limitDimsByArea(t){let{perfLimitSizeTotal:e}=d,i=Math.sqrt(e*t);return[Math.floor(i),Math.floor(e/i)]}},w="6.6.1";function T(){}let O=Math.PI/2,D=2*Math.PI,k=Math.PI/180,M=Object.freeze([1,0,0,1,0,0]),E="center",P="left",A="bottom",j="right",F="none",L=/\r?\n/,R="moving",I="scaling",B="rotating",X="rotate",Y="skewing",W="resizing",V="modifyPoly",H="changed",z="scale",G="scaleX",N="scaleY",U="skewX",q="skewY",K="fill",J="stroke",Q="modified",Z="json",$=new class{constructor(){this[Z]=new Map,this.svg=new Map}has(t){return this[Z].has(t)}getClass(t){let e=this[Z].get(t);if(!e)throw new f("No class registered for ".concat(t));return e}setClass(t,e){e?this[Z].set(e,t):(this[Z].set(t.type,t),this[Z].set(t.type.toLowerCase(),t))}getSVGClass(t){return this.svg.get(t)}setSVGClass(t,e){this.svg.set(null!=e?e:t.type.toLowerCase(),t)}},tt=new class extends Array{remove(t){let e=this.indexOf(t);e>-1&&this.splice(e,1)}cancelAll(){let t=this.splice(0);return t.forEach(t=>t.abort()),t}cancelByCanvas(t){if(!t)return[];let e=this.filter(e=>{var i;return e.target===t||"object"==typeof e.target&&(null===(i=e.target)||void 0===i?void 0:i.canvas)===t});return e.forEach(t=>t.abort()),e}cancelByTarget(t){if(!t)return[];let e=this.filter(e=>e.target===t);return e.forEach(t=>t.abort()),e}};class te{constructor(){o(this,"__eventListeners",{})}on(t,e){return(this.__eventListeners||(this.__eventListeners={}),"object"==typeof t)?(Object.entries(t).forEach(t=>{let[e,i]=t;this.on(e,i)}),()=>this.off(t)):e?(this.__eventListeners[t]||(this.__eventListeners[t]=[]),this.__eventListeners[t].push(e),()=>this.off(t,e)):()=>!1}once(t,e){if("object"==typeof t){let e=[];return Object.entries(t).forEach(t=>{let[i,r]=t;e.push(this.once(i,r))}),()=>e.forEach(t=>t())}if(e){let i=this.on(t,function(){for(var t=arguments.length,r=Array(t),s=0;s!1}_removeEventListener(t,e){if(this.__eventListeners[t]){if(e){let i=this.__eventListeners[t],r=i.indexOf(e);r>-1&&i.splice(r,1)}else this.__eventListeners[t]=[]}}off(t,e){if(this.__eventListeners){if(void 0===t)for(let t in this.__eventListeners)this._removeEventListener(t);else"object"==typeof t?Object.entries(t).forEach(t=>{let[e,i]=t;this._removeEventListener(e,i)}):this._removeEventListener(t,e)}}fire(t,e){var i;if(!this.__eventListeners)return;let r=null===(i=this.__eventListeners[t])||void 0===i?void 0:i.concat();if(r)for(let t=0;t{let i=t.indexOf(e);return -1!==i&&t.splice(i,1),t},tr=t=>{if(0===t)return 1;switch(Math.abs(t)/O){case 1:case 3:return 0;case 2:return -1}return Math.cos(t)},ts=t=>{if(0===t)return 0;let e=Math.sign(t);switch(t/O){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)};class tn{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;"object"==typeof t?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new tn(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new tn(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new tn(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new tn(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new tn(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new tn(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new tn(this.x/t.x,this.y/t.y)}scalarDivide(t){return new tn(this.x/t,this.y/t)}scalarDivideEquals(t){return this.x/=t,this.y/=t,this}eq(t){return this.x===t.x&&this.y===t.y}lt(t){return this.xt.x&&this.y>t.y}gte(t){return this.x>=t.x&&this.y>=t.y}lerp(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new tn(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){let e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}midPointFrom(t){return this.lerp(t)}min(t){return new tn(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new tn(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){let e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i}clone(){return new tn(this.x,this.y)}rotate(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:to,i=ts(t),r=tr(t),s=this.subtract(e);return new tn(s.x*r-s.y*i,s.x*i+s.y*r).add(e)}transform(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new tn(t[0]*this.x+t[2]*this.y+(e?0:t[4]),t[1]*this.x+t[3]*this.y+(e?0:t[5]))}}let to=new tn(0,0),ta=t=>!!t&&Array.isArray(t._objects);function tl(t){class e extends t{constructor(){super(...arguments),o(this,"_objects",[])}_onObjectAdded(t){}_onObjectRemoved(t){}_onStackOrderChanged(t){}add(){for(var t=arguments.length,e=Array(t),i=0;ithis._onObjectAdded(t)),r}insertAt(t){for(var e=arguments.length,i=Array(e>1?e-1:0),r=1;rthis._onObjectAdded(t)),this._objects.length}remove(){let t=this._objects,e=[];for(var i=arguments.length,r=Array(i),s=0;s{let r=t.indexOf(i);-1!==r&&(t.splice(r,1),e.push(i),this._onObjectRemoved(i))}),e}forEachObject(t){this.getObjects().forEach((e,i,r)=>t(e,i,r))}getObjects(){for(var t=arguments.length,e=Array(t),i=0;it.isType(...e))}item(t){return this._objects[t]}isEmpty(){return 0===this._objects.length}size(){return this._objects.length}contains(t,i){return!!this._objects.includes(t)||!!i&&this._objects.some(i=>i instanceof e&&i.contains(t,!0))}complexity(){return this._objects.reduce((t,e)=>t+=e.complexity?e.complexity():0,0)}sendObjectToBack(t){return!(!t||t===this._objects[0])&&(ti(this._objects,t),this._objects.unshift(t),this._onStackOrderChanged(t),!0)}bringObjectToFront(t){return!(!t||t===this._objects[this._objects.length-1])&&(ti(this._objects,t),this._objects.push(t),this._onStackOrderChanged(t),!0)}sendObjectBackwards(t,e){if(!t)return!1;let i=this._objects.indexOf(t);if(0!==i){let r=this.findNewLowerIndex(t,i,e);return ti(this._objects,t),this._objects.splice(r,0,t),this._onStackOrderChanged(t),!0}return!1}bringObjectForward(t,e){if(!t)return!1;let i=this._objects.indexOf(t);if(i!==this._objects.length-1){let r=this.findNewUpperIndex(t,i,e);return ti(this._objects,t),this._objects.splice(r,0,t),this._onStackOrderChanged(t),!0}return!1}moveObjectTo(t,e){return t!==this._objects[e]&&(ti(this._objects,t),this._objects.splice(e,0,t),this._onStackOrderChanged(t),!0)}findNewLowerIndex(t,e,i){let r;if(i){r=e;for(let i=e-1;i>=0;--i)if(t.isOverlapping(this._objects[i])){r=i;break}}else r=e-1;return r}findNewUpperIndex(t,e,i){let r;if(i){r=e;for(let i=e+1;i1&&void 0!==arguments[1]?arguments[1]:{},o=[],a=new tn(e,i),l=a.add(new tn(r,s));for(let t=this._objects.length-1;t>=0;t--){let e=this._objects[t];e.selectable&&e.visible&&(n&&e.intersectsWithRect(a,l)||e.isContainedWithinRect(a,l)||n&&e.containsPoint(a)||n&&e.containsPoint(l))&&o.push(e)}return o}}return e}class th extends te{_setOptions(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(let e in t)this.set(e,t[e])}_setObject(t){for(let e in t)this._set(e,t[e])}set(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){let e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this}get(t){return this[t]}}function tc(t){return C().requestAnimationFrame(t)}function tu(t){return C().cancelAnimationFrame(t)}let td=0,tg=()=>td++,tf=()=>{let t=x().createElement("canvas");if(!t||void 0===t.getContext)throw new f("Failed to create `canvas` element");return t},tp=()=>x().createElement("img"),tm=t=>{let e=tf();return e.width=t.width,e.height=t.height,e},tv=(t,e,i)=>t.toDataURL("image/".concat(e),i),t_=(t,e,i)=>new Promise((r,s)=>{t.toBlob(r,"image/".concat(e),i)}),ty=t=>t*k,tx=t=>t/k,tC=t=>t.every((t,e)=>t===M[e]),tb=(t,e,i)=>new tn(t).transform(e,i),tS=t=>{let e=1/(t[0]*t[3]-t[1]*t[2]),i=[e*t[3],-e*t[1],-e*t[2],e*t[0],0,0],{x:r,y:s}=new tn(t[4],t[5]).transform(i,!0);return i[4]=-r,i[5]=-s,i},tw=(t,e,i)=>[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],i?0:t[0]*e[4]+t[2]*e[5]+t[4],i?0:t[1]*e[4]+t[3]*e[5]+t[5]],tT=(t,e)=>t.reduceRight((t,i)=>i&&t?tw(i,t,e):i||t,void 0)||M.concat(),tO=t=>{let[e,i]=t;return Math.atan2(i,e)},tD=t=>{let e=tO(t),i=Math.pow(t[0],2)+Math.pow(t[1],2),r=Math.sqrt(i),s=(t[0]*t[3]-t[2]*t[1])/r,n=Math.atan2(t[0]*t[2]+t[1]*t[3],i);return{angle:tx(e),scaleX:r,scaleY:s,skewX:tx(n),skewY:0,translateX:t[4]||0,translateY:t[5]||0}},tk=function(t){return[1,0,0,1,t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0]};function tM(){let{angle:t=0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{x:e=0,y:i=0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=ty(t),s=tr(r),n=ts(r);return[s,n,-n,s,e?e-(s*e-n*i):0,i?i-(n*e+s*i):0]}let tE=function(t){return[t,0,0,arguments.length>1&&void 0!==arguments[1]?arguments[1]:t,0,0]},tP=t=>Math.tan(ty(t)),tA=t=>[1,0,tP(t),1,0,0],tj=t=>[1,tP(t),0,1,0,0],tF=t=>{let{scaleX:e=1,scaleY:i=1,flipX:r=!1,flipY:s=!1,skewX:n=0,skewY:o=0}=t,a=tE(r?-e:e,s?-i:i);return n&&(a=tw(a,tA(n),!0)),o&&(a=tw(a,tj(o),!0)),a},tL=t=>{let{translateX:e=0,translateY:i=0,angle:r=0}=t,s=tk(e,i);r&&(s=tw(s,tM({angle:r})));let n=tF(t);return tC(n)||(s=tw(s,n)),s},tR=function(t){let{signal:e,crossOrigin:i=null}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise(function(r,s){let n;if(e&&e.aborted)return s(new p("loadImage"));let o=tp();e&&(n=function(t){o.src="",s(t)},e.addEventListener("abort",n,{once:!0}));let a=function(){o.onload=o.onerror=null,n&&(null==e||e.removeEventListener("abort",n)),r(o)};t?(o.onload=a,o.onerror=function(){n&&(null==e||e.removeEventListener("abort",n)),s(new f("Error loading ".concat(o.src)))},i&&(o.crossOrigin=i),o.src=t):a()})},tI=function(t){let{signal:e,reviver:i=T}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((r,s)=>{let n=[];e&&e.addEventListener("abort",s,{once:!0}),Promise.all(t.map(t=>$.getClass(t.type).fromObject(t,{signal:e}).then(e=>(i(t,e),n.push(e),e)))).then(r).catch(t=>{n.forEach(t=>{t.dispose&&t.dispose()}),s(t)}).finally(()=>{e&&e.removeEventListener("abort",s)})})},tB=function(t){let{signal:e}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((i,r)=>{let s=[];e&&e.addEventListener("abort",r,{once:!0});let n=Object.values(t).map(t=>t&&t.type&&$.has(t.type)?tI([t],{signal:e}).then(t=>{let[e]=t;return s.push(e),e}):t),o=Object.keys(t);Promise.all(n).then(t=>t.reduce((t,e,i)=>(t[o[i]]=e,t),{})).then(i).catch(t=>{s.forEach(t=>{t.dispose&&t.dispose()}),r(t)}).finally(()=>{e&&e.removeEventListener("abort",r)})})},tX=function(t){return(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).reduce((e,i)=>(i in t&&(e[i]=t[i]),e),{})},tY=(t,e)=>Object.keys(t).reduce((i,r)=>(e(t[r],r,t)&&(i[r]=t[r]),i),{}),tW={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#0FF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000",blanchedalmond:"#FFEBCD",blue:"#00F",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#0FF",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:"#F0F",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:"#789",lightslategrey:"#789",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#0F0",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#F0F",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",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:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#639",red:"#F00",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:"#FFF",whitesmoke:"#F5F5F5",yellow:"#FF0",yellowgreen:"#9ACD32"},tV=(t,e,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t),tH=(t,e,i,r)=>{let s,n;t/=255;let o=Math.max(t,e/=255,i/=255),a=Math.min(t,e,i),l=(o+a)/2;if(o===a)s=n=0;else{let r=o-a;switch(n=l>.5?r/(2-o-a):r/(o+a),o){case t:s=(e-i)/r+6*(e0&&void 0!==arguments[0]?arguments[0]:"1";return parseFloat(t)/(t.endsWith("%")?100:1)},tG=t=>Math.min(Math.round(t),255).toString(16).toUpperCase().padStart(2,"0"),tN=t=>{let[e,i,r,s=1]=t,n=Math.round(.3*e+.59*i+.11*r);return[n,n,n,s]};class tU{constructor(t){if(o(this,"isUnrecognised",!1),t){if(t instanceof tU)this.setSource([...t._source]);else if(Array.isArray(t)){let[e,i,r,s=1]=t;this.setSource([e,i,r,s])}else this.setSource(this._tryParsingColor(t))}else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in tW&&(t=tW[t]),"transparent"===t?[255,255,255,0]:tU.sourceFromHex(t)||tU.sourceFromRgb(t)||tU.sourceFromHsl(t)||(this.isUnrecognised=!0,[0,0,0,1])}getSource(){return this._source}setSource(t){this._source=t}toRgb(){let[t,e,i]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(i,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){let[t,e,i]=tH(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(i,"%)")}toHsla(){let[t,e,i,r]=tH(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(i,"%,").concat(r,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){let[t,e,i,r]=this.getSource();return"".concat(tG(t)).concat(tG(e)).concat(tG(i)).concat(tG(Math.round(255*r)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(tN(this.getSource())),this}toBlackWhite(t){let[e,,,i]=tN(this.getSource()),r=e<(t||127)?0:255;return this.setSource([r,r,r,i]),this}overlayWith(t){t instanceof tU||(t=new tU(t));let e=this.getSource(),i=t.getSource(),[r,s,n]=e.map((t,e)=>Math.round(.5*t+.5*i[e]));return this.setSource([r,s,n,e[3]]),this}static fromRgb(t){return tU.fromRgba(t)}static fromRgba(t){return new tU(tU.sourceFromRgb(t))}static sourceFromRgb(t){let e=t.match(/^rgba?\(\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d{0,3}(?:\.\d+)?%?)\s*)?\)$/i);if(e){let[t,i,r]=e.slice(1,4).map(t=>{let e=parseFloat(t);return t.endsWith("%")?Math.round(2.55*e):e});return[t,i,r,tz(e[4])]}}static fromHsl(t){return tU.fromHsla(t)}static fromHsla(t){return new tU(tU.sourceFromHsl(t))}static sourceFromHsl(t){let e,i,r;let s=t.match(/^hsla?\(\s*([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d*(?:\.\d+)?%?)\s*)?\)$/i);if(!s)return;let n=(tU.parseAngletoDegrees(s[1])%360+360)%360/360,o=parseFloat(s[2])/100,a=parseFloat(s[3])/100;if(0===o)e=i=r=a;else{let t=a<=.5?a*(o+1):a+o-a*o,s=2*a-t;e=tV(s,t,n+1/3),i=tV(s,t,n),r=tV(s,t,n-1/3)}return[Math.round(255*e),Math.round(255*i),Math.round(255*r),tz(s[4])]}static fromHex(t){return new tU(tU.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){let e=t.slice(t.indexOf("#")+1),[i,r,s,n=255]=(e.length<=4?e.split("").map(t=>t+t):e.match(/.{2}/g)).map(t=>parseInt(t,16));return[i,r,s,n/255]}}static parseAngletoDegrees(t){let e=t.toLowerCase(),i=parseFloat(e);return e.includes("rad")?tx(i):e.includes("turn")?360*i:i}}let tq=(t,e)=>parseFloat(Number(t).toFixed(e)),tK=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=/\D{0,2}$/.exec(t),r=parseFloat(t),s=d.DPI;switch(null==i?void 0:i[0]){case"mm":return r*s/25.4;case"cm":return r*s/2.54;case"in":return r*s;case"pt":return r*s/72;case"pc":return r*s/72*12;case"em":return r*e;default:return r}},tJ=t=>{let[e,i]=t.trim().split(" "),[r,s]=e&&e!==F?[e.slice(1,4),e.slice(5,8)]:e===F?[e,e]:["Mid","Mid"];return{meetOrSlice:i||"meet",alignX:r,alignY:s}},tQ=t=>"matrix("+t.map(t=>tq(t,d.NUM_FRACTION_DIGITS)).join(" ")+")",tZ=function(t,e){let i,r,s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(e){if(e.toLive)i="url(#SVGID_".concat(e.id,")");else{let t=new tU(e),s=t.getAlpha();i=t.toRgb(),1!==s&&(r=s.toString())}}else i="none";return s?"".concat(t,": ").concat(i,"; ").concat(r?"".concat(t,"-opacity: ").concat(r,"; "):""):"".concat(t,'="').concat(i,'" ').concat(r?"".concat(t,'-opacity="').concat(r,'" '):"")},t$=t=>!!t&&void 0!==t.toLive,t0=t=>!!t&&"function"==typeof t.toObject,t1=t=>!!t&&void 0!==t.offsetX&&"source"in t,t2=t=>!!t&&"multiSelectionStacking"in t;function t5(t){let e=t&&t3(t),i=0,r=0;if(!t||!e)return{left:i,top:r};let s=t,n=e.documentElement,o=e.body||{scrollLeft:0,scrollTop:0};for(;s&&(s.parentNode||s.host)&&((s=s.parentNode||s.host)===e?(i=o.scrollLeft||n.scrollLeft||0,r=o.scrollTop||n.scrollTop||0):(i+=s.scrollLeft||0,r+=s.scrollTop||0),1!==s.nodeType||"fixed"!==s.style.position););return{left:i,top:r}}let t3=t=>t.ownerDocument||null,t4=t=>{var e;return(null===(e=t.ownerDocument)||void 0===e?void 0:e.defaultView)||null},t8=function(t,e,i){let{width:r,height:s}=i,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;t.width=r,t.height=s,n>1&&(t.setAttribute("width",(r*n).toString()),t.setAttribute("height",(s*n).toString()),e.scale(n,n))},t6=(t,e)=>{let{width:i,height:r}=e;i&&(t.style.width="number"==typeof i?"".concat(i,"px"):i),r&&(t.style.height="number"==typeof r?"".concat(r,"px"):r)};function t9(t){return void 0!==t.onselectstart&&(t.onselectstart=()=>!1),t.style.userSelect=F,t}class t7{constructor(t){o(this,"_originalCanvasStyle",void 0),o(this,"lower",void 0);let e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){let e=t&&void 0!==t.getContext?t:t&&x().getElementById(t)||tf();if(e.hasAttribute("data-fabric"))throw new f("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:i}=t,{el:r}=this.lower;r.classList.remove("lower-canvas"),r.removeAttribute("data-fabric"),r.setAttribute("width","".concat(e)),r.setAttribute("height","".concat(i)),r.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){let{el:i,ctx:r}=this.lower;t8(i,r,t,e)}setCSSDimensions(t){t6(this.lower.el,t)}calcOffset(){return function(t){var e;let i=t&&t3(t),r={left:0,top:0};if(!i)return r;let s=(null===(e=t4(t))||void 0===e?void 0:e.getComputedStyle(t,null))||{};r.left+=parseInt(s.borderLeftWidth,10)||0,r.top+=parseInt(s.borderTopWidth,10)||0,r.left+=parseInt(s.paddingLeft,10)||0,r.top+=parseInt(s.paddingTop,10)||0;let n={left:0,top:0},o=i.documentElement;void 0!==t.getBoundingClientRect&&(n=t.getBoundingClientRect());let a=t5(t);return{left:n.left+a.left-(o.clientLeft||0)+r.left,top:n.top+a.top-(o.clientTop||0)+r.top}}(this.lower.el)}dispose(){y().dispose(this.lower.el),delete this.lower}}let et={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...M]};class ee extends tl(th){get lowerCanvasEl(){var t;return null===(t=this.elements.lower)||void 0===t?void 0:t.el}get contextContainer(){var t;return null===(t=this.elements.lower)||void 0===t?void 0:t.ctx}static getDefaults(){return ee.ownDefaults}constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new t7(t)}add(){let t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,i=Array(e>1?e-1:0),r=1;r0&&this.renderOnAddRemove&&this.requestRenderAll(),s}remove(){let t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(g("warn","Canvas is trying to add an object that belongs to a different canvas.\nResulting to default behavior: removing object from previous canvas and adding to new canvas"),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?b():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}setWidth(t,e){return this.setDimensions({width:t},e)}setHeight(t,e){return this.setDimensions({height:t},e)}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:i=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e){let e=l({width:this.width,height:this.height},t);this.elements.setDimensions(e,this.getRetinaScaling()),this.hasLostContext=!0,this.width=e.width,this.height=e.height}i||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){let i=[...this.viewportTransform],r=tb(t,tS(i));i[0]=e,i[3]=e;let s=tb(r,i);i[4]+=t.x-s.x,i[5]+=t.y-s.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new tn(0,0),t)}absolutePan(t){let e=[...this.viewportTransform];return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)}relativePan(t){return this.absolutePan(new tn(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))}getElement(){return this.elements.lower.el}clearContext(t){t.clearRect(0,0,this.width,this.height)}getContext(){return this.elements.lower.ctx}clear(){this.remove(...this.getObjects()),this.backgroundImage=void 0,this.overlayImage=void 0,this.backgroundColor="",this.overlayColor="",this.clearContext(this.getContext()),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll()}renderAll(){this.cancelRequestedRender(),this.destroyed||this.renderCanvas(this.getContext(),this._objects)}renderAndReset(){this.nextRenderHandle=0,this.renderAll()}requestRenderAll(){this.nextRenderHandle||this.disposed||this.destroyed||(this.nextRenderHandle=tc(()=>this.renderAndReset()))}calcViewportBoundaries(){let t=this.width,e=this.height,i=tS(this.viewportTransform),r=tb({x:0,y:0},i),s=tb({x:t,y:e},i),n=r.min(s),o=r.max(s);return this.vptCoords={tl:n,tr:new tn(o.x,n.y),bl:new tn(n.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(tu(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;let i=this.viewportTransform,r=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),r&&(r._set("canvas",this),r.shouldCache(),r._transformDone=!0,r.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,r)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){let i=this.viewportTransform;t.save(),t.transform(...i),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let i=0,r=e.length;i!t.excludeFromExport).map(i=>this._toObject(i,t,e))},this.__serializeBgOverlay(t,e)),r?{clipPath:r}:null)}_toObject(t,e,i){let r;this.includeDefaultValues||(r=t.includeDefaultValues,t.includeDefaultValues=!1);let s=t[e](i);return this.includeDefaultValues||(t.includeDefaultValues=!!r),s}__serializeBgOverlay(t,e){let i={},r=this.backgroundImage,s=this.overlayImage,n=this.backgroundColor,o=this.overlayColor;return t$(n)?n.excludeFromExport||(i.background=n.toObject(e)):n&&(i.background=n),t$(o)?o.excludeFromExport||(i.overlay=o.toObject(e)):o&&(i.overlay=o),r&&!r.excludeFromExport&&(i.backgroundImage=this._toObject(r,t,e)),s&&!s.excludeFromExport&&(i.overlayImage=this._toObject(s,t,e)),i}toSVG(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;let i=[];return this._setSVGPreamble(i,t),this._setSVGHeader(i,t),this.clipPath&&i.push('\n')),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('\n','\n')}_setSVGHeader(t,e){let i;let r=e.width||"".concat(this.width),s=e.height||"".concat(this.height),n=d.NUM_FRACTION_DIGITS,o=e.viewBox;if(o)i='viewBox="'.concat(o.x," ").concat(o.y," ").concat(o.width," ").concat(o.height,'" ');else if(this.svgViewportTransformation){let t=this.viewportTransform;i='viewBox="'.concat(tq(-t[4]/t[0],n)," ").concat(tq(-t[5]/t[3],n)," ").concat(tq(this.width/t[0],n)," ").concat(tq(this.height/t[3],n),'" ')}else i='viewBox="0 0 '.concat(this.width," ").concat(this.height,'" ');t.push("\n',"Created with Fabric.js ",w,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")}createSVGClipPathMarkup(t){let e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(tg()),'\n').concat(e.toClipPathSVG(t.reviver),"\n")):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{let e=this["".concat(t,"Color")];if(t$(e)){let i=this["".concat(t,"Vpt")],r=this.viewportTransform,s={isType:()=>!1,width:this.width/(i?r[0]:1),height:this.height/(i?r[3]:1)};return e.toSVG(s,{additionalTransform:i?tQ(r):""})}}).join("")}createSVGFontFacesMarkup(){let t=[],e={},i=d.fontPaths;this._objects.forEach(function e(i){t.push(i),ta(i)&&i._objects.forEach(e)}),t.forEach(t=>{if(!t||"function"!=typeof t._renderText)return;let{styles:r,fontFamily:s}=t;!e[s]&&i[s]&&(e[s]=!0,r&&Object.values(r).forEach(t=>{Object.values(t).forEach(t=>{let{fontFamily:r=""}=t;!e[r]&&i[r]&&(e[r]=!0)})}))});let r=Object.keys(e).map(t=>" @font-face {\n font-family: '".concat(t,"';\n src: url('").concat(i[t],"');\n }\n")).join("");return r?' \n"):""}_setSVGObjects(t,e){this.forEachObject(i=>{i.excludeFromExport||this._setSVGObject(t,i,e)})}_setSVGObject(t,e,i){t.push(e.toSVG(i))}_setSVGBgOverlayImage(t,e,i){let r=this[e];r&&!r.excludeFromExport&&r.toSVG&&t.push(r.toSVG(i))}_setSVGBgOverlayColor(t,e){let i=this["".concat(e,"Color")];if(i){if(t$(i)){let r=i.repeat||"",s=this.width,n=this.height,o=this["".concat(e,"Vpt")]?tQ(tS(this.viewportTransform)):"";t.push('\n'))}else t.push('\n")}}loadFromJSON(t,e){let{signal:i}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)return Promise.reject(new f("`json` is undefined"));let r="string"==typeof t?JSON.parse(t):t,{objects:s=[],backgroundImage:n,background:o,overlayImage:a,overlay:l,clipPath:h}=r,c=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([tI(s,{reviver:e,signal:i}),tB({backgroundImage:n,backgroundColor:o,overlayImage:a,overlayColor:l,clipPath:h},{signal:i})]).then(t=>{let[e,i]=t;return this.clear(),this.add(...e),this.set(r),this.set(i),this.renderOnAddRemove=c,this})}clone(t){let e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){let t=tm(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{format:e="png",quality:i=1,multiplier:r=1,enableRetinaScaling:s=!1}=t,n=r*(s?this.getRetinaScaling():1);return tv(this.toCanvasElement(n,t),e,i)}toBlob(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{format:e="png",quality:i=1,multiplier:r=1,enableRetinaScaling:s=!1}=t,n=r*(s?this.getRetinaScaling():1);return t_(this.toCanvasElement(n,t),e,i)}toCanvasElement(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,{width:e,height:i,left:r,top:s,filter:n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=(e||this.width)*t,a=(i||this.height)*t,l=this.getZoom(),h=this.width,c=this.height,u=this.skipControlsDrawing,d=l*t,g=this.viewportTransform,f=[d,0,0,d,(g[4]-(r||0))*t,(g[5]-(s||0))*t],p=this.enableRetinaScaling,m=tm({width:o,height:a}),v=n?this._objects.filter(t=>n(t)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=f,this.width=o,this.height=a,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(m.getContext("2d"),v),this.viewportTransform=g,this.width=h,this.height=c,this.calcViewportBoundaries(),this.enableRetinaScaling=p,this.skipControlsDrawing=u,m}dispose(){return this.disposed||this.elements.cleanupDOM({width:this.width,height:this.height}),tt.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{let i=()=>{this.destroy(),t(!0)};i.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=i:i()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(t=>t.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#")}}o(ee,"ownDefaults",et);let ei=["touchstart","touchmove","touchend"],er=t=>{let e=t5(t.target),i=function(t){let e=t.changedTouches;return e&&e[0]?e[0]:t}(t);return new tn(i.clientX+e.left,i.clientY+e.top)},es=t=>ei.includes(t.type)||"touch"===t.pointerType,en=t=>{t.preventDefault(),t.stopPropagation()},eo=t=>{let e=0,i=0,r=0,s=0;for(let n=0,o=t.length;nr||!n)&&(r=o),(os||!n)&&(s=a),(aeh(t,tw(e,t.calcOwnMatrix())),eh=(t,e)=>{let i=tD(e),{translateX:r,translateY:s,scaleX:n,scaleY:o}=i,a=h(i,ea),l=new tn(r,s);t.flipX=!1,t.flipY=!1,Object.assign(t,a),t.set({scaleX:n,scaleY:o}),t.setPositionByOrigin(l,E,E)},ec=t=>{t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.rotate(0)},eu=t=>({scaleX:t.scaleX,scaleY:t.scaleY,skewX:t.skewX,skewY:t.skewY,angle:t.angle,left:t.left,flipX:t.flipX,flipY:t.flipY,top:t.top}),ed=(t,e,i)=>{let r=t/2,s=e/2,n=eo([new tn(-r,-s),new tn(r,-s),new tn(-r,s),new tn(r,s)].map(t=>t.transform(i)));return new tn(n.width,n.height)},eg=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;return tw(tS(arguments.length>1&&void 0!==arguments[1]?arguments[1]:M),t)},ef=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:M,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:M;return t.transform(eg(e,i))},ep=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:M,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:M;return t.transform(eg(e,i),!0)},em=(t,e,i)=>{let r=eg(e,i);return eh(t,tw(r,t.calcOwnMatrix())),r},ev=(t,e)=>{var i;let{transform:{target:r}}=e;null===(i=r.canvas)||void 0===i||i.fire("object:".concat(t),l(l({},e),{},{target:r})),r.fire(t,e)},e_={left:-.5,top:-.5,center:0,bottom:.5,right:.5},ey=t=>"string"==typeof t?e_[t]:t-.5,ex="not-allowed";function eC(t){return ey(t.originX)===ey(E)&&ey(t.originY)===ey(E)}let eb=(t,e)=>t[e],eS=(t,e,i,r)=>({e:t,transform:e,pointer:new tn(i,r)});function ew(t,e){return Math.round((t.getTotalAngle()+tx(Math.atan2(e.y,e.x))+360)%360/45)}function eT(t,e,i,r,s){var n;let{target:o,corner:a}=t,l=o.controls[a],h=(null===(n=o.canvas)||void 0===n?void 0:n.getZoom())||1,c=o.padding/h,u=function(t,e,i,r){let s=t.getRelativeCenterPoint(),n=void 0!==i&&void 0!==r?t.translateToGivenOrigin(s,E,E,i,r):new tn(t.left,t.top);return(t.angle?e.rotate(-ty(t.angle),s):e).subtract(n)}(o,new tn(r,s),e,i);return u.x>=c&&(u.x-=c),u.x<=-c&&(u.x+=c),u.y>=c&&(u.y-=c),u.y<=c&&(u.y+=c),u.x-=l.offsetX,u.y-=l.offsetY,u}let eO=(t,e,i,r)=>{let{target:s,offsetX:n,offsetY:o}=e,a=i-n,l=r-o,h=!eb(s,"lockMovementX")&&s.left!==a,c=!eb(s,"lockMovementY")&&s.top!==l;return h&&s.set(P,a),c&&s.set("top",l),(h||c)&&ev(R,eS(t,e,i,r)),h||c};class eD{getSvgStyles(t){let e=this.fillRule?this.fillRule:"nonzero",i=this.strokeWidth?this.strokeWidth:"0",r=this.strokeDashArray?this.strokeDashArray.join(" "):F,s=this.strokeDashOffset?this.strokeDashOffset:"0",n=this.strokeLineCap?this.strokeLineCap:"butt",o=this.strokeLineJoin?this.strokeLineJoin:"miter",a=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=void 0!==this.opacity?this.opacity:"1",h=this.visible?"":" visibility: hidden;",c=t?"":this.getSvgFilter(),u=tZ(K,this.fill);return[tZ(J,this.stroke),"stroke-width: ",i,"; ","stroke-dasharray: ",r,"; ","stroke-linecap: ",n,"; ","stroke-dashoffset: ",s,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",a,"; ",u,"fill-rule: ",e,"; ","opacity: ",l,";",c,h].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=t?this.calcTransformMatrix():this.calcOwnMatrix(),r='transform="'.concat(tQ(i));return"".concat(r).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:i=""}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[this.getSvgTransform(!0,i),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let e,{noStyle:i,reviver:r,withShadow:s,additionalTransform:n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=i?"":'style="'.concat(this.getSvgStyles(),'" '),a=s?'style="'.concat(this.getSvgFilter(),'" '):"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,g=this.shadow,f=[],p=t.indexOf("COMMON_PARTS");l&&(l.clipPathId="CLIPPATH_".concat(tg()),e='\n').concat(l.toClipPathSVG(r),"\n")),c&&f.push("\n"),f.push("\n");let m=[o,h,i?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[p]=m,t$(d)&&f.push(d.toSVG(this)),t$(u)&&f.push(u.toSVG(this)),g&&f.push(g.toSVG(this)),l&&f.push(e),f.push(t.join("")),f.push("\n"),c&&f.push("\n"),r?r(f.join("")):f.join("")}addPaintOrder(){return this.paintFirst!==K?' paint-order="'.concat(this.paintFirst,'" '):""}}function ek(t){return RegExp("^("+t.join("|")+")\\b","i")}let eM=String.raw(e9||(e9=c(["(?:[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?)"],["(?:[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)"]))),eE="http://www.w3.org/2000/svg",eP=RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+eM+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+eM+"))?\\s+(.*)"),eA={cx:P,x:P,r:"radius",cy:"top",y:"top",display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","letter-spacing":"charSpacing","paint-order":"paintFirst","stroke-dasharray":"strokeDashArray","stroke-dashoffset":"strokeDashOffset","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"textAnchor",opacity:"opacity","clip-path":"clipPath","clip-rule":"clipRule","vector-effect":"strokeUniform","image-rendering":"imageSmoothing"},ej="font-size",eF="clip-path",eL=ek(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),eR=ek(["symbol","image","marker","pattern","view","svg"]),eI=ek(["symbol","g","a","svg","clipPath","defs"]),eB=RegExp("^\\s*("+eM+"+)\\s*,?\\s*("+eM+"+)\\s*,?\\s*("+eM+"+)\\s*,?\\s*("+eM+"+)\\s*$"),eX=new tn(1,0),eY=new tn,eW=(t,e)=>t.rotate(e),eV=(t,e)=>new tn(e).subtract(t),eH=t=>t.distanceFrom(eY),ez=(t,e)=>Math.atan2(eq(t,e),eK(t,e)),eG=t=>ez(eX,t),eN=t=>t.eq(eY)?t:t.scalarDivide(eH(t)),eU=function(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return eN(new tn(-t.y,t.x).scalarMultiply(e?1:-1))},eq=(t,e)=>t.x*e.y-t.y*e.x,eK=(t,e)=>t.x*e.x+t.y*e.y,eJ=(t,e,i)=>{if(t.eq(e)||t.eq(i))return!0;let r=eq(e,i),s=eq(e,t),n=eq(i,t);return r>=0?s>=0&&n<=0:!(s<=0&&n>=0)},eQ="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",eZ=RegExp("(?:\\s|^)"+eQ+eQ+"("+eM+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class e${constructor(t){let e="string"==typeof t?e$.parseShadow(t):t;Object.assign(this,e$.ownDefaults,e),this.id=tg()}static parseShadow(t){let e=t.trim(),[,i=0,r=0,s=0]=(eZ.exec(e)||[]).map(t=>parseFloat(t)||0);return{color:(e.replace(eZ,"")||"rgb(0,0,0)").trim(),offsetX:i,offsetY:r,blur:s}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){let e=eW(new tn(this.offsetX,this.offsetY),ty(-t.angle)),i=new tU(this.color),r=40,s=40;return t.width&&t.height&&(r=100*tq((Math.abs(e.x)+this.blur)/t.width,d.NUM_FRACTION_DIGITS)+20,s=100*tq((Math.abs(e.y)+this.blur)/t.height,d.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'\n \n \n \n \n \n \n \n \n\n')}toObject(){let t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=e$.ownDefaults;return this.includeDefaultValues?t:tY(t,(t,i)=>t!==e[i])}static async fromObject(t){return new this(t)}}o(e$,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),o(e$,"type","shadow"),$.setClass(e$,"shadow");let e0=(t,e,i)=>Math.max(t,Math.min(e,i)),e1=["top",P,G,N,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",U,q],e2=[K,J,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],e5=(t,e,i,r)=>(tt*Math.pow(2,10*(r-=1))*Math.sin((r*s-e)*D/i),e4=(t,e,i,r)=>-i*Math.cos(t/r*O)+i+e,e8=(t,e,i,r)=>(t/=r)<1/2.75?7.5625*t*t*i+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e,e6=(t,e,i,r)=>i-e8(r-t,0,i,r)+e;var e9,e7,it,ie,ii,ir,is,io,ia=Object.freeze({__proto__:null,defaultEasing:e4,easeInBack:function(t,e,i,r){let s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return i*(t/=r)*t*((s+1)*t-s)+e},easeInBounce:e6,easeInCirc:(t,e,i,r)=>-i*(Math.sqrt(1-(t/=r)*t)-1)+e,easeInCubic:(t,e,i,r)=>i*(t/r)**3+e,easeInElastic:(t,e,i,r)=>{let s=0;if(0===t)return e;if(1==(t/=r))return e+i;s||(s=.3*r);let{a:n,s:o,p:a}=e5(i,i,s,1.70158);return-e3(n,o,a,t,r)+e},easeInExpo:(t,e,i,r)=>0===t?e:i*2**(10*(t/r-1))+e,easeInOutBack:function(t,e,i,r){let s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return(t/=r/2)<1?i/2*(t*t*((1+(s*=1.525))*t-s))+e:i/2*((t-=2)*t*((1+(s*=1.525))*t+s)+2)+e},easeInOutBounce:(t,e,i,r)=>t(t/=r/2)<1?-i/2*(Math.sqrt(1-t**2)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e,easeInOutCubic:(t,e,i,r)=>(t/=r/2)<1?i/2*t**3+e:i/2*((t-2)**3+2)+e,easeInOutElastic:(t,e,i,r)=>{let s=0;if(0===t)return e;if(2==(t/=r/2))return e+i;s||(s=.3*1.5*r);let{a:n,s:o,p:a,c:l}=e5(i,i,s,1.70158);return t<1?-.5*e3(n,o,a,t,r)+e:n*Math.pow(2,-10*(t-=1))*Math.sin((t*r-o)*D/a)*.5+l+e},easeInOutExpo:(t,e,i,r)=>0===t?e:t===r?e+i:(t/=r/2)<1?i/2*2**(10*(t-1))+e:-(i/2*(2**(-10*--t)+2))+e,easeInOutQuad:(t,e,i,r)=>(t/=r/2)<1?i/2*t**2+e:-i/2*(--t*(t-2)-1)+e,easeInOutQuart:(t,e,i,r)=>(t/=r/2)<1?i/2*t**4+e:-i/2*((t-=2)*t**3-2)+e,easeInOutQuint:(t,e,i,r)=>(t/=r/2)<1?i/2*t**5+e:i/2*((t-2)**5+2)+e,easeInOutSine:(t,e,i,r)=>-i/2*(Math.cos(Math.PI*t/r)-1)+e,easeInQuad:(t,e,i,r)=>i*(t/=r)*t+e,easeInQuart:(t,e,i,r)=>i*(t/=r)*t**3+e,easeInQuint:(t,e,i,r)=>i*(t/r)**5+e,easeInSine:(t,e,i,r)=>-i*Math.cos(t/r*O)+i+e,easeOutBack:function(t,e,i,r){let s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return i*((t=t/r-1)*t*((s+1)*t+s)+1)+e},easeOutBounce:e8,easeOutCirc:(t,e,i,r)=>i*Math.sqrt(1-(t=t/r-1)*t)+e,easeOutCubic:(t,e,i,r)=>i*((t/r-1)**3+1)+e,easeOutElastic:(t,e,i,r)=>{let s=0;if(0===t)return e;if(1==(t/=r))return e+i;s||(s=.3*r);let{a:n,s:o,p:a,c:l}=e5(i,i,s,1.70158);return n*2**(-10*t)*Math.sin((t*r-o)*D/a)+l+e},easeOutExpo:(t,e,i,r)=>t===r?e+i:-(i*(2**(-10*t/r)+1))+e,easeOutQuad:(t,e,i,r)=>-i*(t/=r)*(t-2)+e,easeOutQuart:(t,e,i,r)=>-i*((t=t/r-1)*t**3-1)+e,easeOutQuint:(t,e,i,r)=>i*((t/r-1)**5+1)+e,easeOutSine:(t,e,i,r)=>i*Math.sin(t/r*O)+e});let il=()=>!1;class ih{constructor(t){let{startValue:e,byValue:i,duration:r=500,delay:s=0,easing:n=e4,onStart:a=T,onChange:l=T,onComplete:h=T,abort:c=il,target:u}=t;o(this,"_state","pending"),o(this,"durationProgress",0),o(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=r,this.delay=s,this.easing=n,this._onStart=a,this._onChange=l,this._onComplete=h,this._abort=c,this.target=u,this.startValue=e,this.byValue=i,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return"aborted"===this._state||"completed"===this._state}start(){let t=t=>{"pending"===this._state&&(this.startTime=t||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>tc(t),this.delay):tc(t)}tick(t){let e=(t||+new Date)-this.startTime,i=Math.min(e,this.duration);this.durationProgress=i/this.duration;let{value:r,valueProgress:s}=this.calculate(i);this.value=Object.freeze(r),this.valueProgress=s,"aborted"!==this._state&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),tc(this.tick)))}register(){tt.push(this)}unregister(){tt.remove(this)}abort(){this._state="aborted",this.unregister()}}let ic=["startValue","endValue"];class iu extends ih{constructor(t){let{startValue:e=0,endValue:i=100}=t;super(l(l({},h(t,ic)),{},{startValue:e,byValue:i-e}))}calculate(t){let e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}let id=["startValue","endValue"];class ig extends ih{constructor(t){let{startValue:e=[0],endValue:i=[100]}=t;super(l(l({},h(t,id)),{},{startValue:e,byValue:i.map((t,i)=>t-e[i])}))}calculate(t){let e=this.startValue.map((e,i)=>this.easing(t,e,this.byValue[i],this.duration,i));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}let ip=["startValue","endValue","easing","onChange","onComplete","abort"],im=(t,e,i,r)=>e+i*(1-Math.cos(t/r*O)),iv=t=>t&&((e,i,r)=>t(new tU(e).toRgba(),i,r));class i_ extends ih{constructor(t){let{startValue:e,endValue:i,easing:r=im,onChange:s,onComplete:n,abort:o}=t,a=h(t,ip),c=new tU(e).getSource();super(l(l({},a),{},{startValue:c,byValue:new tU(i).getSource().map((t,e)=>t-c[e]),easing:r,onChange:iv(s),onComplete:iv(n),abort:iv(o)}))}calculate(t){let[e,i,r,s]=this.startValue.map((e,i)=>this.easing(t,e,this.byValue[i],this.duration,i)),n=[...[e,i,r].map(Math.round),e0(0,s,1)];return{value:n,valueProgress:n.map((t,e)=>0!==this.byValue[e]?Math.abs((t-this.startValue[e])/this.byValue[e]):0).find(t=>0!==t)||0}}}function iy(t){let e=Array.isArray(t.startValue)||Array.isArray(t.endValue)?new ig(t):new iu(t);return e.start(),e}function ix(t){let e=new i_(t);return e.start(),e}class iC{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some(e=>e.eq(t))}append(){for(var t=arguments.length,e=Array(t),i=0;i!this.includes(t))),this}static isPointContained(t,e,i){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(e.eq(i))return t.eq(e);if(e.x===i.x)return t.x===e.x&&(r||t.y>=Math.min(e.y,i.y)&&t.y<=Math.max(e.y,i.y));if(e.y===i.y)return t.y===e.y&&(r||t.x>=Math.min(e.x,i.x)&&t.x<=Math.max(e.x,i.x));{let s=eV(e,i),n=eV(e,t).divide(s);return r?Math.abs(n.x)===Math.abs(n.y):n.x===n.y&&n.x>=0&&n.x<=1}}static isPointInPolygon(t,e){let i=new tn(t).setX(Math.min(t.x-1,...e.map(t=>t.x))),r=0;for(let s=0;s4&&void 0!==arguments[4])||arguments[4],n=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=e.x-t.x,a=e.y-t.y,l=r.x-i.x,h=r.y-i.y,c=t.x-i.x,u=t.y-i.y,d=l*u-h*c,g=o*u-a*c,f=h*o-l*a;if(0!==f){let e=d/f,i=g/f;return(s||0<=e&&e<=1)&&(n||0<=i&&i<=1)?new iC("Intersection").append(new tn(t.x+e*o,t.y+e*a)):new iC}if(0===d||0===g){let o=s||n||iC.isPointContained(t,i,r)||iC.isPointContained(e,i,r)||iC.isPointContained(i,t,e)||iC.isPointContained(r,t,e);return new iC(o?"Coincident":void 0)}return new iC("Parallel")}static intersectSegmentLine(t,e,i,r){return iC.intersectLineLine(t,e,i,r,!1,!0)}static intersectSegmentSegment(t,e,i,r){return iC.intersectLineLine(t,e,i,r,!1,!1)}static intersectLinePolygon(t,e,i){let r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],s=new iC,n=i.length;for(let o,a,l,h=0;h0&&(s.status="Intersection"),s}static intersectSegmentPolygon(t,e,i){return iC.intersectLinePolygon(t,e,i,!1)}static intersectPolygonPolygon(t,e){let i=new iC,r=t.length,s=[];for(let n=0;n0&&s.length===t.length?new iC("Coincident"):(i.points.length>0&&(i.status="Intersection"),i)}static intersectPolygonRectangle(t,e,i){let r=e.min(i),s=e.max(i),n=new tn(s.x,r.y),o=new tn(r.x,s.y);return iC.intersectPolygonPolygon(t,[r,n,s,o])}}class ib extends th{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){let t=this.getRelativeXY();return this.group?tb(t,this.group.calcTransformMatrix()):t}setXY(t,e,i){this.group&&(t=tb(t,tS(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,i)}getRelativeXY(){return new tn(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.originX,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.originY;this.setPositionByOrigin(t,e,i)}isStrokeAccountedForInDimensions(){return!1}getCoords(){let{tl:t,tr:e,br:i,bl:r}=this.aCoords||(this.aCoords=this.calcACoords()),s=[t,e,i,r];if(this.group){let t=this.group.calcTransformMatrix();return s.map(e=>tb(e,t))}return s}intersectsWithRect(t,e){return"Intersection"===iC.intersectPolygonRectangle(this.getCoords(),t,e).status}intersectsWithObject(t){let e=iC.intersectPolygonPolygon(this.getCoords(),t.getCoords());return"Intersection"===e.status||"Coincident"===e.status||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){let{left:i,top:r,width:s,height:n}=this.getBoundingRect();return i>=t.x&&i+s<=e.x&&r>=t.y&&r+n<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return iC.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;let{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some(i=>i.x<=e.x&&i.x>=t.x&&i.y<=e.y&&i.y>=t.y)||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;let{tl:t,br:e}=this.canvas.vptCoords;return!!this.intersectsWithRect(t,e)||this.getCoords().every(i=>(i.x>=e.x||i.x<=t.x)&&(i.y>=e.y||i.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return eo(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(G,t),this._set(N,t),this.setCoords()}scaleToWidth(t){let e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){let e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return(null===(t=this.canvas)||void 0===t?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?tx(tO(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return(null===(t=this.canvas)||void 0===t?void 0:t.viewportTransform)||M.concat()}calcACoords(){let t=tM({angle:this.angle}),{x:e,y:i}=this.getRelativeCenterPoint(),r=tw(tk(e,i),t),s=this._getTransformedDimensions(),n=s.x/2,o=s.y/2;return{tl:tb({x:-n,y:-o},r),tr:tb({x:n,y:-o},r),bl:tb({x:-n,y:o},r),br:tb({x:n,y:o},r)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,ey(this.originX),ey(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;let i=this.transformMatrixKey(t),r=this.matrixCache;return r&&r.key.every((t,e)=>t===i[e])?r.value:(this.group&&(e=tw(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:i,value:e},e)}calcOwnMatrix(){let t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;let i=this.getRelativeCenterPoint(),r=tL({angle:this.angle,translateX:i.x,translateY:i.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY});return this.ownMatrixCache={key:t,value:r},r}_getNonTransformedDimensions(){return new tn(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=l({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),i=e.strokeWidth,r=i,s=0;this.strokeUniform&&(r=0,s=i);let n=e.width+r,o=e.height+r;return(0===e.skewX&&0===e.skewY?new tn(n*e.scaleX,o*e.scaleY):ed(n,o,tF(e))).scalarAdd(s)}translateToGivenOrigin(t,e,i,r,s){let n=t.x,o=t.y,a=ey(r)-ey(e),l=ey(s)-ey(i);if(a||l){let t=this._getTransformedDimensions();n+=a*t.x,o+=l*t.y}return new tn(n,o)}translateToCenterPoint(t,e,i){if(e===E&&i===E)return t;let r=this.translateToGivenOrigin(t,e,i,E,E);return this.angle?r.rotate(ty(this.angle),t):r}translateToOriginPoint(t,e,i){let r=this.translateToGivenOrigin(t,E,E,e,i);return this.angle?r.rotate(ty(this.angle),t):r}getCenterPoint(){let t=this.getRelativeCenterPoint();return this.group?tb(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new tn(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,i){let r=this.translateToCenterPoint(t,e,i),s=this.translateToOriginPoint(r,this.originX,this.originY);this.set({left:s.x,top:s.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),P,"top")}}let iS=["type"],iw=["extraParam"],iT=class t extends ib{static getDefaults(){return t.ownDefaults}get type(){let t=this.constructor.type;return"FabricObject"===t?"object":t.toLowerCase()}set type(t){g("warn","Setting type has no effect",t)}constructor(e){super(),o(this,"_cacheContext",null),Object.assign(this,t.ownDefaults),this.setOptions(e)}_createCacheCanvas(){this._cacheCanvas=tf(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){let e=t.width,i=t.height,r=d.maxCacheSideLimit,s=d.minCacheSideLimit;if(e<=r&&i<=r&&e*i<=d.perfLimitSizeTotal)return ea&&(t.zoomX/=e/a,t.width=a,t.capped=!0),i>l&&(t.zoomY/=i/l,t.height=l,t.capped=!0),t}_getCacheCanvasDimensions(){let t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),i=e.x*t.x/this.scaleX,r=e.y*t.y/this.scaleY;return{width:Math.ceil(i+2),height:Math.ceil(r+2),zoomX:t.x,zoomY:t.y,x:i,y:r}}_updateCacheCanvas(){let t=this._cacheCanvas,e=this._cacheContext,{width:i,height:r,zoomX:s,zoomY:n,x:o,y:a}=this._limitCacheSize(this._getCacheCanvasDimensions()),l=i!==t.width||r!==t.height,h=this.zoomX!==s||this.zoomY!==n;if(!t||!e)return!1;if(l||h){i!==t.width||r!==t.height?(t.width=i,t.height=r):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));let l=o/2,h=a/2;return this.cacheTranslationX=Math.round(t.width/2-l)+l,this.cacheTranslationY=Math.round(t.height/2-h)+h,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(s,n),this.zoomX=s,this.zoomY=n,!0}return!1}setOptions(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._setOptions(t)}transform(t){let e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])}getObjectScaling(){if(!this.group)return new tn(Math.abs(this.scaleX),Math.abs(this.scaleY));let t=tD(this.calcTransformMatrix());return new tn(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){let t=this.getObjectScaling();if(this.canvas){let e=this.canvas.getZoom(),i=this.getCanvasRetinaScaling();return t.scalarMultiply(e*i)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t){t.transform(r)}),e.parentClipPaths.push(t),t.absolutePositioned){let t=tS(this.calcTransformMatrix());r.transform(t[0],t[1],t[2],t[3],t[4],t[5])}return t.transform(r),t.drawObject(r,!0,e),i}_drawClipPath(t,e,i){if(!e)return;e._transformDone=!0;let r=this.createClipPathLayer(e,i);this.drawClipPathOnCache(t,e,r)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.isNotVisible())return!1;let e=this._cacheCanvas,i=this._cacheContext;return!(!e||!i||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&i&&!t&&(i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,e.width,e.height),i.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;let e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}_setOpacity(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity}_setStrokeStyles(t,e){let i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,t$(i)?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:i}=e;i&&(t$(i)?(t.fillStyle=i.toLive(t),this._applyPatternGradientTransform(t,i)):t.fillStyle=i)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&0!==e.length&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;let e=this.shadow,i=this.canvas,r=this.getCanvasRetinaScaling(),[s,,,n]=(null==i?void 0:i.viewportTransform)||M,o=s*r,a=n*r,l=e.nonScaling?new tn(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*d.browserShadowBlurConstant*(o+a)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*a*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!t$(e))return{offsetX:0,offsetY:0};let i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,s=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,s):t.transform(1,0,0,1,r,s),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:s}}_renderPaintInOrder(t){this.paintFirst===J?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){let e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var i;let r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=this.getCanvasRetinaScaling(),n=r.x/this.scaleX/s,o=r.y/this.scaleY/s,a=tm({width:Math.ceil(n),height:Math.ceil(o)}),l=a.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(n,0),l.lineTo(n,o),l.lineTo(0,o),l.closePath(),l.translate(n/2,o/2),l.scale(r.zoomX/this.scaleX/s,r.zoomY/this.scaleY/s),this._applyPatternGradientTransform(l,e),l.fillStyle=e.toLive(t),l.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(s*this.scaleX/r.zoomX,s*this.scaleY/r.zoomY),t.strokeStyle=null!==(i=l.createPattern(a,"no-repeat"))&&void 0!==i?i:"")}_findCenterFromElement(){return new tn(this.left+this.width/2,this.top+this.height/2)}clone(t){let e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){let e=this.toCanvasElement(t);return new($.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=eu(this),i=this.group,r=this.shadow,s=Math.abs,n=t.enableRetinaScaling?b():1,o=(t.multiplier||1)*n,a=t.canvasProvider||(t=>new ee(t,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&ec(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&em(this,this.getViewportTransform()),this.setCoords();let l=tf(),h=this.getBoundingRect(),c=this.shadow,u=new tn;if(c){let t=c.blur,e=c.nonScaling?new tn(1,1):this.getObjectScaling();u.x=2*Math.round(s(c.offsetX)+t)*s(e.x),u.y=2*Math.round(s(c.offsetY)+t)*s(e.y)}let d=h.width+u.x,g=h.height+u.y;l.width=Math.ceil(d),l.height=Math.ceil(g);let f=a(l);"jpeg"===t.format&&(f.backgroundColor="#fff"),this.setPositionByOrigin(new tn(f.width/2,f.height/2),E,E);let p=this.canvas;f._objects=[this],this.set("canvas",f),this.setCoords();let m=f.toCanvasElement(o||1,t);return this.set("canvas",p),this.shadow=r,i&&(this.group=i),this.set(e),this.setCoords(),f._objects=[],f.destroy(),m}toDataURL(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return tv(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t_(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=Array(t),i=0;i{let[r,s]=i;return t[r]=this._animate(r,s,e),t},{})}_animate(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=t.split("."),s=this.constructor.colorProperties.includes(r[r.length-1]),{abort:n,startValue:o,onChange:a,onComplete:h}=i,c=l(l({},i),{},{target:this,startValue:null!=o?o:r.reduce((t,e)=>t[e],this),endValue:e,abort:null==n?void 0:n.bind(this),onChange:(t,e,i)=>{r.reduce((e,i,s)=>(s===r.length-1&&(e[i]=t),e[i]),this),a&&a(t,e,i)},onComplete:(t,e,i)=>{this.setCoords(),h&&h(t,e,i)}});return s?ix(c):iy(c)}isDescendantOf(t){let{parent:e,group:i}=this;return e===t||i===t||!!e&&e.isDescendantOf(t)||!!i&&i!==e&&i.isDescendantOf(t)}getAncestors(){let t=[],e=this;do(e=e.parent)&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};let e=this.getAncestors(),i=t.getAncestors();if(0===e.length&&i.length>0&&this===i[i.length-1])return{fork:[],otherFork:[t,...i.slice(0,i.length-1)],common:[this]};for(let r,s=0;s-1&&n>o}toObject(){let e;let i=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).concat(t.customProperties,this.constructor.customProperties||[]),r=d.NUM_FRACTION_DIGITS,{clipPath:s,fill:n,stroke:o,shadow:a,strokeDashArray:h,left:c,top:u,originX:g,originY:f,width:p,height:m,strokeWidth:v,strokeLineCap:_,strokeDashOffset:y,strokeLineJoin:x,strokeUniform:C,strokeMiterLimit:b,scaleX:S,scaleY:T,angle:O,flipX:D,flipY:k,opacity:M,visible:E,backgroundColor:P,fillRule:A,paintFirst:j,globalCompositeOperation:F,skewX:L,skewY:R}=this;s&&!s.excludeFromExport&&(e=s.toObject(i.concat("inverted","absolutePositioned")));let I=t=>tq(t,r),B=l(l({},tX(this,i)),{},{type:this.constructor.type,version:w,originX:g,originY:f,left:I(c),top:I(u),width:I(p),height:I(m),fill:t0(n)?n.toObject():n,stroke:t0(o)?o.toObject():o,strokeWidth:I(v),strokeDashArray:h?h.concat():h,strokeLineCap:_,strokeDashOffset:y,strokeLineJoin:x,strokeUniform:C,strokeMiterLimit:I(b),scaleX:I(S),scaleY:I(T),angle:I(O),flipX:D,flipY:k,opacity:I(M),shadow:a?a.toObject():a,visible:E,backgroundColor:P,fillRule:A,paintFirst:j,globalCompositeOperation:F,skewX:I(L),skewY:I(R)},e?{clipPath:e}:null);return this.includeDefaultValues?B:this._removeDefaultValues(B)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){let e=this.constructor.getDefaults(),i=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return tY(t,(t,e)=>{if(e===P||"top"===e||"type"===e)return!0;let r=i[e];return t!==r&&!(Array.isArray(t)&&Array.isArray(r)&&0===t.length&&0===r.length)})}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=h(t,iS),i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{extraParam:r}=i;return tB(e,h(i,iw)).then(t=>r?(delete t[r],new this(e[r],t)):new this(t))}static fromObject(t,e){return this._fromObject(t,e)}};o(iT,"stateProperties",e1),o(iT,"cacheProperties",e2),o(iT,"ownDefaults",{top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:P,originY:"top",strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:K,fill:"rgb(0,0,0)",fillRule:"nonzero",stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,globalCompositeOperation:"source-over",backgroundColor:"",shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0}),o(iT,"type","FabricObject"),o(iT,"colorProperties",[K,J,"backgroundColor"]),o(iT,"customProperties",[]),$.setClass(iT),$.setClass(iT,"object");let iO=(t,e,i)=>(r,s,n,o)=>{let a=e(r,s,n,o);return a&&ev(t,l(l({},eS(r,s,n,o)),i)),a};function iD(t){return(e,i,r,s)=>{let{target:n,originX:o,originY:a}=i,l=n.getRelativeCenterPoint(),h=n.translateToOriginPoint(l,o,a),c=t(e,i,r,s);return n.setPositionByOrigin(h,i.originX,i.originY),c}}let ik=iO(W,iD((t,e,i,r)=>{let s=eT(e,e.originX,e.originY,i,r);if(ey(e.originX)===ey(E)||ey(e.originX)===ey(j)&&s.x<0||ey(e.originX)===ey(P)&&s.x>0){let{target:t}=e,i=t.strokeWidth/(t.strokeUniform?t.scaleX:1),r=eC(e)?2:1,n=t.width,o=Math.abs(s.x*r/t.scaleX)-i;return t.set("width",Math.max(o,1)),n!==t.width}return!1}));function iM(t,e,i,r,s){r=r||{};let n=this.sizeX||r.cornerSize||s.cornerSize,o=this.sizeY||r.cornerSize||s.cornerSize,a=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=a?J:K,h=!a&&(r.cornerStrokeColor||s.cornerStrokeColor),c,u=e,d=i;t.save(),t.fillStyle=r.cornerColor||s.cornerColor||"",t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor||"",n>o?(c=n,t.scale(1,o/n),d=i*n/o):o>n?(c=o,t.scale(n/o,1),u=e*o/n):c=n,t.beginPath(),t.arc(u,d,c/2,0,D,!1),t[l](),h&&t.stroke(),t.restore()}function iE(t,e,i,r,s){r=r||{};let n=this.sizeX||r.cornerSize||s.cornerSize,o=this.sizeY||r.cornerSize||s.cornerSize,a=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=a?J:K,h=!a&&(r.cornerStrokeColor||s.cornerStrokeColor),c=n/2,u=o/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor||"",t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor||"",t.translate(e,i);let d=s.getTotalAngle();t.rotate(ty(d)),t["".concat(l,"Rect")](-c,-u,n,o),h&&t.strokeRect(-c,-u,n,o),t.restore()}class iP{constructor(t){o(this,"visible",!0),o(this,"actionName",z),o(this,"angle",0),o(this,"x",0),o(this,"y",0),o(this,"offsetX",0),o(this,"offsetY",0),o(this,"sizeX",0),o(this,"sizeY",0),o(this,"touchSizeX",0),o(this,"touchSizeY",0),o(this,"cursorStyle","crosshair"),o(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,i,r){var s;let{tl:n,tr:o,br:a,bl:l}=r;return(null===(s=e.canvas)||void 0===s?void 0:s.getActiveObject())===e&&e.isControlVisible(t)&&iC.isPointInPolygon(i,[n,o,a,l])}getActionHandler(t,e,i){return this.actionHandler}getMouseDownHandler(t,e,i){return this.mouseDownHandler}getMouseUpHandler(t,e,i){return this.mouseUpHandler}cursorStyleHandler(t,e,i){return e.cursorStyle}getActionName(t,e,i){return e.actionName}getVisibility(t,e){var i,r;return null!==(i=null===(r=t._controlsVisibility)||void 0===r?void 0:r[e])&&void 0!==i?i:this.visible}setVisibility(t,e,i){this.visible=t}positionHandler(t,e,i,r){return new tn(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,i,r,s,n){let o=tT([tk(i,r),tM({angle:t}),tE((s?this.touchSizeX:this.sizeX)||e,(s?this.touchSizeY:this.sizeY)||e)]);return{tl:new tn(-.5,-.5).transform(o),tr:new tn(.5,-.5).transform(o),br:new tn(.5,.5).transform(o),bl:new tn(-.5,.5).transform(o)}}render(t,e,i,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?iM.call(this,t,e,i,r,s):iE.call(this,t,e,i,r,s)}}let iA=(t,e,i)=>i.lockRotation?ex:e.cursorStyle,ij=iO(B,iD((t,e,i,r)=>{let{target:s,ex:n,ey:o,theta:a,originX:l,originY:h}=e,c=s.translateToOriginPoint(s.getRelativeCenterPoint(),l,h);if(eb(s,"lockRotation"))return!1;let u=Math.atan2(o-c.y,n-c.x),d=tx(Math.atan2(r-c.y,i-c.x)-u+a);if(s.snapAngle&&s.snapAngle>0){let t=s.snapAngle,e=s.snapThreshold||t,i=Math.ceil(d/t)*t,r=Math.floor(d/t)*t;Math.abs(d-r){let r=iF(t,i);if(iL(i,0!==e.x&&0===e.y?"x":0===e.x&&0!==e.y?"y":"",r))return ex;let s=ew(i,e);return"".concat(iR[s],"-resize")};function iB(t,e,i,r){let s,n,o,a,l,h,c=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},u=e.target,d=c.by,g=iF(t,u);if(iL(u,d,g))return!1;if(e.gestureScale)n=e.scaleX*e.gestureScale,o=e.scaleY*e.gestureScale;else{if(s=eT(e,e.originX,e.originY,i,r),l="y"!==d?Math.sign(s.x||e.signX||1):1,h="x"!==d?Math.sign(s.y||e.signY||1):1,e.signX||(e.signX=l),e.signY||(e.signY=h),eb(u,"lockScalingFlip")&&(e.signX!==l||e.signY!==h))return!1;if(a=u._getTransformedDimensions(),g&&!d){let t=Math.abs(s.x)+Math.abs(s.y),{original:i}=e,r=t/(Math.abs(a.x*i.scaleX/u.scaleX)+Math.abs(a.y*i.scaleY/u.scaleY));n=i.scaleX*r,o=i.scaleY*r}else n=Math.abs(s.x*u.scaleX/a.x),o=Math.abs(s.y*u.scaleY/a.y);eC(e)&&(n*=2,o*=2),e.signX!==l&&"y"!==d&&(e.originX=.5-ey(e.originX),n*=-1,e.signX=l),e.signY!==h&&"x"!==d&&(e.originY=.5-ey(e.originY),o*=-1,e.signY=h)}let f=u.scaleX,p=u.scaleY;return d?("x"===d&&u.set(G,n),"y"===d&&u.set(N,o)):(eb(u,"lockScalingX")||u.set(G,n),eb(u,"lockScalingY")||u.set(N,o)),f!==u.scaleX||p!==u.scaleY}let iX=iO(I,iD((t,e,i,r)=>iB(t,e,i,r))),iY=iO(I,iD((t,e,i,r)=>iB(t,e,i,r,{by:"x"}))),iW=iO(I,iD((t,e,i,r)=>iB(t,e,i,r,{by:"y"}))),iV=["target","ex","ey","skewingSide"],iH={x:{counterAxis:"y",scale:G,skew:U,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:N,skew:q,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},iz=["ns","nesw","ew","nwse"],iG=(t,e,i)=>{if(0!==e.x&&eb(i,"lockSkewingY")||0!==e.y&&eb(i,"lockSkewingX"))return ex;let r=ew(i,e)%4;return"".concat(iz[r],"-resize")};function iN(t,e,i,r,s){let{target:n}=i,{counterAxis:o,origin:a,lockSkewing:c,skew:u,flip:d}=iH[t];if(eb(n,c))return!1;let{origin:g,flip:f}=iH[o],p=-Math.sign(ey(i[g])*(n[f]?-1:1))*(n[d]?-1:1),m=-(.5*((0===n[u]&&eT(i,E,E,r,s)[t]>0||n[u]>0?1:-1)*p))+.5;return iO(Y,iD((e,i,r,s)=>(function(t,e,i){let{target:r,ex:s,ey:n,skewingSide:o}=e,a=h(e,iV),{skew:l}=iH[t],c=i.subtract(new tn(s,n)).divide(new tn(r.scaleX,r.scaleY))[t],u=r[l],d=Math.tan(ty(a[l])),g=tx(Math.atan(2*c*o/Math.max("y"===t?r._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:r._getTransformedDimensions({scaleX:1,scaleY:1}).y,1)+d));r.set(l,g);let f=u!==r[l];if(f&&"y"===t){let{skewX:t,scaleX:e}=r,i=r._getTransformedDimensions({skewY:u}),s=r._getTransformedDimensions(),n=0!==t?i.x/s.x:1;1!==n&&r.set(G,n*e)}return f})(t,i,new tn(r,s))))(e,l(l({},i),{},{[a]:m,skewingSide:p}),r,s)}let iU=(t,e,i,r)=>iN("x",t,e,i,r),iq=(t,e,i,r)=>iN("y",t,e,i,r);function iK(t,e){return t[e.canvas.altActionKey]}let iJ=(t,e,i)=>{let r=iK(t,i);return 0===e.x?r?U:N:0===e.y?r?q:G:""},iQ=(t,e,i)=>iK(t,i)?iG(0,e,i):iI(t,e,i),iZ=(t,e,i,r)=>iK(t,e.target)?iq(t,e,i,r):iY(t,e,i,r),i$=(t,e,i,r)=>iK(t,e.target)?iU(t,e,i,r):iW(t,e,i,r),i0=()=>({ml:new iP({x:-.5,y:0,cursorStyleHandler:iQ,actionHandler:iZ,getActionName:iJ}),mr:new iP({x:.5,y:0,cursorStyleHandler:iQ,actionHandler:iZ,getActionName:iJ}),mb:new iP({x:0,y:.5,cursorStyleHandler:iQ,actionHandler:i$,getActionName:iJ}),mt:new iP({x:0,y:-.5,cursorStyleHandler:iQ,actionHandler:i$,getActionName:iJ}),tl:new iP({x:-.5,y:-.5,cursorStyleHandler:iI,actionHandler:iX}),tr:new iP({x:.5,y:-.5,cursorStyleHandler:iI,actionHandler:iX}),bl:new iP({x:-.5,y:.5,cursorStyleHandler:iI,actionHandler:iX}),br:new iP({x:.5,y:.5,cursorStyleHandler:iI,actionHandler:iX}),mtr:new iP({x:0,y:-.5,actionHandler:ij,cursorStyleHandler:iA,offsetY:-40,withConnection:!0,actionName:X})}),i1=()=>({mr:new iP({x:.5,y:0,actionHandler:ik,cursorStyleHandler:iQ,actionName:W}),ml:new iP({x:-.5,y:0,actionHandler:ik,cursorStyleHandler:iQ,actionName:W})}),i2=()=>l(l({},i0()),i1());class i5 extends iT{static getDefaults(){return l(l({},super.getDefaults()),i5.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),i5.ownDefaults),this.setOptions(t)}static createControls(){return{controls:i0()}}_updateCacheCanvas(){let t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){let e=t._currentTransform,i=e.target,r=e.action;if(this===i&&r&&r.startsWith(z))return!1}return super._updateCacheCanvas()}getActiveControl(){let t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;let i=Object.entries(this.oCoords);for(let r=i.length-1;r>=0;r--){let[s,n]=i[r],o=this.controls[s];if(o.shouldActivate(s,this,t,e?n.touchCorner:n.corner))return this.__corner=s,{key:s,control:o,coord:this.oCoords[s]}}}calcOCoords(){let t=this.getViewportTransform(),e=this.getCenterPoint(),i=tw(tk(e.x,e.y),tM({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)})),r=tw(t,i),s=tw(r,[1/t[0],0,0,1/t[3],0,0]),n=this.group?tD(this.calcTransformMatrix()):void 0;n&&(n.scaleX=Math.abs(n.scaleX),n.scaleY=Math.abs(n.scaleY));let o=this._calculateCurrentDimensions(n),a={};return this.forEachControl((t,e)=>{let i=t.positionHandler(o,s,this,t);a[e]=Object.assign(i,this._calcCornerCoords(t,i))}),a}_calcCornerCoords(t,e){let i=this.getTotalAngle();return{corner:t.calcCornerCoords(i,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(i,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(let e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();let e=this.getRelativeCenterPoint(),i=this._calculateCurrentDimensions(),r=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/r[0],1/r[3]),t.rotate(ty(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-i.x/2,-i.y/2,i.x,i.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=l({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},i);t.save(),t.strokeStyle=r.borderColor,this._setLineDash(t,r.borderDashArray),this.strokeBorders(t,e),r.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{hasBorders:i,hasControls:r}=this,s=l({hasBorders:i,hasControls:r},e),n=this.getViewportTransform(),o=s.hasBorders,a=s.hasControls,h=tD(tw(n,this.calcTransformMatrix()));t.save(),t.translate(h.translateX,h.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(h.angle-=180),t.rotate(ty(this.group?h.angle:this.angle)),o&&this.drawBorders(t,h,e),a&&this.drawControls(t,e),t.restore()}drawBorders(t,e,i){let r;if(i&&i.forActiveSelection||this.group){let t=ed(this.width,this.height,tF(e)),i=this.isStrokeAccountedForInDimensions()?to:(this.strokeUniform?(new tn).scalarAdd(this.canvas?this.canvas.getZoom():1):new tn(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);r=t.add(i).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else r=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,r,i)}drawControlsConnectingLines(t,e){let i=!1;t.beginPath(),this.forEachControl((r,s)=>{r.withConnection&&r.getVisibility(this,s)&&(i=!0,t.moveTo(r.x*e.x,r.y*e.y),t.lineTo(r.x*e.x+r.offsetX,r.y*e.y+r.offsetY))}),i&&t.stroke()}drawControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.save();let i=this.getCanvasRetinaScaling(),{cornerStrokeColor:r,cornerDashArray:s,cornerColor:n}=this,o=l({cornerStrokeColor:r,cornerDashArray:s,cornerColor:n},e);t.setTransform(i,0,0,i,0,0),t.strokeStyle=t.fillStyle=o.cornerColor,this.transparentCorners||(t.strokeStyle=o.cornerStrokeColor),this._setLineDash(t,o.cornerDashArray),this.forEachControl((e,i)=>{if(e.getVisibility(this,i)){let r=this.oCoords[i];e.render(t,r.x,r.y,o,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.entries(t).forEach(t=>{let[e,i]=t;return this.setControlVisible(e,i)})}clearContextTop(t){if(!this.canvas)return;let e=this.canvas.contextTop;if(!e)return;let i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e);let r=this.width+4,s=this.height+4;return e.clearRect(-r/2,-s/2,r,s),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}}function i3(t,e){return e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i)||Object.create(null))})}),t}o(i5,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class i4 extends i5{}i3(i4,[eD]),$.setClass(i4),$.setClass(i4,"object");let i8=(t,e,i,r)=>{let s=2*(r=Math.round(r))+1,{data:n}=t.getImageData(e-r,i-r,s,s);for(let t=3;t0)return!1;return!0};class i6{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new tn(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new tn(1/this.options.scaleX,1/this.options.scaleY):new tn(1,1)}createSideVector(t,e){let i=eV(t,e);return this.options.strokeUniform?i.multiply(this.scale):i}projectOrthogonally(t,e,i){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,i)))}isSkewed(){return 0!==this.options.skewX||0!==this.options.skewY}applySkew(t){let e=new tn(t);return e.y+=e.x*Math.tan(ty(this.options.skewY)),e.x+=e.y*Math.tan(ty(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}let i9=new tn;class i7 extends i6{static getOrthogonalRotationFactor(t,e){return Math.abs(e?ez(t,e):eG(t))2&&void 0!==arguments[2]?arguments[2]:this.strokeProjectionMagnitude,r=eU(this.createSideVector(t,e)),s=i7.getOrthogonalRotationFactor(r,this.bisector);return this.scaleUnitVector(r,i*s)}projectBevel(){let t=[];return(this.alpha%D==0?[this.B]:[this.B,this.C]).forEach(e=>{t.push(this.projectOrthogonally(this.A,e)),t.push(this.projectOrthogonally(this.A,e,-this.strokeProjectionMagnitude))}),t}projectMiter(){let t=[],e=1/Math.sin(Math.abs(this.alpha)/2),i=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*e),r=this.options.strokeUniform?eH(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return eH(i)/this.strokeProjectionMagnitude<=r&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){let i=[],r=new tn(i7.getOrthogonalRotationFactor(this.bisector),i7.getOrthogonalRotationFactor(new tn(this.bisector.y,this.bisector.x)));return[new tn(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r),new tn(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r)].forEach(r=>{eJ(r,t,e)&&i.push(this.A.add(r))}),i}projectRoundWithSkew(t,e){let i=[],{skewX:r,skewY:s,scaleX:n,scaleY:o,strokeUniform:a}=this.options,l=new tn(Math.tan(ty(r)),Math.tan(ty(s))),h=this.strokeProjectionMagnitude,c=a?h/o/Math.sqrt(1/o**2+1/n**2*l.y**2):h/Math.sqrt(1+l.y**2),u=new tn(Math.sqrt(Math.max(h**2-c**2,0)),c),d=a?h/Math.sqrt(1+l.x**2*(1/o)**2/(1/n+1/n*l.x*l.y)**2):h/Math.sqrt(1+l.x**2/(1+l.x*l.y)**2),g=new tn(d,Math.sqrt(Math.max(h**2-d**2,0)));return[g,g.scalarMultiply(-1),u,u.scalarMultiply(-1)].map(t=>this.applySkew(a?t.multiply(this.strokeUniformScalar):t)).forEach(r=>{eJ(r,t,e)&&i.push(this.applySkew(this.A).add(r))}),i}projectRound(){let t=[];t.push(...this.projectBevel());let e=this.alpha%D==0,i=this.applySkew(this.A),r=t[2*!e].subtract(i),s=t[+!!e].subtract(i),n=eq(r,e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)))>0,o=n?r:s,a=n?s:r;return this.isSkewed()?t.push(...this.projectRoundWithSkew(o,a)):t.push(...this.projectRoundNoSkew(o,a)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector}))}}class rt extends i6{constructor(t,e,i){super(i),this.A=new tn(t),this.T=new tn(e)}calcOrthogonalProjection(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.strokeProjectionMagnitude,r=this.createSideVector(t,e);return this.scaleUnitVector(eU(r),i)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){let t=[];if(!this.isSkewed()&&this.A.eq(this.T)){let e=new tn(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.applySkew(this.A.add(e)),this.applySkew(this.A.subtract(e)))}else t.push(...new i7(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){let t=[];if(this.A.eq(this.T)){let e=new tn(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{let e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),i=this.scaleUnitVector(eN(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),r=this.A.add(i);t.push(r.add(e),r.subtract(e))}return t.map(t=>this.applySkew(t))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t}))}}let re=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=[];if(0===t.length)return r;let s=t.reduce((t,e)=>(t[t.length-1].eq(e)||t.push(new tn(e)),t),[new tn(t[0])]);if(1===s.length)i=!0;else if(!i){let t=s[0],e=((t,e)=>{for(let i=t.length-1;i>=0;i--)if(e(t[i],i,t))return i;return -1})(s,e=>!e.eq(t));s.splice(e+1)}return s.forEach((t,s,n)=>{let o,a;0===s?(a=n[1],o=i?t:n[n.length-1]):s===n.length-1?(o=n[s-1],a=i?t:n[0]):(o=n[s-1],a=n[s+1]),i&&1===n.length?r.push(...new rt(t,t,e).project()):i&&(0===s||s===n.length-1)?r.push(...new rt(t,0===s?a:o,e).project()):r.push(...new i7(t,o,a,e).project())}),r},ri=t=>{let e={};return Object.keys(t).forEach(i=>{e[i]={},Object.keys(t[i]).forEach(r=>{e[i][r]=l({},t[i][r])})}),e},rr=t=>t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">"),rs=t=>{let e=[];for(let i,r=0;r{let i=t.charCodeAt(e);if(isNaN(i))return"";if(i<55296||i>57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";let i=t.charCodeAt(e+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";let r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1};var ro=Object.freeze({__proto__:null,capitalize:function(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return"".concat(t.charAt(0).toUpperCase()).concat(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:rr,graphemeSplit:rs});let ra=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle||t.textBackgroundColor!==e.textBackgroundColor||t.deltaY!==e.deltaY||i&&(t.overline!==e.overline||t.underline!==e.underline||t.linethrough!==e.linethrough)},rl=(t,e)=>{let i=e.split("\n"),r=[],s=-1,n={};t=ri(t);for(let e=0;e0&&(ra(n,o,!0)?r.push({start:s,end:s+1,style:o}):r[r.length-1].end++),n=o||{}}else s+=o.length,n={}}return r},rh=(t,e)=>{if(!Array.isArray(t))return ri(t);let i=e.split(L),r={},s=-1,n=0;for(let e=0;e{var e;return null!==(e=eA[t])&&void 0!==e?e:t},rg=RegExp("(".concat(eM,")"),"gi"),rf=t=>t.replace(rg," $1 ").replace(/,/gi," ").replace(/\s+/gi," "),rp="(".concat(eM,")"),rm=String.raw(e7||(e7=c(["(skewX)(",")"],["(skewX)\\(","\\)"])),rp),rv=String.raw(it||(it=c(["(skewY)(",")"],["(skewY)\\(","\\)"])),rp),r_=String.raw(ie||(ie=c(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),rp,rp,rp),ry=String.raw(ii||(ii=c(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),rp,rp),rx=String.raw(ir||(ir=c(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),rp,rp),rC=String.raw(is||(is=c(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),rp,rp,rp,rp,rp,rp),rb="(?:".concat(rC,"|").concat(rx,"|").concat(r_,"|").concat(ry,"|").concat(rm,"|").concat(rv,")"),rS=new RegExp(String.raw(io||(io=c(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),"(?:".concat(rb,"*)"))),rw=new RegExp(rb),rT=RegExp(rb,"g");function rO(t){let e=[];if(!(t=rf(t).replace(/\s*([()])\s*/gi,"$1"))||t&&!rS.test(t))return[...M];for(let i of t.matchAll(rT)){let t=rw.exec(i[0]);if(!t)continue;let r=M,[,s,...n]=t.filter(t=>!!t),[o,a,l,h,c,u]=n.map(t=>parseFloat(t));switch(s){case"translate":r=tk(o,a);break;case X:r=tM({angle:o},{x:a,y:l});break;case z:r=tE(o,a);break;case U:r=tA(o);break;case q:r=tj(o);break;case"matrix":r=[o,a,l,h,c,u]}e.push(r)}return tT(e)}function rD(t,e){t.replace(/;\s*$/,"").split(";").forEach(t=>{if(!t)return;let[i,r]=t.split(":");e[i.trim().toLowerCase()]=r.trim()})}let rk={stroke:"strokeOpacity",fill:"fillOpacity"};function rM(t,e,i){if(!t)return{};let r,s={},n=16;t.parentNode&&eI.test(t.parentNode.nodeName)&&(s=rM(t.parentElement,e,i)).fontSize&&(r=n=tK(s.fontSize));let o=l(l(l({},e.reduce((e,i)=>{let r=t.getAttribute(i);return r&&(e[i]=r),e},{})),function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};for(let r in e)(function(t,e){let i=!0,r=ru(t,e.pop());return r&&e.length&&(i=function(t,e){let i,r=!0;for(;t.parentElement&&1===t.parentElement.nodeType&&e.length;)r&&(i=e.pop()),r=ru(t=t.parentElement,i);return 0===e.length}(t,e)),r&&i&&0===e.length})(t,r.split(" "))&&(i=l(l({},i),e[r]));return i}(t,i)),function(t){let e={},i=t.getAttribute("style");return i&&("string"==typeof i?rD(i,e):function(t,e){Object.entries(t).forEach(t=>{let[i,r]=t;void 0!==r&&(e[i.toLowerCase()]=r)})}(i,e)),e}(t));o[eF]&&t.setAttribute(eF,o[eF]),o[ej]&&(r=tK(o[ej],n),o[ej]="".concat(r));let a={};for(let t in o){let e=rd(t),i=function(t,e,i,r){let s=Array.isArray(e),n,o=e;if(t!==K&&t!==J||e!==F){if("strokeUniform"===t)return"non-scaling-stroke"===e;if("strokeDashArray"===t)o=e===F?null:e.replace(/,/g," ").split(/\s+/).map(parseFloat);else if("transformMatrix"===t)o=i&&i.transformMatrix?tw(i.transformMatrix,rO(e)):rO(e);else if("visible"===t)o=e!==F&&"hidden"!==e,i&&!1===i.visible&&(o=!1);else if("opacity"===t)o=parseFloat(e),i&&void 0!==i.opacity&&(o*=i.opacity);else if("textAnchor"===t)o="start"===e?P:"end"===e?j:E;else if("charSpacing"===t)n=tK(e,r)/r*1e3;else if("paintFirst"===t){let t=e.indexOf(K),i=e.indexOf(J);o=K,(t>-1&&i>-1&&i-1)&&(o=J)}else{if("href"===t||"xlink:href"===t||"font"===t||"id"===t)return e;if("imageSmoothing"===t)return"optimizeQuality"===e;n=s?e.map(tK):tK(e,r)}}else o="";return!s&&isNaN(n)?o:n}(e,o[t],s,r);a[e]=i}a&&a.font&&function(t,e){let i=t.match(eP);if(!i)return;let r=i[1],s=i[3],n=i[4],o=i[5],a=i[6];r&&(e.fontStyle=r),s&&(e.fontWeight=isNaN(parseFloat(s))?s:parseFloat(s)),n&&(e.fontSize=tK(n)),a&&(e.fontFamily=a),o&&(e.lineHeight="normal"===o?1:o)}(a.font,a);let h=l(l({},s),a);return eI.test(t.nodeName)?h:function(t){let e=i4.getDefaults();return Object.entries(rk).forEach(i=>{let[r,s]=i;if(void 0===t[s]||""===t[r])return;if(void 0===t[r]){if(!e[r])return;t[r]=e[r]}if(0===t[r].indexOf("url("))return;let n=new tU(t[r]);t[r]=n.setAlpha(tq(n.getAlpha()*t[s],2)).toRgba()}),t}(h)}let rE=["left","top","width","height","visible"],rP=["rx","ry"];class rA extends i4{static getDefaults(){return l(l({},super.getDefaults()),rA.ownDefaults)}constructor(t){super(),Object.assign(this,rA.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){let{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){let{width:e,height:i}=this,r=-e/2,s=-i/2,n=this.rx?Math.min(this.rx,e/2):0,o=this.ry?Math.min(this.ry,i/2):0,a=0!==n||0!==o;t.beginPath(),t.moveTo(r+n,s),t.lineTo(r+e-n,s),a&&t.bezierCurveTo(r+e-.4477152502*n,s,r+e,s+.4477152502*o,r+e,s+o),t.lineTo(r+e,s+i-o),a&&t.bezierCurveTo(r+e,s+i-.4477152502*o,r+e-.4477152502*n,s+i,r+e-n,s+i),t.lineTo(r+n,s+i),a&&t.bezierCurveTo(r+.4477152502*n,s+i,r,s+i-.4477152502*o,r,s+i-o),t.lineTo(r,s+o),a&&t.bezierCurveTo(r,s+.4477152502*o,r+.4477152502*n,s,r+n,s),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...rP,...t])}_toSVG(){let{width:t,height:e,rx:i,ry:r}=this;return["\n')]}static async fromElement(t,e,i){let r=rM(t,this.ATTRIBUTE_NAMES,i),{left:s=0,top:n=0,width:o=0,height:a=0,visible:c=!0}=r,u=h(r,rE);return new this(l(l(l({},e),u),{},{left:s,top:n,width:o,height:a,visible:!!(c&&o&&a)}))}}o(rA,"type","Rect"),o(rA,"cacheProperties",[...e2,...rP]),o(rA,"ownDefaults",{rx:0,ry:0}),o(rA,"ATTRIBUTE_NAMES",[...rc,"x","y","rx","ry","width","height"]),$.setClass(rA),$.setSVGClass(rA);let rj="initialization",rF="added",rL="removed",rR="imperative",rI=(t,e)=>{let{strokeUniform:i,strokeWidth:r,width:s,height:n,group:o}=e,a=o&&o!==t?eg(o.calcTransformMatrix(),t.calcTransformMatrix()):null,l=a?e.getRelativeCenterPoint().transform(a):e.getRelativeCenterPoint(),h=!e.isStrokeAccountedForInDimensions(),c=i&&h?ep(new tn(r,r),void 0,t.calcTransformMatrix()):to,u=!i&&h?r:0,d=ed(s+u,n+u,tT([a,e.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[l.subtract(d),l.add(d)]};class rB{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:i,strategy:r}=t;return e===rj||e===rR||!!i&&r!==i}shouldLayoutClipPath(t){let{type:e,target:{clipPath:i}}=t;return e!==rj&&i&&!i.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){let{type:i,target:r}=e;if(i===rR&&e.overrides)return e.overrides;if(0===t.length)return;let{left:s,top:n,width:o,height:a}=eo(t.map(t=>rI(r,t)).reduce((t,e)=>t.concat(e),[])),l=new tn(o,a),h=new tn(s,n).add(l.scalarDivide(2));if(i===rj){let t=this.getInitialSize(e,{size:l,center:h});return{center:h,relativeCorrection:new tn(0,0),size:t}}return{center:h.transform(r.calcOwnMatrix()),size:l}}}o(rB,"type","strategy");class rX extends rB{shouldPerformLayout(t){return!0}}o(rX,"type","fit-content"),$.setClass(rX);let rY=["strategy"],rW=["target","strategy","bubbles","prevStrategy"],rV="layoutManager";class rH{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new rX;o(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){let e=l(l({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);let i=this.getLayoutResult(e);i&&this.commitLayout(e,i),this.onAfterLayout(e,i),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){let{target:i}=e;return[Q,R,W,B,I,Y,H,V,"modifyPath"].map(e=>t.on(e,t=>this.performLayout(e===Q?{type:"object_modified",trigger:e,e:t,target:i}:{type:"object_modifying",trigger:e,e:t,target:i})))}subscribe(t,e){this.unsubscribe(t,e);let i=this.attachHandlers(t,e);this._subscriptions.set(t,i)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach(t=>t()),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach(e=>this.unsubscribe(e,t))}subscribeTargets(t){t.targets.forEach(e=>this.subscribe(e,t))}onBeforeLayout(t){let{target:e,type:i}=t,{canvas:r}=e;if(i===rj||i===rF?this.subscribeTargets(t):i===rL&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),r&&r.fire("object:layout:before",{target:e,context:t}),i===rR&&t.deep){let i=h(t,rY);e.forEachObject(t=>t.layoutManager&&t.layoutManager.performLayout(l(l({},i),{},{bubbles:!1,target:t})))}}getLayoutResult(t){let{target:e,strategy:i,type:r}=t,s=i.calcLayoutResult(t,e.getObjects());if(!s)return;let n=r===rj?new tn:e.getRelativeCenterPoint(),{center:o,correction:a=new tn,relativeCorrection:l=new tn}=s,h=n.subtract(o).add(a).transform(r===rj?M:tS(e.calcOwnMatrix()),!0).add(l);return{result:s,prevCenter:n,nextCenter:o,offset:h}}commitLayout(t,e){var i,r;let{target:s}=t,{result:{size:n},nextCenter:o}=e;(s.set({width:n.x,height:n.y}),this.layoutObjects(t,e),t.type===rj)?s.set({left:null!==(i=t.x)&&void 0!==i?i:o.x+n.x*ey(s.originX),top:null!==(r=t.y)&&void 0!==r?r:o.y+n.y*ey(s.originY)}):(s.setPositionByOrigin(o,E,E),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){let{target:i}=t;i.forEachObject(r=>{r.group===i&&this.layoutObject(t,e,r)}),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,i.clipPath)}layoutObject(t,e,i){let{offset:r}=e;i.set({left:i.left+r.x,top:i.top+r.y})}onAfterLayout(t,e){let{target:i,strategy:r,bubbles:s,prevStrategy:n}=t,o=h(t,rW),{canvas:a}=i;i.fire("layout:after",{context:t,result:e}),a&&a.fire("object:layout:after",{context:t,result:e,target:i});let c=i.parent;s&&null!=c&&c.layoutManager&&((o.path||(o.path=[])).push(i),c.layoutManager.performLayout(l(l({},o),{},{target:c}))),i.set("dirty",!0)}dispose(){let{_subscriptions:t}=this;t.forEach(t=>t.forEach(t=>t())),t.clear()}toObject(){return{type:rV,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}$.setClass(rH,rV);let rz=["type","objects","layoutManager"];class rG extends rH{performLayout(){}}class rN extends tl(i4){static getDefaults(){return l(l({},super.getDefaults()),rN.ownDefaults)}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),o(this,"_activeObjects",[]),o(this,"__objectSelectionTracker",void 0),o(this,"__objectSelectionDisposer",void 0),Object.assign(this,rN.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var i;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(t=>{this.enterGroup(t,!1)}),this.layoutManager=null!==(i=e.layoutManager)&&void 0!==i?i:new rH,this.layoutManager.performLayout({type:rj,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(g("error","Group: circular object trees are not supported, this call has no effect"),!1):-1===this._objects.indexOf(t)||(g("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter((t,e,i)=>this.canEnterGroup(t)&&i.indexOf(t)===e)}add(){for(var t=arguments.length,e=Array(t),i=0;i1?e-1:0),r=1;r{i._set(t,e)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:i}=e,r=this._activeObjects;if(t)r.push(i),this._set("dirty",!0);else if(r.length>0){let t=r.indexOf(i);t>-1&&(r.splice(t,1),this._set("dirty",!0))}}_watchObject(t,e){t&&this._watchObject(!1,e),t?(e.on("selected",this.__objectSelectionTracker),e.on("deselected",this.__objectSelectionDisposer)):(e.off("selected",this.__objectSelectionTracker),e.off("deselected",this.__objectSelectionDisposer))}enterGroup(t,e){t.group&&t.group.remove(t),t._set("parent",this),this._enterGroup(t,e)}_enterGroup(t,e){e&&eh(t,tw(tS(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);let i=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();i&&(i===t||t.isDescendantOf(i))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(eh(t,tw(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);let i=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;i>-1&&this._activeObjects.splice(i,1)}shouldCache(){let t=i4.prototype.shouldCache.call(this);if(t){for(let t=0;tt.setCoords())}triggerLayout(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.layoutManager.performLayout(l({target:this,type:rR},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){let i=this.includeDefaultValues;return this._objects.filter(function(t){return!t.excludeFromExport}).map(function(r){let s=r.includeDefaultValues;r.includeDefaultValues=i;let n=r[t||"toObject"](e);return r.includeDefaultValues=s,n})}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=this.layoutManager.toObject();return l(l(l({},super.toObject(["subTargetCheck","interactive",...t])),"fit-content"!==e.strategy||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";let e=rA.prototype._toSVG.call(this),i=e.indexOf("COMMON_PARTS");e[i]='for="group" ';let r=e.join("");return t?t(r):r}_toSVG(t){let e=["\n"],i=this._createSVGBgRect(t);i&&e.push(" ",i);for(let i=0;i\n"),e}getSvgStyles(){let t=void 0!==this.opacity&&1!==this.opacity?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){let e=[],i=this._createSVGBgRect(t);i&&e.push(" ",i);for(let i=0;i{let[e,i]=t,r=new this(e,l(l(l({},n),i),{},{layoutManager:new rG}));if(s){let t=$.getClass(s.type),e=$.getClass(s.strategy);r.layoutManager=new t(new e)}else r.layoutManager=new rH;return r.layoutManager.subscribeTargets({type:rj,target:r,targets:r.getObjects()}),r.setCoords(),r})}}o(rN,"type","Group"),o(rN,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),$.setClass(rN);let rU=(t,e)=>Math.min(e.width/t.width,e.height/t.height),rq=(t,e)=>Math.max(e.width/t.width,e.height/t.height),rK="\\s*,?\\s*",rJ="".concat(rK,"(").concat(eM,")"),rQ="".concat(rJ).concat(rJ).concat(rJ).concat(rK,"([01])").concat(rK,"([01])").concat(rJ).concat(rJ),rZ={m:"l",M:"L"},r$=(t,e,i,r,s,n,o,a,l,h,c)=>{let u=tr(t),d=ts(t),g=tr(e),f=ts(e),p=i*s*g-r*n*f+o,m=r*s*g+i*n*f+a;return["C",h+l*(-i*s*d-r*n*u),c+l*(-r*s*d+i*n*u),p+l*(i*s*f+r*n*g),m+l*(r*s*f-i*n*g),p,m]},r0=(t,e,i,r)=>{let s=Math.atan2(e,t),n=Math.atan2(r,i);return n>=s?n-s:2*Math.PI-(s-n)};function r1(t,e,i,r,s,n,o,a){let l;if(d.cachesBoundsOfCurve&&(l=[...arguments].join(),S.boundsOfCurveCache[l]))return S.boundsOfCurveCache[l];let h=Math.sqrt,c=Math.abs,u=[],g=[[0,0],[0,0]],f=6*t-12*i+6*s,p=-3*t+9*i-9*s+3*o,m=3*i-3*t;for(let t=0;t<2;++t){if(t>0&&(f=6*e-12*r+6*n,p=-3*e+9*r-9*n+3*a,m=3*r-3*e),1e-12>c(p)){if(1e-12>c(f))continue;let t=-m/f;0{let[r,s,n,o,a,l,h,c]=i,u=((t,e,i,r,s,n,o)=>{if(0===i||0===r)return[];let a=0,l=0,h=0,c=Math.PI,u=o*k,d=ts(u),g=tr(u),f=.5*(-g*t-d*e),p=.5*(-g*e+d*t),m=i**2,v=r**2,_=p**2,y=f**2,x=m*v-m*_-v*y,C=Math.abs(i),b=Math.abs(r);if(x<0){let t=Math.sqrt(1-x/(m*v));C*=t,b*=t}else h=(s===n?-1:1)*Math.sqrt(x/(m*_+v*y));let S=h*C*p/b,w=-h*b*f/C,T=g*S-d*w+.5*t,O=d*S+g*w+.5*e,D=r0(1,0,(f-S)/C,(p-w)/b),M=r0((f-S)/C,(p-w)/b,(-f-S)/C,(-p-w)/b);0===n&&M>0?M-=2*c:1===n&&M<0&&(M+=2*c);let E=Math.ceil(Math.abs(M/c*2)),P=[],A=M/E,j=8/3*Math.sin(A/4)*Math.sin(A/4)/Math.sin(A/2),F=D+A;for(let t=0;t{let e=0,i=0,r=0,s=0,n=[],o,a=0,l=0;for(let h of t){let t;let c=[...h];switch(c[0]){case"l":c[1]+=e,c[2]+=i;case"L":t=["L",e=c[1],i=c[2]];break;case"h":c[1]+=e;case"H":t=["L",e=c[1],i];break;case"v":c[1]+=i;case"V":t=["L",e,i=c[1]];break;case"m":c[1]+=e,c[2]+=i;case"M":e=c[1],i=c[2],r=c[1],s=c[2],t=["M",e,i];break;case"c":c[1]+=e,c[2]+=i,c[3]+=e,c[4]+=i,c[5]+=e,c[6]+=i;case"C":a=c[3],l=c[4],e=c[5],i=c[6],t=["C",c[1],c[2],a,l,e,i];break;case"s":c[1]+=e,c[2]+=i,c[3]+=e,c[4]+=i;case"S":"C"===o?(a=2*e-a,l=2*i-l):(a=e,l=i),e=c[3],i=c[4],a=(t=["C",a,l,c[1],c[2],e,i])[3],l=t[4];break;case"q":c[1]+=e,c[2]+=i,c[3]+=e,c[4]+=i;case"Q":a=c[1],l=c[2],t=["Q",a,l,e=c[3],i=c[4]];break;case"t":c[1]+=e,c[2]+=i;case"T":"Q"===o?(a=2*e-a,l=2*i-l):(a=e,l=i),t=["Q",a,l,e=c[1],i=c[2]];break;case"a":c[6]+=e,c[7]+=i;case"A":r2(e,i,c).forEach(t=>n.push(t)),e=c[6],i=c[7];break;case"z":case"Z":e=r,i=s,t=["Z"]}t?(n.push(t),o=t[0]):o=""}return n},r3=(t,e,i,r)=>Math.sqrt((i-t)**2+(r-e)**2),r4=(t,e,i,r,s,n,o,a)=>l=>{let h=l**3,c=(t=>3*t**2*(1-t))(l),u=(t=>3*t*(1-t)**2)(l),d=(1-l)**3;return new tn(o*h+s*c+i*u+t*d,a*h+n*c+r*u+e*d)},r8=t=>t**2,r6=t=>2*t*(1-t),r9=t=>(1-t)**2,r7=(t,e,i,r,s,n,o,a)=>l=>{let h=r8(l),c=r6(l),u=r9(l);return Math.atan2(3*(u*(r-e)+c*(n-r)+h*(a-n)),3*(u*(i-t)+c*(s-i)+h*(o-s)))},st=(t,e,i,r,s,n)=>o=>{let a=r8(o),l=r6(o),h=r9(o);return new tn(s*a+i*l+t*h,n*a+r*l+e*h)},se=(t,e,i,r,s,n)=>o=>{let a=1-o;return Math.atan2(2*(a*(r-e)+o*(n-r)),2*(a*(i-t)+o*(s-i)))},si=(t,e,i)=>{let r=new tn(e,i),s=0;for(let e=1;e<=100;e+=1){let i=t(e/100);s+=r3(r.x,r.y,i.x,i.y),r=i}return s},sr=(t,e)=>{let i,r=0,s=0,n={x:t.x,y:t.y},o=l({},n),a=.01,h=0,c=t.iterator,u=t.angleFinder;for(;s1e-4;)o=c(r),h=r,(i=r3(n.x,n.y,o.x,o.y))+s>e?(r-=a,a/=2):(n=o,r+=a,s+=i);return l(l({},o),{},{angle:u(h)})},ss=t=>{let e,i,r=0,s=0,n=0,o=0,a=0,l=[];for(let h of t){let t={x:s,y:n,command:h[0],length:0};switch(h[0]){case"M":(i=t).x=o=s=h[1],i.y=a=n=h[2];break;case"L":(i=t).length=r3(s,n,h[1],h[2]),s=h[1],n=h[2];break;case"C":e=r4(s,n,h[1],h[2],h[3],h[4],h[5],h[6]),(i=t).iterator=e,i.angleFinder=r7(s,n,h[1],h[2],h[3],h[4],h[5],h[6]),i.length=si(e,s,n),s=h[5],n=h[6];break;case"Q":e=st(s,n,h[1],h[2],h[3],h[4]),(i=t).iterator=e,i.angleFinder=se(s,n,h[1],h[2],h[3],h[4]),i.length=si(e,s,n),s=h[3],n=h[4];break;case"Z":(i=t).destX=o,i.destY=a,i.length=r3(s,n,o,a),s=o,n=a}r+=i.length,l.push(i)}return l.push({length:r,x:s,y:n}),l},sn=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ss(t),r=0;for(;e-i[r].length>0&&r{var e;let i=[];for(let r of null!==(e=t.match(so))&&void 0!==e?e:[]){let t=r[0];if("z"===t||"Z"===t){i.push([t]);continue}let e=sh[t.toLowerCase()],s=[];if("a"===t||"A"===t){sa.lastIndex=0;for(let t=null;t=sa.exec(r);)s.push(...t.slice(1))}else s=r.match(sl)||[];for(let r=0;r0&&o?o:t;for(let t=0;t1&&void 0!==arguments[1]?arguments[1]:0,r=new tn(t[0]),s=new tn(t[1]),n=1,o=0,a=[],l=t.length,h=l>2;for(h&&(n=t[2].xt[e-2].x?1:r.x===t[e-2].x?0:-1,o=r.y>t[e-2].y?1:r.y===t[e-2].y?0:-1),a.push(["L",r.x+n*i,r.y+o*i]),a},sd=(t,e)=>t.map(t=>t.map((t,i)=>0===i||void 0===e?t:tq(t,e)).join(" ")).join(" ");function sg(t,e){let i=t.style;i&&e&&("string"==typeof e?i.cssText+=";"+e:Object.entries(e).forEach(t=>{let[e,r]=t;return i.setProperty(e,r)}))}let sf=(t,e)=>{let i=t._findCenterFromElement();t.transformMatrix&&((t=>{if(t.transformMatrix){let{scaleX:e,scaleY:i,angle:r,skewX:s}=tD(t.transformMatrix);t.flipX=!1,t.flipY=!1,t.set(G,e),t.set(N,i),t.angle=r,t.skewX=s,t.skewY=0}})(t),i=i.transform(t.transformMatrix)),delete t.transformMatrix,e&&(t.scaleX*=e.scaleX,t.scaleY*=e.scaleY,t.cropX=e.cropX,t.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,t.width=e.width,t.height=e.height),t.setPositionByOrigin(i,E,E)};Object.freeze({__proto__:null,addTransformToObject:el,animate:iy,animateColor:ix,applyTransformToObject:eh,calcAngleBetweenVectors:ez,calcDimensionsMatrix:tF,calcPlaneChangeMatrix:eg,calcVectorRotation:eG,cancelAnimFrame:tu,capValue:e0,composeMatrix:tL,copyCanvasElement:t=>{var e;let i=tm(t);return null===(e=i.getContext("2d"))||void 0===e||e.drawImage(t,0,0),i},cos:tr,createCanvasElement:tf,createImage:tp,createRotateMatrix:tM,createScaleMatrix:tE,createSkewXMatrix:tA,createSkewYMatrix:tj,createTranslateMatrix:tk,createVector:eV,crossProduct:eq,degreesToRadians:ty,dotProduct:eK,ease:ia,enlivenObjectEnlivables:tB,enlivenObjects:tI,findScaleToCover:rq,findScaleToFit:rU,getBoundsOfCurve:r1,getOrthonormalVector:eU,getPathSegmentsInfo:ss,getPointOnPath:sn,getPointer:er,getRandomInt:(t,e)=>Math.floor(Math.random()*(e-t+1))+t,getRegularPolygonPath:(t,e)=>{let i=2*Math.PI/t,r=-O;t%2==0&&(r+=i/2);let s=Array(t+1);for(let n=0;n{let e=["instantiated_by_use","style","id","class"];switch(t){case"linearGradient":return e.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return e.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return e.concat(["offset","stop-color","stop-opacity"])}return e},getUnitVector:eN,groupSVGElements:(t,e)=>t&&1===t.length?t[0]:new rN(t,e),hasStyleChanged:ra,invertTransform:tS,isBetweenVectors:eJ,isIdentityMatrix:tC,isTouchEvent:es,isTransparent:i8,joinPath:sd,loadImage:tR,magnitude:eH,makeBoundingBoxFromPoints:eo,makePathSimpler:r5,matrixToSVG:tQ,mergeClipPaths:(t,e)=>{var i;let r=t,s=e;r.inverted&&!s.inverted&&(r=e,s=t),em(s,null===(i=s.group)||void 0===i?void 0:i.calcTransformMatrix(),r.calcTransformMatrix());let n=r.inverted&&s.inverted;return n&&(r.inverted=s.inverted=!1),new rN([r],{clipPath:s,inverted:n})},multiplyTransformMatrices:tw,multiplyTransformMatrixArray:tT,parsePath:sc,parsePreserveAspectRatioAttribute:tJ,parseUnit:tK,pick:tX,projectStrokeOnPoints:re,qrDecompose:tD,radiansToDegrees:tx,removeFromArray:ti,removeTransformFromObject:(t,e)=>{let i=tw(tS(e),t.calcOwnMatrix());eh(t,i)},removeTransformMatrixForSvgParsing:sf,request:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e.onComplete||T,r=new(C()).XMLHttpRequest,s=e.signal,n=function(){r.abort()},o=function(){s&&s.removeEventListener("abort",n),r.onerror=r.ontimeout=T};if(s&&s.aborted)throw new p("request");return s&&s.addEventListener("abort",n,{once:!0}),r.onreadystatechange=function(){4===r.readyState&&(o(),i(r),r.onreadystatechange=T)},r.onerror=r.ontimeout=o,r.open("get",t,!0),r.send(),r},requestAnimFrame:tc,resetObjectTransform:ec,rotatePoint:(t,e,i)=>t.rotate(i,e),rotateVector:eW,saveObjectTransform:eu,sendObjectToPlane:em,sendPointToPlane:ef,sendVectorToPlane:ep,setStyle:sg,sin:ts,sizeAfterTransform:ed,string:ro,stylesFromArray:rh,stylesToArray:rl,toBlob:t_,toDataURL:tv,toFixed:tq,transformPath:(t,e,i)=>(i&&(e=tw(e,[1,0,0,1,-i.x,-i.y])),t.map(t=>{let i=[...t];for(let r=1;r1&&void 0!==arguments[1]?arguments[1]:{};super(t),o(this,"upper",void 0),o(this,"container",void 0);let{el:r}=this.lower,s=this.createUpperCanvas();this.upper={el:s,ctx:s.getContext("2d")},this.applyCanvasStyle(r,{allowTouchScrolling:e}),this.applyCanvasStyle(s,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});let n=this.createContainerElement();n.classList.add(i),r.parentNode&&r.parentNode.replaceChild(n,r),n.append(r,s),this.container=n}createUpperCanvas(){let{el:t}=this.lower,e=tf();return e.className=t.className,e.classList.remove("lower-canvas"),e.classList.add("upper-canvas"),e.setAttribute("data-fabric","top"),e.style.cssText=t.style.cssText,e.setAttribute("draggable","true"),e}createContainerElement(){let t=x().createElement("div");return t.setAttribute("data-fabric","wrapper"),sg(t,{position:"relative"}),t9(t),t}applyCanvasStyle(t,e){let{styles:i,allowTouchScrolling:r}=e;sg(t,l(l({},i),{},{"touch-action":r?"manipulation":F})),t9(t)}setDimensions(t,e){super.setDimensions(t,e);let{el:i,ctx:r}=this.upper;t8(i,r,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),t6(this.upper.el,t),t6(this.container,t)}cleanupDOM(t){let e=this.container,{el:i}=this.lower,{el:r}=this.upper;super.cleanupDOM(t),e.removeChild(r),e.removeChild(i),e.parentNode&&e.parentNode.replaceChild(i,e)}dispose(){super.dispose(),y().dispose(this.upper.el),delete this.upper,delete this.container}}class sm extends ee{constructor(){super(...arguments),o(this,"targets",[]),o(this,"_hoveredTargets",[]),o(this,"_objectsToRender",void 0),o(this,"_currentTransform",null),o(this,"_groupSelector",null),o(this,"contextTopDirty",!1)}static getDefaults(){return l(l({},super.getDefaults()),sm.ownDefaults)}get upperCanvasEl(){var t;return null===(t=this.elements.upper)||void 0===t?void 0:t.el}get contextTop(){var t;return null===(t=this.elements.upper)||void 0===t?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new sp(t,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(t){this._objectsToRender=void 0,super._onObjectAdded(t)}_onObjectRemoved(t){this._objectsToRender=void 0,t===this._activeObject&&(this.fire("before:selection:cleared",{deselected:[t]}),this._discardActiveObject(),this.fire("selection:cleared",{deselected:[t]}),t.fire("deselected",{target:t})),t===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(t)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){let t=this._activeObject;return!this.preserveObjectStacking&&t?this._objects.filter(e=>!e.group&&e!==t).concat(t):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1),this._objectsToRender||(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()}renderTop(){let t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;let e=this.getRetinaScaling(),i=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=i,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,i){let r=this.targetFindTolerance,s=this.pixelFindContext;this.clearContext(s),s.save(),s.translate(-e+r,-i+r),s.transform(...this.viewportTransform);let n=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(s),t.selectionBackgroundColor=n,s.restore();let o=Math.round(r*this.getRetinaScaling());return i8(s,o,o,o)}_isSelectionKeyPressed(t){let e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find(e=>!!e&&!0===t[e]):t[e])}_shouldClearSelection(t,e){let i=this.getActiveObjects(),r=this._activeObject;return!!(!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e)}_shouldCenterTransform(t,e,i){let r;if(t)return e===z||e===G||e===N||e===W?r=this.centeredScaling||t.centeredScaling:e===X&&(r=this.centeredRotation||t.centeredRotation),r?!i:i}_getOriginFromCorner(t,e){let i={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?i.x=j:["mr","tr","br"].includes(e)&&(i.x=P),["tl","mt","tr"].includes(e)?i.y=A:["bl","mb","br"].includes(e)&&(i.y="top")),i}_setupCurrentTransform(t,e,i){var r;let s=e.group?ef(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:n="",control:o}=e.getActiveControl()||{},a=i&&o?null===(r=o.getActionHandler(t,e,o))||void 0===r?void 0:r.bind(o):eO,h=((t,e,i,r)=>{if(!e||!t)return"drag";let s=r.controls[e];return s.getActionName(i,s,r)})(i,n,t,e),c=t[this.centeredKey],u=this._shouldCenterTransform(e,h,c)?{x:E,y:E}:this._getOriginFromCorner(e,n),d={target:e,action:h,actionHandler:a,actionPerformed:!1,corner:n,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:s.x-e.left,offsetY:s.y-e.top,originX:u.x,originY:u.y,ex:s.x,ey:s.y,lastX:s.x,lastY:s.y,theta:ty(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:c,original:l(l({},eu(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){let{x:e,y:i,deltaX:r,deltaY:s}=this._groupSelector,n=new tn(e,i).transform(this.viewportTransform),o=new tn(e+r,i+s).transform(this.viewportTransform),a=this.selectionLineWidth/2,l=Math.min(n.x,o.x),h=Math.min(n.y,o.y),c=Math.max(n.x,o.x),u=Math.max(n.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(l,h,c-l,u-h)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=a,h+=a,c-=a,u-=a,i4.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,h,c-l,u-h))}findTarget(t){if(this.skipTargetFind)return;let e=this.getViewportPoint(t),i=this._activeObject,r=this.getActiveObjects();if(this.targets=[],i&&r.length>=1){if(i.findControl(e,es(t))||r.length>1&&this.searchPossibleTargets([i],e))return i;if(i===this.searchPossibleTargets([i],e)){if(this.preserveObjectStacking){let r=this.targets;this.targets=[];let s=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&s&&s!==i?(this.targets=r,i):s}return i}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let i=t.getCoords(),r=this.getZoom(),s=t.padding/r;if(s){let[t,e,r,n]=i,o=Math.atan2(e.y-t.y,e.x-t.x),a=tr(o)*s,l=ts(o)*s,h=a+l,c=a-l;i=[new tn(t.x-c,t.y-h),new tn(e.x+h,e.y-c),new tn(r.x+c,r.y+h),new tn(n.x-h,n.y+c)]}return iC.isPointInPolygon(e,i)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,ef(e,void 0,this.viewportTransform)))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||!!t.isEditing||!this.isTargetTransparent(t,e.x,e.y))}_searchPossibleTargets(t,e){let i=t.length;for(;i--;){let r=t[i];if(this._checkTarget(r,e)){if(ta(r)&&r.subTargetCheck){let t=this._searchPossibleTargets(r._objects,e);t&&this.targets.push(t)}return r}}}searchPossibleTargets(t,e){let i=this._searchPossibleTargets(t,e);if(i&&ta(i)&&i.interactive&&this.targets[0]){let t=this.targets;for(let e=t.length-1;e>0;e--){let i=t[e];if(!ta(i)||!i.interactive)return i}return t[0]}return i}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.upperCanvasEl,r=i.getBoundingClientRect(),s=er(t),n=r.width||0,o=r.height||0;n&&o||("top"in r&&A in r&&(o=Math.abs(r.top-r.bottom)),j in r&&P in r&&(n=Math.abs(r.right-r.left))),this.calcOffset(),s.x=s.x-this._offset.left,s.y=s.y-this._offset.top,e||(s=ef(s,void 0,this.viewportTransform));let a=this.getRetinaScaling();1!==a&&(s.x/=a,s.y/=a);let l=0===n||0===o?new tn(1,1):new tn(i.width/n,i.height/o);return s.multiply(l)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=tf(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){let t=this._activeObject;return t2(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let i=!1,r=!1,s=this.getActiveObjects(),n=[],o=[];t.forEach(t=>{s.includes(t)||(i=!0,t.fire("deselected",{e:e,target:t}),o.push(t))}),s.forEach(r=>{t.includes(r)||(i=!0,r.fire("selected",{e:e,target:r}),n.push(r))}),t.length>0&&s.length>0?(r=!0,i&&this.fire("selection:updated",{e:e,selected:n,deselected:o})):s.length>0?(r=!0,this.fire("selection:created",{e:e,selected:n})):t.length>0&&(r=!0,this.fire("selection:cleared",{e:e,deselected:o})),r&&(this._objectsToRender=void 0)}setActiveObject(t,e){let i=this.getActiveObjects(),r=this._setActiveObject(t,e);return this._fireSelectionEvents(i,e),r}_setActiveObject(t,e){let i=this._activeObject;return i!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e:e})&&(this._activeObject=t,t2(t)&&i!==t&&t.set("canvas",this),t.setCoords(),!0)}_discardActiveObject(t,e){let i=this._activeObject;return!!i&&!i.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===i&&this.endCurrentTransform(t),t2(i)&&i===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){let e=this.getActiveObjects(),i=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[i]});let r=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),r}endCurrentTransform(t){let e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){let e=this._currentTransform,i=e.target,r={e:t,target:i,transform:e,action:e.action};i._scaling&&(i._scaling=!1),i.setCoords(),e.actionPerformed&&(this.fire("object:modified",r),i.fire(Q,r))}setViewportTransform(t){super.setViewportTransform(t);let e=this._activeObject;e&&e.setCoords()}destroy(){let t=this._activeObject;t2(t)&&(t.removeAll(),t.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(t){let e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,i){let r=this._realizeGroupTransformOnObject(t),s=super._toObject(t,e,i);return t.set(r),s}_realizeGroupTransformOnObject(t){let{group:e}=t;if(e&&t2(e)&&this._activeObject===e){let i=tX(t,["angle","flipX","flipY",P,G,N,U,q,"top"]);return el(t,e.calcOwnMatrix()),i}return{}}_setSVGObject(t,e,i){let r=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,i),e.set(r)}}o(sm,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class sv{constructor(t){o(this,"targets",[]),o(this,"__disposer",void 0);let e=()=>{let{hiddenTextarea:e}=t.getActiveObject()||{};e&&e.focus()},i=t.upperCanvasEl;i.addEventListener("click",e),this.__disposer=()=>i.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach(t=>{t.isEditing&&t.exitEditing()})}add(t){this.targets.push(t)}remove(t){this.unregister(t),ti(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;(null===(e=this.target)||void 0===e?void 0:e.isEditing)&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}}let s_=["target","oldTarget","fireCanvas","e"],sy={passive:!1},sx=(t,e)=>{let i=t.getViewportPoint(e),r=t.getScenePoint(e);return{viewportPoint:i,scenePoint:r,pointer:i,absolutePointer:r}},sC=function(t){for(var e=arguments.length,i=Array(e>1?e-1:0),r=1;r1?e-1:0),r=1;r1&&void 0!==arguments[1]?arguments[1]:{}),o(this,"_isClick",void 0),o(this,"textEditingManager",new sv(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onDoubleClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(t=>{this[t]=this[t].bind(this)}),this.addOrRemove(sC,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){let i=this.upperCanvasEl,r=this._getEventPrefix();t(t4(i),"resize",this._onResize),t(i,r+"down",this._onMouseDown),t(i,"".concat(r,"move"),this._onMouseMove,sy),t(i,"".concat(r,"out"),this._onMouseOut),t(i,"".concat(r,"enter"),this._onMouseEnter),t(i,"wheel",this._onMouseWheel),t(i,"contextmenu",this._onContextMenu),t(i,"dblclick",this._onDoubleClick),t(i,"dragstart",this._onDragStart),t(i,"dragend",this._onDragEnd),t(i,"dragover",this._onDragOver),t(i,"dragenter",this._onDragEnter),t(i,"dragleave",this._onDragLeave),t(i,"drop",this._onDrop),this.enablePointerEvents||t(i,"touchstart",this._onTouchStart,sy)}removeListeners(){this.addOrRemove(sb,"remove");let t=this._getEventPrefix(),e=t3(this.upperCanvasEl);sb(e,"".concat(t,"up"),this._onMouseUp),sb(e,"touchend",this._onTouchEnd,sy),sb(e,"".concat(t,"move"),this._onMouseMove,sy),sb(e,"touchmove",this._onMouseMove,sy),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){let e=this._hoveredTarget,i=l({e:t},sx(this,t));this.fire("mouse:out",l(l({},i),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",l({},i)),this._hoveredTargets.forEach(t=>{this.fire("mouse:out",l(l({},i),{},{target:t})),t&&t.fire("mouseout",l({},i))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",l({e:t},sx(this,t))),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;let e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;let i={e:t,target:e};return this.fire("dragstart",i),e.fire("dragstart",i),void sC(this.upperCanvasEl,"drag",this._onDragProgress)}en(t)}_renderDragEffects(t,e,i){let r=!1,s=this._dropTarget;s&&s!==e&&s!==i&&(s.clearContextTop(),r=!0),null==e||e.clearContextTop(),i!==e&&(null==i||i.clearContextTop());let n=this.contextTop;n.save(),n.transform(...this.viewportTransform),e&&(n.save(),e.transform(n),e.renderDragSourceEffect(t),n.restore(),r=!0),i&&(n.save(),i.transform(n),i.renderDropTargetEffect(t),n.restore(),r=!0),n.restore(),r&&(this.contextTopDirty=!0)}_onDragEnd(t){let e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==F,i=e?this._activeObject:void 0,r={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:i};sb(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",r),this._dragSource&&this._dragSource.fire("dragend",r),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){let e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){let e;let i="dragover",{target:r,targets:s}=this.findDragTargets(t),n=this._dragSource,o={e:t,target:r,subTargets:s,dragSource:n,canDrop:!1,dropTarget:void 0};this.fire(i,o),this._fireEnterLeaveEvents(r,o),r&&(r.canDrop(t)&&(e=r),r.fire(i,o));for(let r=0;r0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;let e=this._getEventPrefix(),i=t3(this.upperCanvasEl);sb(i,"touchend",this._onTouchEnd,sy),sb(i,"touchmove",this._onMouseMove,sy),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{sC(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();let e=this.upperCanvasEl,i=this._getEventPrefix();if(this._isMainEvent(t)){let t=t3(this.upperCanvasEl);sb(t,"".concat(i,"up"),this._onMouseUp),sb(t,"".concat(i,"move"),this._onMouseMove,sy),sC(e,"".concat(i,"move"),this._onMouseMove,sy)}}_onMouseMove(t){let e=this.getActiveObject();this.allowTouchScrolling||e&&e.shouldStartDragging(t)||!t.preventDefault||t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){let e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");let i=this._currentTransform,r=this._isClick,s=this._target,{button:n}=t;if(n)return(this.fireMiddleClick&&1===n||this.fireRightClick&&2===n)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o,a,l=!1;if(i&&(this._finalizeCurrentTransform(t),l=i.actionPerformed),!r){let e=s===this._activeObject;this.handleSelection(t),l||(l=this._shouldRender(s)||!e&&s===this._activeObject)}if(s){let{key:e,control:r}=s.findControl(this.getViewportPoint(t),es(t))||{};if(a=e,s.selectable&&s!==this._activeObject&&"up"===s.activeOn)this.setActiveObject(s,t),l=!0;else if(r){let e=r.getMouseUpHandler(t,s,r);e&&(o=this.getScenePoint(t),e.call(r,t,i,o.x,o.y))}s.isMoving=!1}if(i&&(i.target!==s||i.corner!==a)){let e=i.target&&i.target.controls[i.corner],r=e&&e.getMouseUpHandler(t,i.target,e);o=o||this.getScenePoint(t),r&&r.call(e,t,i,o.x,o.y)}this._setCursorFromEvent(t,s),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,s&&(s.__corner=void 0),l?this.requestRenderAll():r||null!==(e=this._activeObject)&&void 0!==e&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){let{target:i,subTargets:r=[]}=e;this.fire(t,e),i&&i.fire(t,e);for(let s=0;s{i=t.hoverCursor||i}),this.setCursor(i)}handleMultiSelection(t,e){let i=this._activeObject,r=t2(i);if(i&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(i!==e||r)&&(r||!e.isDescendantOf(i)&&!i.isDescendantOf(e))&&!e.onSelect({e:t})&&!i.getActiveControl()){if(r){let r=i.getObjects();if(e===i){let i=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(r,i)||this.searchPossibleTargets(this._objects,i))||!e.selectable)return!1}e.group===i?(i.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],1===i.size()&&this._setActiveObject(i.item(0),t)):(i.multiSelectAdd(e),this._hoveredTarget=i,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(r,t)}else{i.isEditing&&i.exitEditing();let r=new($.getClass("ActiveSelection"))([],{canvas:this});r.multiSelectAdd(i,e),this._hoveredTarget=r,this._setActiveObject(r,t),this._fireSelectionEvents([i],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;let{x:e,y:i,deltaX:r,deltaY:s}=this._groupSelector,n=new tn(e,i),o=n.add(new tn(r,s)),a=n.min(o),l=n.max(o).subtract(a),h=this.collectObjects({left:a.x,top:a.y,width:l.x,height:l.y},{includeIntersecting:!this.selectionFullyContained}),c=n.eq(o)?h[0]?[h[0]]:[]:h.length>1?h.filter(e=>!e.onSelect({e:t})).reverse():h;if(1===c.length)this.setActiveObject(c[0],t);else if(c.length>1){let e=$.getClass("ActiveSelection");this.setActiveObject(new e(c,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}let sT={x1:0,y1:0,x2:0,y2:0},sO=l(l({},sT),{},{r1:0,r2:0}),sD=(t,e)=>isNaN(t)&&"number"==typeof e?e:t,sk=/^(\d+\.\d+)%|(\d+)%$/;function sM(t){return t&&sk.test(t)}function sE(t,e){return e0(0,sD("number"==typeof t?t:"string"==typeof t?parseFloat(t)/(sM(t)?100:1):NaN,e),1)}let sP=/\s*;\s*/,sA=/\s*:\s*/;function sj(t){return"linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?"linear":"radial"}function sF(t){return"userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage"}function sL(t,e){return t.getAttribute(e)}class sR{constructor(t){let{type:e="linear",gradientUnits:i="pixels",coords:r={},colorStops:s=[],offsetX:n=0,offsetY:o=0,gradientTransform:a,id:h}=t||{};Object.assign(this,{type:e,gradientUnits:i,coords:l(l({},"radial"===e?sO:sT),r),colorStops:s,offsetX:n,offsetY:o,gradientTransform:a,id:h?"".concat(h,"_").concat(tg()):tg()})}addColorStop(t){for(let e in t){let i=new tU(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this}toObject(t){return l(l({},tX(this,t)),{},{type:this.type,coords:l({},this.coords),colorStops:this.colorStops.map(t=>l({},t)),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=[],r=this.gradientTransform?this.gradientTransform.concat():M.concat(),s="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox",n=this.colorStops.map(t=>l({},t)).sort((t,e)=>t.offset-e.offset),o=-this.offsetX,a=-this.offsetY;"objectBoundingBox"===s?(o/=t.width,a/=t.height):(o+=t.width/2,a+=t.height/2),t&&"function"==typeof t._renderPathCommands&&"percentage"!==this.gradientUnits&&(o-=t.pathOffset.x,a-=t.pathOffset.y),r[4]-=o,r[5]-=a;let h=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(s,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(tQ(r),'"'),""].join(" ");if("linear"===this.type){let{x1:t,y1:e,x2:r,y2:s}=this.coords;i.push("\n')}else if("radial"===this.type){let{x1:t,y1:e,x2:r,y2:s,r1:o,r2:a}=this.coords,l=o>a;i.push("\n'),l&&(n.reverse(),n.forEach(t=>{t.offset=1-t.offset}));let c=Math.min(o,a);if(c>0){let t=c/Math.max(o,a);n.forEach(e=>{e.offset+=t*(1-e.offset)})}}return n.forEach(t=>{let{color:e,offset:r,opacity:s}=t;i.push("\n')}),i.push("linear"===this.type?"":"","\n"),i.join("")}toLive(t){let{x1:e,y1:i,x2:r,y2:s,r1:n,r2:o}=this.coords,a="linear"===this.type?t.createLinearGradient(e,i,r,s):t.createRadialGradient(e,i,n,r,s,o);return this.colorStops.forEach(t=>{let{color:e,opacity:i,offset:r}=t;a.addColorStop(r,void 0!==i?new tU(e).setAlpha(i).toRgba():e)}),a}static async fromObject(t){let{colorStops:e,gradientTransform:i}=t;return new this(l(l({},t),{},{colorStops:e?e.map(t=>l({},t)):void 0,gradientTransform:i?[...i]:void 0}))}static fromElement(t,e,i){var r;let s=sF(t),n=e._findCenterFromElement();return new this(l({id:t.getAttribute("id")||void 0,type:sj(t),coords:(r={width:i.viewBoxWidth||i.width,height:i.viewBoxHeight||i.height},function(t,e){let i,{width:r,height:s,gradientUnits:n}=e;return Object.keys(t).reduce((e,o)=>{let a=t[o];return"Infinity"===a?i=1:"-Infinity"===a?i=0:(i="string"==typeof a?parseFloat(a):a,"string"==typeof a&&sM(a)&&(i*=.01,"pixels"===n&&("x1"!==o&&"x2"!==o&&"r2"!==o||(i*=r),"y1"!==o&&"y2"!==o||(i*=s)))),e[o]=i,e},{})}("linear"===sj(t)?{x1:sL(t,"x1")||0,y1:sL(t,"y1")||0,x2:sL(t,"x2")||"100%",y2:sL(t,"y2")||0}:{x1:sL(t,"fx")||sL(t,"cx")||"50%",y1:sL(t,"fy")||sL(t,"cy")||"50%",r1:0,x2:sL(t,"cx")||"50%",y2:sL(t,"cy")||"50%",r2:sL(t,"r")||"50%"},l(l({},r),{},{gradientUnits:sF(t)}))),colorStops:function(t,e){let i=[],r=t.getElementsByTagName("stop"),s=sE(e,1);for(let t=r.length;t--;)i.push(function(t,e){let i,r;let s=t.getAttribute("style");if(s){let t=s.split(sP);""===t[t.length-1]&&t.pop();for(let e=t.length;e--;){let[s,n]=t[e].split(sA).map(t=>t.trim());"stop-color"===s?i=n:"stop-opacity"===s&&(r=n)}}let n=new tU(i||t.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:sE(t.getAttribute("offset"),0),color:n.toRgb(),opacity:sD(parseFloat(r||t.getAttribute("stop-opacity")||""),1)*n.getAlpha()*e}}(r[t],s));return i}(t,i.opacity),gradientUnits:s,gradientTransform:rO(t.getAttribute("gradientTransform")||"")},"pixels"===s?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}o(sR,"type","Gradient"),$.setClass(sR,"gradient"),$.setClass(sR,"linear"),$.setClass(sR,"radial");let sI=["type","source","patternTransform"];class sB{get type(){return"pattern"}set type(t){g("warn","Setting type has no effect",t)}constructor(t){o(this,"repeat","repeat"),o(this,"offsetX",0),o(this,"offsetY",0),o(this,"crossOrigin",""),this.id=tg(),Object.assign(this,t)}isImageSource(){return!!this.source&&"string"==typeof this.source.src}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&0!==this.source.naturalWidth&&0!==this.source.naturalHeight)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],{repeat:e,crossOrigin:i}=this;return l(l({},tX(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:i,offsetX:tq(this.offsetX,d.NUM_FRACTION_DIGITS),offsetY:tq(this.offsetY,d.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null})}toSVG(t){let{width:e,height:i}=t,{source:r,repeat:s,id:n}=this,o=sD(this.offsetX/e,0),a=sD(this.offsetY/i,0),l="repeat-y"===s||"no-repeat"===s?1+Math.abs(o||0):sD(r.width/e,0),h="repeat-x"===s||"no-repeat"===s?1+Math.abs(a||0):sD(r.height/i,0);return[''),''),"",""].join("\n")}static async fromObject(t,e){let{type:i,source:r,patternTransform:s}=t,n=h(t,sI),o=await tR(r,l(l({},e),{},{crossOrigin:n.crossOrigin}));return new this(l(l({},n),{},{patternTransform:s&&s.slice(0),source:o}))}}o(sB,"type","Pattern"),$.setClass(sB),$.setClass(sB,"pattern");class sX{constructor(t){o(this,"color","rgb(0, 0, 0)"),o(this,"width",1),o(this,"shadow",null),o(this,"strokeLineCap","round"),o(this,"strokeLineJoin","round"),o(this,"strokeMiterLimit",10),o(this,"strokeDashArray",null),o(this,"limitedToCanvasSize",!1),this.canvas=t}_setBrushStyles(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])}_saveAndTransform(t){let e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])}needsFullRender(){return 1>new tU(this.color).getAlpha()||!!this.shadow}_setShadow(){if(!this.shadow||!this.canvas)return;let t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom()*t.getRetinaScaling();i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}_resetShadow(){let t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0}_isOutSideCanvas(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}let sY=["path","left","top"],sW=["d"];class sV extends i4{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{path:i,left:r,top:s}=e,n=h(e,sY);super(),Object.assign(this,sV.ownDefaults),this.setOptions(n),this._setPath(t||[],!0),"number"==typeof r&&this.set(P,r),"number"==typeof s&&this.set("top",s)}_setPath(t,e){this.path=r5(Array.isArray(t)?t:sc(t)),this.setBoundingBox(e)}_findCenterFromElement(){let t=this._calcBoundsFromPath();return new tn(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){let e=-this.pathOffset.x,i=-this.pathOffset.y;for(let r of(t.beginPath(),this.path))switch(r[0]){case"L":t.lineTo(r[1]+e,r[2]+i);break;case"M":t.moveTo(r[1]+e,r[2]+i);break;case"C":t.bezierCurveTo(r[1]+e,r[2]+i,r[3]+e,r[4]+i,r[5]+e,r[6]+i);break;case"Q":t.quadraticCurveTo(r[1]+e,r[2]+i,r[3]+e,r[4]+i);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#")}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return l(l({},super.toObject(t)),{},{path:this.path.map(t=>t.slice())})}toDatalessObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){let t=sd(this.path,d.NUM_FRACTION_DIGITS);return["\n')]}_getOffsetTransform(){let t=d.NUM_FRACTION_DIGITS;return" translate(".concat(tq(-this.pathOffset.x,t),", ").concat(tq(-this.pathOffset.y,t),")")}toClipPathSVG(t){let e=this._getOffsetTransform();return" "+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){let e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){let{width:e,height:i,pathOffset:r}=this._calcDimensions();this.set({width:e,height:i,pathOffset:r}),t&&this.setPositionByOrigin(r,E,E)}_calcBoundsFromPath(){let t=[],e=0,i=0,r=0,s=0;for(let n of this.path)switch(n[0]){case"L":r=n[1],s=n[2],t.push({x:e,y:i},{x:r,y:s});break;case"M":r=n[1],s=n[2],e=r,i=s;break;case"C":t.push(...r1(r,s,n[1],n[2],n[3],n[4],n[5],n[6])),r=n[5],s=n[6];break;case"Q":t.push(...r1(r,s,n[1],n[2],n[1],n[2],n[3],n[4])),r=n[3],s=n[4];break;case"Z":r=e,s=i}return eo(t)}_calcDimensions(){let t=this._calcBoundsFromPath();return l(l({},t),{},{pathOffset:new tn(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,i){let r=rM(t,this.ATTRIBUTE_NAMES,i),{d:s}=r;return new this(s,l(l(l({},h(r,sW)),e),{},{left:void 0,top:void 0}))}}o(sV,"type","Path"),o(sV,"cacheProperties",[...e2,"path","fillRule"]),o(sV,"ATTRIBUTE_NAMES",[...rc,"d"]),$.setClass(sV),$.setSVGClass(sV);class sH extends sX{constructor(t){super(t),o(this,"decimate",.4),o(this,"drawStraightLine",!1),o(this,"straightLineKey","shiftKey"),this._points=[],this._hasStraightLine=!1}needsFullRender(){return super.needsFullRender()||this._hasStraightLine}static drawSegment(t,e,i){let r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r}onMouseDown(t,e){let{e:i}=e;this.canvas._isMainEvent(i)&&(this.drawStraightLine=!!this.straightLineKey&&i[this.straightLineKey],this._prepareForDrawing(t),this._addPoint(t),this._render())}onMouseMove(t,e){let{e:i}=e;if(this.canvas._isMainEvent(i)&&(this.drawStraightLine=!!this.straightLineKey&&i[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._addPoint(t)&&this._points.length>1)){if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{let t=this._points,e=t.length,i=this.canvas.contextTop;this._saveAndTransform(i),this.oldEnd&&(i.beginPath(),i.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=sH.drawSegment(i,t[e-2],t[e-1]),i.stroke(),i.restore()}}}onMouseUp(t){let{e:e}=t;return!this.canvas._isMainEvent(e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)}_prepareForDrawing(t){this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)}_addPoint(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1]))&&(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),!0)}_reset(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1}_render(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.canvas.contextTop,e=this._points[0],i=this._points[1];if(this._saveAndTransform(t),t.beginPath(),2===this._points.length&&e.x===i.x&&e.y===i.y){let t=this.width/1e3;e.x-=t,i.x+=t}t.moveTo(e.x,e.y);for(let r=1;r=r&&n.push(i=t[e]);return n.push(t[s]),n}_finalizeAndAddPath(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));let t=this.convertPointsToSVGPath(this._points);if("M 0 0 Q 0 0 0 0 L 0 0"===sd(t))return void this.canvas.requestRenderAll();let e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}let sz=["left","top","radius"],sG=["radius","startAngle","endAngle","counterClockwise"];class sN extends i4{static getDefaults(){return l(l({},super.getDefaults()),sN.ownDefaults)}constructor(t){super(),Object.assign(this,sN.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),"radius"===t&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,ty(this.startAngle),ty(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(G)}getRadiusY(){return this.get("radius")*this.get(N)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...sG,...t])}_toSVG(){let t=(this.endAngle-this.startAngle)%360;if(0===t)return["\n'];{let{radius:e}=this,i=ty(this.startAngle),r=ty(this.endAngle),s=tr(i)*e,n=ts(i)*e,o=tr(r)*e,a=ts(r)*e,l=+!this.counterClockwise;return['180)," ").concat(l," ").concat(o," ").concat(a,'" '),"COMMON_PARTS"," />\n"]}}static async fromElement(t,e,i){let r=rM(t,this.ATTRIBUTE_NAMES,i),{left:s=0,top:n=0,radius:o=0}=r;return new this(l(l({},h(r,sz)),{},{radius:o,left:s-o,top:n-o}))}static fromObject(t){return super._fromObject(t)}}o(sN,"type","Circle"),o(sN,"cacheProperties",[...e2,...sG]),o(sN,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),o(sN,"ATTRIBUTE_NAMES",["cx","cy","r",...rc]),$.setClass(sN),$.setSVGClass(sN);let sU=["x1","y1","x2","y2"],sq=["x1","y1","x2","y2"],sK=["x1","x2","y1","y2"];class sJ extends i4{constructor(){let[t,e,i,r]=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0,0,0],s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Object.assign(this,sJ.ownDefaults),this.setOptions(s),this.x1=t,this.x2=i,this.y1=e,this.y2=r,this._setWidthHeight();let{left:n,top:o}=s;"number"==typeof n&&this.set(P,n),"number"==typeof o&&this.set("top",o)}_setWidthHeight(){let{x1:t,y1:e,x2:i,y2:r}=this;this.width=Math.abs(i-t),this.height=Math.abs(r-e);let{left:s,top:n,width:o,height:a}=eo([{x:t,y:e},{x:i,y:r}]),l=new tn(s+o/2,n+a/2);this.setPositionByOrigin(l,E,E)}_set(t,e){return super._set(t,e),sK.includes(t)&&this._setWidthHeight(),this}_render(t){var e;t.beginPath();let i=this.calcLinePoints();t.moveTo(i.x1,i.y1),t.lineTo(i.x2,i.y2),t.lineWidth=this.strokeWidth;let r=t.strokeStyle;t$(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=null!==(e=this.stroke)&&void 0!==e?e:t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=r}_findCenterFromElement(){return new tn((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return l(l({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){let t=super._getNonTransformedDimensions();return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t}calcLinePoints(){let{x1:t,x2:e,y1:i,y2:r,width:s,height:n}=this,o=t<=e?-1:1,a=i<=r?-1:1;return{x1:o*s/2,x2:-(o*s)/2,y1:a*n/2,y2:-(a*n)/2}}_toSVG(){let{x1:t,x2:e,y1:i,y2:r}=this.calcLinePoints();return["\n')]}static async fromElement(t,e,i){let r=rM(t,this.ATTRIBUTE_NAMES,i),{x1:s=0,y1:n=0,x2:o=0,y2:a=0}=r;return new this([s,n,o,a],h(r,sU))}static fromObject(t){let{x1:e,y1:i,x2:r,y2:s}=t,n=h(t,sq);return this._fromObject(l(l({},n),{},{points:[e,i,r,s]}),{extraParam:"points"})}}o(sJ,"type","Line"),o(sJ,"cacheProperties",[...e2,...sK]),o(sJ,"ATTRIBUTE_NAMES",rc.concat(sK)),$.setClass(sJ),$.setSVGClass(sJ);class sQ extends i4{static getDefaults(){return l(l({},super.getDefaults()),sQ.ownDefaults)}constructor(t){super(),Object.assign(this,sQ.ownDefaults),this.setOptions(t)}_render(t){let e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){let t=this.width/2,e=this.height/2;return["']}}o(sQ,"type","Triangle"),o(sQ,"ownDefaults",{width:100,height:100}),$.setClass(sQ),$.setSVGClass(sQ);let sZ=["rx","ry"];class s$ extends i4{static getDefaults(){return l(l({},super.getDefaults()),s$.ownDefaults)}constructor(t){super(),Object.assign(this,s$.ownDefaults),this.setOptions(t)}_set(t,e){switch(super._set(t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this}getRx(){return this.get("rx")*this.get(G)}getRy(){return this.get("ry")*this.get(N)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...sZ,...t])}_toSVG(){return["\n')]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,D,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,i){let r=rM(t,this.ATTRIBUTE_NAMES,i);return r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,new this(r)}}o(s$,"type","Ellipse"),o(s$,"cacheProperties",[...e2,...sZ]),o(s$,"ownDefaults",{rx:0,ry:0}),o(s$,"ATTRIBUTE_NAMES",[...rc,"cx","cy","rx","ry"]),$.setClass(s$),$.setSVGClass(s$);let s0=["left","top"],s1={exactBoundingBox:!1};class s2 extends i4{static getDefaults(){return l(l({},super.getDefaults()),s2.ownDefaults)}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),o(this,"strokeDiff",void 0),Object.assign(this,s2.ownDefaults),this.setOptions(e),this.points=t;let{left:i,top:r}=e;this.initialized=!0,this.setBoundingBox(!0),"number"==typeof i&&this.set(P,i),"number"==typeof r&&this.set("top",r)}isOpen(){return!0}_projectStrokeOnPoints(t){return re(this.points,t,this.isOpen())}_calcDimensions(t){t=l({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});let e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(t=>t.projectedPoint):this.points;if(0===e.length)return{left:0,top:0,width:0,height:0,pathOffset:new tn,strokeOffset:new tn,strokeDiff:new tn};let i=eo(e),r=tF(l(l({},t),{},{scaleX:1,scaleY:1})),s=eo(this.points.map(t=>tb(t,r,!0))),n=new tn(this.scaleX,this.scaleY),o=i.left+i.width/2,a=i.top+i.height/2;return this.exactBoundingBox&&(o-=a*Math.tan(ty(this.skewX)),a-=o*Math.tan(ty(this.skewY))),l(l({},i),{},{pathOffset:new tn(o,a),strokeOffset:new tn(s.left,s.top).subtract(new tn(i.left,i.top)).multiply(n),strokeDiff:new tn(i.width,i.height).subtract(new tn(s.width,s.height)).multiply(n)})}_findCenterFromElement(){let t=eo(this.points);return new tn(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){let{left:e,top:i,width:r,height:s,pathOffset:n,strokeOffset:o,strokeDiff:a}=this._calcDimensions();this.set({width:r,height:s,pathOffset:n,strokeOffset:o,strokeDiff:a}),t&&this.setPositionByOrigin(new tn(e+r/2,i+s/2),E,E)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new tn(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.exactBoundingBox){var e,i,r,s;let n;if(Object.keys(t).some(t=>this.strokeUniform||this.constructor.layoutProperties.includes(t))){let{width:r,height:s}=this._calcDimensions(t);n=new tn(null!==(e=t.width)&&void 0!==e?e:r,null!==(i=t.height)&&void 0!==i?i:s)}else n=new tn(null!==(r=t.width)&&void 0!==r?r:this.width,null!==(s=t.height)&&void 0!==s?s:this.height);return n.multiply(new tn(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){let i=this.initialized&&this[t]!==e,r=super._set(t,e);return this.exactBoundingBox&&i&&((t===G||t===N)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),r}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return l(l({},super.toObject(t)),{},{points:this.points.map(t=>{let{x:e,y:i}=t;return{x:e,y:i}})})}_toSVG(){let t=[],e=this.pathOffset.x,i=this.pathOffset.y,r=d.NUM_FRACTION_DIGITS;for(let s=0,n=this.points.length;s\n')]}_render(t){let e=this.points.length,i=this.pathOffset.x,r=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-i,this.points[0].y-r);for(let s=0;svoid 0!==t);this._setStyleDeclaration(i,r,s)}getSelectionStyles(t,e,i){let r=[];for(let s=t;s<(e||t);s++)r.push(this.getStyleAtPosition(s,i));return r}getStyleAtPosition(t,e){let{lineIndex:i,charIndex:r}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(i,r):this._getStyleDeclaration(i,r)}setSelectionStyles(t,e,i){for(let r=e;r<(i||e);r++)this._extendStyles(r,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var i;let r=this.styles&&this.styles[t];return r&&null!==(i=r[e])&&void 0!==i?i:{}}getCompleteStyleDeclaration(t,e){return l(l({},tX(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,i){this.styles[t][e]=i}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}o(nr,"_styleProperties",s9);let ns=/ +/g,nn=/"/g;function no(t,e,i,r,s){return" ".concat(function(t,e){let{left:i,top:r,width:s,height:n}=e,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:d.NUM_FRACTION_DIGITS,a=tZ(K,t,!1),[l,h,c,u]=[i,r,s,n].map(t=>tq(t,o));return"')}(t,{left:e,top:i,width:r,height:s}),"\n")}let na=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];class nl extends nr{static getDefaults(){return l(l({},super.getDefaults()),nl.ownDefaults)}constructor(t,e){super(),o(this,"__charBounds",[]),Object.assign(this,nl.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){let t=this.path;t&&(t.segmentsInfo=ss(t.path))}_splitText(){let t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(s7)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,i,r,s,n,o;for(let a=0,l=this._textLines.length;a')}_getCacheCanvasDimensions(){let t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){let e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===J?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,i){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case E:t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline=A}t.font=this._getFontDeclaration(e,i)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,i=this._textLines.length;et&&(t=i)}return t}_renderTextLine(t,e,i,r,s,n){this._renderChars(t,e,i,r,s,n)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;let e=t.fillStyle,i=this._getLeftOffset(),r=this._getTopOffset();for(let e=0,s=this._textLines.length;e=0:re?t%=e:t<0&&(t+=e),this._setGraphemeOnPath(t,i),t+=i.kernedWidth}return{width:r,numOfSpaces:0}}_setGraphemeOnPath(t,e){let i=t+e.kernedWidth/2,r=this.path,s=sn(r.path,i,r.segmentsInfo);e.renderLeft=s.x-r.pathOffset.x,e.renderTop=s.y-r.pathOffset.y,e.angle=s.angle+(this.pathSide===j?Math.PI:0)}_getGraphemeBox(t,e,i,r,s){let n=this.getCompleteStyleDeclaration(e,i),o=r?this.getCompleteStyleDeclaration(e,i-1):{},a=this._measureChar(t,n,r,o),l,h=a.kernedWidth,c=a.width;0!==this.charSpacing&&(c+=l=this._getWidthOfCharSpacing(),h+=l);let u={width:c,left:0,height:n.fontSize,kernedWidth:h,deltaY:n.deltaY};if(i>0&&!s){let t=this.__charBounds[e][i-1];u.left=t.left+t.width+a.kernedWidth-a.width}return u}getHeightOfLine(t){if(this.__lineHeights[t])return this.__lineHeights[t];let e=this.getHeightOfChar(t,0);for(let i=1,r=this._textLines[t].length;i0){let e=r+u+f;"rtl"===this.direction&&(e=this.width-e-p),m&&v&&(t.fillStyle=v,t.fillRect(e,_+o*y+x,p,this.fontSize/15)),f=n.left,p=n.width,m=d,v=g,y=l,x=h}else p+=n.kernedWidth}let C=r+u+f;"rtl"===this.direction&&(C=this.width-C-p),t.fillStyle=g,d&&g&&t.fillRect(C,_+o*y+x,p-n,this.fontSize/15),i+=l}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:i=this.fontWeight,fontSize:r=this.fontSize}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0,n=t.includes("'")||t.includes('"')||t.includes(",")||nl.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,i,"".concat(s?this.CACHE_FONT_SIZE:r,"px"),n].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return rs(t)}_splitTextIntoLines(t){let e=t.split(this._reNewline),i=Array(e.length),r=["\n"],s=[];for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:[];return l(l({},super.toObject([...s6,...t])),{},{styles:rl(this.styles,this.text)},this.path?{path:this.path.toObject()}:{})}set(t,e){let{textLayoutProperties:i}=this.constructor;super.set(t,e);let r=!1,s=!1;if("object"==typeof t)for(let e in t)"path"===e&&this.setPathInfo(),r=r||i.includes(e),s=s||"path"===e;else r=i.includes(t),s="path"===t;return s&&this.setPathInfo(),r&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,i){let r=rM(t,nl.ATTRIBUTE_NAMES,i),s=l(l({},e),r),{textAnchor:n=P,textDecoration:o="",dx:a=0,dy:c=0,top:u=0,left:d=0,fontSize:g=16,strokeWidth:f=1}=s,p=h(s,na),m=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),l({left:d+a,top:u+c,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:g},p)),v=m.getScaledHeight()/m.height,_=((m.height+m.strokeWidth)*m.lineHeight-m.height)*v,y=m.getScaledHeight()+_,x=0;return n===E&&(x=m.getScaledWidth()/2),n===j&&(x=m.getScaledWidth()),m.set({left:m.left-x,top:m.top-(y-m.fontSize*(.07+m._fontSizeFraction))/m.lineHeight,strokeWidth:f}),m}static fromObject(t){return this._fromObject(l(l({},t),{},{styles:rh(t.styles||{},t.text)}),{extraParam:"text"})}}o(nl,"textLayoutProperties",s8),o(nl,"cacheProperties",[...e2,...s6]),o(nl,"ownDefaults",{_reNewline:L,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:P,fontStyle:"normal",lineHeight:1.16,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:P,pathAlign:"baseline",_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.315,overline:-.88},_fontSizeMult:1.13,charSpacing:0,deltaY:0,direction:"ltr",CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2}),o(nl,"type","Text"),o(nl,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),o(nl,"ATTRIBUTE_NAMES",rc.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),i3(nl,[class extends eD{_toSVG(){let t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(t){let{textBgRects:e,textSpans:i}=t,r=this.getSvgTextDecoration(this);return[e.join(""),' ",i.join(""),"\n"]}_getSVGTextAndBg(t,e){let i=[],r=[],s,n=t;this.backgroundColor&&r.push(...no(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let t=0,o=this._textLines.length;t").concat(rr(t),"")}_setSVGTextLineText(t,e,i,r){let s=this.getHeightOfLine(e),n=this.textAlign.includes(s7),o=this._textLines[e],a,l,h,c,u,d="",g=0;r+=s*(1-this._fontSizeFraction)/this.lineHeight;for(let s=0,f=o.length-1;s<=f;s++)u=s===f||this.charSpacing,d+=o[s],h=this.__charBounds[e][s],0===g?(i+=h.kernedWidth-h.width,g+=h.width):g+=h.kernedWidth,n&&!u&&this._reSpaceAndTab.test(o[s])&&(u=!0),u||(u=ra(a=a||this.getCompleteStyleDeclaration(e,s),l=this.getCompleteStyleDeclaration(e,s+1),!0)),u&&(c=this._getStyleDeclaration(e,s),t.push(this._createTextCharSpan(d,c,i,r)),d="",a=l,"rtl"===this.direction?i-=g:i+=g,g=0)}_setSVGTextLineBg(t,e,i,r){let s=this._textLines[e],n=this.getHeightOfLine(e)/this.lineHeight,o,a=0,l=0,h=this.getValueOfPropertyAt(e,0,"textBackgroundColor");for(let c=0;ct[e.replace("-","")]).join(" ")}}]),$.setClass(nl),$.setSVGClass(nl);class nh{constructor(t){o(this,"target",void 0),o(this,"__mouseDownInPlace",!1),o(this,"__dragStartFired",!1),o(this,"__isDraggingOver",!1),o(this,"__dragStartSelection",void 0),o(this,"__dragImageDisposer",void 0),o(this,"_dispose",void 0),this.target=t;let e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach(t=>t()),this._dispose=void 0}}isPointerOverSelection(t){let e=this.target,i=e.getSelectionStartFromPointer(t);return e.isEditing&&i>=e.selectionStart&&i<=e.selectionEnd&&e.selectionStart{y.remove()},t3(t.target||this.target.hiddenTextarea).body.appendChild(y),null===(i=t.dataTransfer)||void 0===i||i.setDragImage(y,p.x,p.y)}onDragStart(t){this.__dragStartFired=!0;let e=this.target,i=this.isActive();if(i&&t.dataTransfer){let i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},r=e._text.slice(i.selectionStart,i.selectionEnd).join(""),s=l({text:e.text,value:r},i);t.dataTransfer.setData("text/plain",r),t.dataTransfer.setData("application/fabric",JSON.stringify({value:r,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,s)}return e.abortCursorAnimation(),i}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){let e=this.target.getSelectionStartFromPointer(t),i=this.__dragStartSelection;return ei.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e:e}=t,i=this.targetCanDrop(e);!this.__isDraggingOver&&i&&(this.__isDraggingOver=!0)}dragOverHandler(t){let{e:e}=t,i=this.targetCanDrop(e);!this.__isDraggingOver&&i?this.__isDraggingOver=!0:this.__isDraggingOver&&!i&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;let{e:i}=t,r=i.defaultPrevented;this.__isDraggingOver=!1,i.preventDefault();let s=null===(e=i.dataTransfer)||void 0===e?void 0:e.getData("text/plain");if(s&&!r){let e=this.target,r=e.canvas,n=e.getSelectionStartFromPointer(i),{styles:o}=i.dataTransfer.types.includes("application/fabric")?JSON.parse(i.dataTransfer.getData("application/fabric")):{},a=s[Math.max(0,s.length-1)];if(this.__dragStartSelection){let t=this.__dragStartSelection.selectionStart,i=this.__dragStartSelection.selectionEnd;n>t&&n<=i?n=t:n>i&&(n-=i-t),e.removeChars(t,i),delete this.__dragStartSelection}e._reNewline.test(a)&&(e._reNewline.test(e._text[n])||n===e._text.length)&&(s=s.trimEnd()),t.didDrop=!0,t.dropTarget=e,e.insertChars(s,o,n),r.setActiveObject(e),e.enterEditing(i),e.selectionStart=Math.min(n+0,e._text.length),e.selectionEnd=Math.min(e.selectionStart+s.length,e._text.length),e.hiddenTextarea.value=e.text,e._updateTextarea(),e.hiddenTextarea.focus(),e.fire(H,{index:n+0,action:"drop"}),r.fire("text:changed",{target:e}),r.contextTopDirty=!0,r.requestRenderAll()}}dragEndHandler(t){let{e:e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var i;let t=this.target,r=this.target.canvas,{selectionStart:s,selectionEnd:n}=this.__dragStartSelection,o=(null===(i=e.dataTransfer)||void 0===i?void 0:i.dropEffect)||F;o===F?(t.selectionStart=s,t.selectionEnd=n,t._updateTextarea(),t.hiddenTextarea.focus()):(t.clearContextTop(),"move"===o&&(t.removeChars(s,n),t.selectionStart=t.selectionEnd=s,t.hiddenTextarea&&(t.hiddenTextarea.value=t.text),t._updateTextarea(),t.fire(H,{index:s,action:"dragend"}),r.fire("text:changed",{target:t}),r.requestRenderAll()),t.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}let nc=/[ \n\.,;!\?\-]/;class nu extends nl{constructor(){super(...arguments),o(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:i,delay:r,onComplete:s}=t;return iy({startValue:this._currentCursorOpacity,endValue:e,duration:i,delay:r,onComplete:s,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:t=>{this._currentCursorOpacity=t,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;null===(t=this._currentTickCompleteState)||void 0===t||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach(e=>{e&&!e.isDone()&&(t=!0,e.abort())}),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(t=>!t||t.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e}findWordBoundaryRight(t){let e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e}findLineBoundaryRight(t){let e=0,i=t;for(;!/\n/.test(this._text[i])&&i0&&this._reSpace.test(i[t])&&(-1===e||!L.test(i[t-1]))?t-1:t,s=i[r];for(;r>0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=i):(this.selectionStart=i,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===r&&this.selectionEnd===s||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,i){let r=i.slice(0,t),s=this.graphemeSplit(r).length;if(t===e)return{selectionStart:s,selectionEnd:s};let n=i.slice(t,e);return{selectionStart:s,selectionEnd:s+this.graphemeSplit(n).length}}fromGraphemeToStringSelection(t,e,i){let r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){let t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};let t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();let e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){let t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};let t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,s=i.charIndex,n=this.getValueOfPropertyAt(r,s,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.getCanvasRetinaScaling(),l=this.canvas.upperCanvasEl,h=l.width/a,c=l.height/a,u=h-n,d=c-n,g=new tn(e.left+o,e.top+e.topOffset+n).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new tn(l.clientWidth/h,l.clientHeight/c));return g.x<0&&(g.x=0),g.x>u&&(g.x=u),g.y<0&&(g.y=0),g.y>d&&(g.y=d),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:"".concat(g.x,"px"),top:"".concat(g.y,"px"),fontSize:"".concat(n,"px"),charHeight:n}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){let t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){let t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(Q),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(let t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){let{lineIndex:i,charIndex:r}=this.get2DCursorLocation(t,!0),{lineIndex:s,charIndex:n}=this.get2DCursorLocation(e,!0);if(i!==s){if(this.styles[i])for(let t=r;t=n&&(t[i-e]=t[r],delete t[r])}}}shiftLineStyles(t,e){let i=Object.assign({},this.styles);for(let r in this.styles){let s=parseInt(r,10);s>t&&(this.styles[s+e]=i[s],i[s-e]||delete this.styles[s])}}insertNewlineStyleObject(t,e,i,r){let s={},n=this._unwrappedTextLines[t].length,o=n===e,a=!1;i||(i=1),this.shiftLineStyles(t,i);let h=this.styles[t]?this.styles[t][0===e?e:e-1]:void 0;for(let i in this.styles[t]){let r=parseInt(i,10);r>=e&&(a=!0,s[r-e]=this.styles[t][i],o&&0===e||delete this.styles[t][i])}let c=!1;for(a&&!o&&(this.styles[t+i]=s,c=!0),(c||n>e)&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:l({},r[i-1])}:h?this.styles[t+i]={0:l({},h)}:delete this.styles[t+i],i--;this._forceClearCache=!0}insertCharStyleObject(t,e,i,r){this.styles||(this.styles={});let s=this.styles[t],n=s?l({},s):{};for(let t in i||(i=1),n){let r=parseInt(t,10);r>=e&&(s[r+i]=n[r],n[r-i]||delete s[r])}if(this._forceClearCache=!0,r){for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=l({},r[i]));return}if(!s)return;let o=s[e?e-1:1];for(;o&&i--;)this.styles[t][e+i]=l({},o)}insertNewStyleBlock(t,e,i){let r=this.get2DCursorLocation(e,!0),s=[0],n,o=0;for(let e=0;e0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,s[0],i),i=i&&i.slice(s[0]+1)),o&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+s[0],o),n=1;n0?this.insertCharStyleObject(r.lineIndex+n,0,s[n],i):i&&this.styles[r.lineIndex+n]&&i[0]&&(this.styles[r.lineIndex+n][0]=i[0]),i=i&&i.slice(s[n]+1);s[n]>0&&this.insertCharStyleObject(r.lineIndex+n,0,s[n],i)}removeChars(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,i){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:i;r>i&&this.removeStyleFromTo(i,r);let s=this.graphemeSplit(t);this.insertNewStyleBlock(s,i,e),this._text=[...this._text.slice(0,i),...s,...this._text.slice(r)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,i){i<=t?(e===t?this._selectionDirection=P:this._selectionDirection===j&&(this._selectionDirection=P,this.selectionEnd=t),this.selectionStart=i):i>t&&i{let[i,r]=t;return e.setAttribute(i,r)});let{top:i,left:r,fontSize:s}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(i,"; left: ").concat(r,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(s,";"),(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map(t=>{let[i,r]=t;return e.addEventListener(i,this[r].bind(this))}),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;let e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){let e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;let i=()=>{this.updateFromTextArea(),this.fire(H),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(""===this.hiddenTextarea.value)return this.styles={},void i();let r=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,s=this._text.length,n=r.length,o=this.selectionStart,a=this.selectionEnd,l=o!==a,h,c,u,g,f=n-s,p=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=o>p.selectionStart;l?(c=this._text.slice(o,a),f+=a-o):nh[0])),l?(u=o,g=a):m?(u=a-c.length,g=a):(u=a,g=a+c.length),this.removeStyleFromTo(u,g)),v.length){let{copyPasteData:t}=y();e&&v.join("")===t.copiedText&&!d.disableStyleCopyPaste&&(h=t.copiedTextStyle),this.insertNewStyleBlock(v,o,h)}i()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t,{selectionStart:i,selectionEnd:r}=e;this.compositionStart=i,this.compositionEnd=r,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;let{copyPasteData:t}=y();t.copiedText=this.getSelectedText(),d.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let i,r=this._getLineLeftOffset(t);return e>0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r}getDownCursorOffset(t,e){let i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),s=r.lineIndex;if(s===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;let n=r.charIndex,o=this._getWidthBeforeCursor(s,n),a=this._getIndexOnLine(s+1,o);return this._textLines[s].slice(n).length+a+1+this.missingNewlineOffset(s)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){let i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),s=r.lineIndex;if(0===s||t.metaKey||33===t.keyCode)return-i;let n=r.charIndex,o=this._getWidthBeforeCursor(s,n),a=this._getIndexOnLine(s-1,o),l=this._textLines[s].slice(0,n),h=this.missingNewlineOffset(s-1);return-this._textLines[s-1].length+a-l.length+(1-h)}_getIndexOnLine(t,e){let i=this._textLines[t],r,s,n=this._getLineLeftOffset(t),o=0;for(let a=0,l=i.length;ae){s=!0;let t=Math.abs(n-r-e);o=Math.abs(n-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){let i=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===j);if(e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i){let t=this.text.length;this.selectionStart=e0(0,this.selectionStart,t),this.selectionEnd=e0(0,this.selectionEnd,t),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){let e=this._selectionDirection===P?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t}moveCursorLeft(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)}_move(t,e,i){let r;if(t.altKey)r=this["findWordBoundary".concat(i)](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary".concat(i)](this[e])}return void 0!==r&&this[e]!==r&&(this[e]=r,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=P,this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===j&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection=P,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){let i="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===P&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=j,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=j,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}let ng=t=>!!t.button;class nf extends nd{constructor(){super(...arguments),o(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler),this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown),this.draggableTextDelegate=new nh(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}onMouseDown(t){if(!this.canvas)return;this.__newClickTime=+new Date;let e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),en(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastSelected=this.selected&&!this.getActiveControl()}isTripleClick(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y}doubleClickHandler(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))}tripleClickHandler(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))}_mouseDownHandler(t){let{e:e}=t;this.canvas&&this.editable&&!ng(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection())))}_mouseDownHandlerBefore(t){let{e:e}=t;this.canvas&&this.editable&&!ng(e)&&(this.selected=this===this.canvas._activeObject)}mouseUpHandler(t){let{e:e,transform:i}=t,r=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);let t=this.canvas._activeObject;if(t&&t!==this)return}!this.editable||this.group&&!this.group.interactive||i&&i.actionPerformed||ng(e)||r||(this.__lastSelected&&!this.getActiveControl()?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0)}setCursorByClick(t){let e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){let e=this.canvas.getScenePoint(t).transform(tS(this.calcTransformMatrix())).add(new tn(-this._getLeftOffset(),-this._getTopOffset())),i=0,r=0,s=0;for(let t=0;t0&&(r+=this._textLines[t-1].length+this.missingNewlineOffset(t-1));let n=Math.abs(this._getLineLeftOffset(s)),o=this._textLines[s].length,a=this.__charBounds[s];for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:this.selectionStart||0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.selectionEnd,i=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,i)}setSelectionStyles(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.selectionStart||0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,i)}get2DCursorLocation(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){let e=this.isEditing;this.isEditing=!1;let i=super.toCanvasElement(t);return this.isEditing=e,i}renderCursorOrSelection(){if(!this.isEditing)return;let t=this.clearContextTop(!0);if(!t)return;let e=this._getCursorBoundaries();this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(t,e):this.renderCursor(t,e),this.canvas.contextTopDirty=!0,t.restore()}_getCursorBoundaries(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0,i=this._getLeftOffset(),r=this._getTopOffset(),s=this._getCursorBoundariesOffsets(t,e);return{left:i,top:r,leftOffset:s.left,topOffset:s.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,i=0,{charIndex:r,lineIndex:s}=this.get2DCursorLocation(t);for(let t=0;t0?i:0)};return"rtl"===this.direction&&(this.textAlign===j||this.textAlign===s7||this.textAlign===ne?a.left*=-1:this.textAlign===P||this.textAlign===nt?a.left=n-(i>0?i:0):this.textAlign!==E&&this.textAlign!==ni||(a.left=n-(i>0?i:0))),a}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.selectionStart,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,s=i.charIndex>0?i.charIndex-1:0,n=this.getValueOfPropertyAt(r,s,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),a=this.cursorWidth/o,l=this.getValueOfPropertyAt(r,s,"deltaY"),h=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-n*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(r,s,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-a/2,top:h+e.top+l,width:a,height:n}}_renderCursor(t,e,i){let{color:r,opacity:s,left:n,top:o,width:a,height:l}=this.getCursorRenderingData(i,e);t.fillStyle=r,t.globalAlpha=s,t.fillRect(n,o,a,l)}renderSelection(t,e){let i={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,i,e)}renderDragSourceEffect(){let t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){let e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,i){let r=e.selectionStart,s=e.selectionEnd,n=this.textAlign.includes(s7),o=this.get2DCursorLocation(r),a=this.get2DCursorLocation(s),l=o.lineIndex,h=a.lineIndex,c=o.charIndex<0?0:o.charIndex,u=a.charIndex<0?0:a.charIndex;for(let e=l;e<=h;e++){let r=this._getLineLeftOffset(e)||0,s=this.getHeightOfLine(e),o=0,a=0,d=0;if(e===l&&(a=this.__charBounds[l][c].left),e>=l&&e1)&&(s/=this.lineHeight);let g=i.left+r+a,f=s,p=0,m=d-a;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",f=1,p=s):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(this.textAlign===j||this.textAlign===s7||this.textAlign===ne?g=this.width-g-m:this.textAlign===P||this.textAlign===nt?g=i.left+r-d:this.textAlign!==E&&this.textAlign!==ni||(g=i.left+r-d)),t.fillRect(g,i.top+i.topOffset+p,m,f),i.topOffset+=o}}getCurrentCharFontSize(){let t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){let t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,K)}_getCurrentCharIndex(){let t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}o(nC,"ownDefaults",nx),o(nC,"type","IText"),$.setClass(nC),$.setClass(nC,"i-text");class nb extends nC{static getDefaults(){return l(l({},super.getDefaults()),nb.ownDefaults)}constructor(t,e){super(t,l(l({},nb.ownDefaults),e))}static createControls(){return{controls:i2()}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this.textAlign.includes(s7)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,i=0,r=0,s={};for(let n=0;n0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&n>0&&(i++,r++),s[n]={line:e,offset:i},r+=t.graphemeLines[n].length,i+=t.graphemeLines[n].length;return s}styleHas(t,e){if(this._styleMap&&!this.isWrapping){let t=this._styleMap[e];t&&(e=t.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,i=0,r=t+1,s=!1,n=this._styleMap[t],o=this._styleMap[t+1];n&&(t=n.line,i=n.offset),o&&(s=o.line===t,e=o.offset);let a=void 0===t?this.styles:{line:this.styles[t]};for(let t in a)for(let r in a[t]){let n=parseInt(r,10);if(n>=i&&(!s||n{let n=0,o=e?this.graphemeSplit(t):this.wordSplit(t);return 0===o.length?[{word:[],width:0}]:o.map(t=>{let o=e?[t]:this.graphemeSplit(t),a=this._measureWord(o,s,n);return r=Math.max(a,r),n+=o.length+i.length,{word:o,width:a}})}),largestWordWidth:r}}_measureWord(t,e){let i,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=0;for(let n=0,o=t.length;n3&&void 0!==arguments[3]?arguments[3]:0,a=this._getWidthOfCharSpacing(),l=this.splitByGrapheme,h=[],c=l?"":" ",u=0,d=[],g=0,f=0,p=!0,m=Math.max(e-=o,s,this.dynamicMinWidth),v=n[t];for(g=0,r=0;rm&&!p?(h.push(d),d=[],u=i,p=!0):u+=a,p||l||d.push(c),d=d.concat(e),f=l?0:this._measureWord([c],t,g),g++,p=!1}return r&&h.push(d),s+o>this.dynamicMinWidth&&(this.dynamicMinWidth=s-a+o),h}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?+!!this.isEndOfWrapping(t):1}_splitTextIntoLines(t){let e=super._splitTextIntoLines(t),i=this._wrapText(e.lines,this.width),r=Array(i.length);for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}o(nb,"type","Textbox"),o(nb,"textLayoutProperties",[...nC.textLayoutProperties,"width"]),o(nb,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),$.setClass(nb);class nS extends rB{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){let{target:i}=t,{clipPath:r,group:s}=i;if(!r||!this.shouldPerformLayout(t))return;let{width:n,height:o}=eo(rI(i,r)),a=new tn(n,o);if(r.absolutePositioned)return{center:ef(r.getRelativeCenterPoint(),void 0,s?s.calcTransformMatrix():void 0),size:a};{let s=r.getRelativeCenterPoint().transform(i.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){let{center:i=new tn,correction:r=new tn}=this.calcBoundingBox(e,t)||{};return{center:i.add(s),correction:r.subtract(s),size:a}}return{center:i.getRelativeCenterPoint().add(s),size:a}}}}o(nS,"type","clip-path"),$.setClass(nS);class nw extends rB{getInitialSize(t,e){let{target:i}=t,{size:r}=e;return new tn(i.width||r.x,i.height||r.y)}}o(nw,"type","fixed"),$.setClass(nw);class nT extends rH{subscribeTargets(t){let e=t.target;t.targets.reduce((t,e)=>(e.parent&&t.add(e.parent),t),new Set).forEach(t=>{t.layoutManager.subscribeTargets({target:t,targets:[e]})})}unsubscribeTargets(t){let e=t.target,i=e.getObjects();t.targets.reduce((t,e)=>(e.parent&&t.add(e.parent),t),new Set).forEach(t=>{i.some(e=>e.parent===t)||t.layoutManager.unsubscribeTargets({target:t,targets:[e]})})}}class nO extends rN{static getDefaults(){return l(l({},super.getDefaults()),nO.ownDefaults)}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Object.assign(this,nO.ownDefaults),this.setOptions(e);let{left:i,top:r,layoutManager:s}=e;this.groupInit(t,{left:i,top:r,layoutManager:null!=s?s:new nT})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=Array(t),i=0;i{let e=this._objects.findIndex(e=>e.isInFrontOf(t)),i=-1===e?this.size():e;this.insertAt(i,t)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?(g("error","ActiveSelection: circular object trees are not supported, this call has no effect"),!1):super.canEnterGroup(t)}enterGroup(t,e){t.parent&&t.parent===t.group?t.parent._exitGroup(t):t.group&&t.parent!==t.group&&t.group.remove(t),this._enterGroup(t,e)}exitGroup(t,e){this._exitGroup(t,e),t.parent&&t.parent._enterGroup(t,!0)}_onAfterObjectsChange(t,e){super._onAfterObjectsChange(t,e);let i=new Set;e.forEach(t=>{let{parent:e}=t;e&&i.add(e)}),t===rL?i.forEach(t=>{t._onAfterObjectsChange(rF,e)}):i.forEach(t=>{t._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return"#")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;let r=l(l({hasControls:!1},i),{},{forActiveSelection:!0});for(let e=0;e{t.applyTo(o)});let{imageData:a}=o;return a.width===i&&a.height===r||(s.width=a.width,s.height=a.height),n.putImageData(a,0,0),o}}class nk{constructor(){let{tileSize:t=d.textureSize}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};o(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),o(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){let i=tm({width:t,height:e}),r=i.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)}applyFilters(t,e,i,r,s,n){let o;let a=this.gl,l=s.getContext("2d");if(!a||!l)return;n&&(o=this.getCachedTexture(n,e));let h={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,o?void 0:e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,o?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:s},c=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,c),t.forEach(t=>{t&&t.applyTo(h)}),function(t){let e=t.targetCanvas,i=e.width,r=e.height,s=t.destinationWidth,n=t.destinationHeight;i===s&&r===n||(e.width=s,e.height=n)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(c),l.setTransform(1,0,0,1,0,0),h}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,i,r,s){let{NEAREST:n,TEXTURE_2D:o,RGBA:a,UNSIGNED_BYTE:l,CLAMP_TO_EDGE:h,TEXTURE_MAG_FILTER:c,TEXTURE_MIN_FILTER:u,TEXTURE_WRAP_S:d,TEXTURE_WRAP_T:g}=t,f=t.createTexture();return t.bindTexture(o,f),t.texParameteri(o,c,s||n),t.texParameteri(o,u,s||n),t.texParameteri(o,d,h),t.texParameteri(o,g,h),r?t.texImage2D(o,0,a,a,l,r):t.texImage2D(o,0,a,e,i,0,a,l,null),f}getCachedTexture(t,e,i){let{textureCache:r}=this;if(r[t])return r[t];{let s=this.createTexture(this.gl,e.width,e.height,e,i);return s&&(r[t]=s),s}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){let i=t.canvas,r=e.targetCanvas,s=r.getContext("2d");if(!s)return;s.translate(0,r.height),s.scale(1,-1);let n=i.height-r.height;s.drawImage(i,0,n,r.width,r.height,0,0,r.width,r.height)}copyGLTo2DPutImageData(t,e){let i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,s=e.destinationHeight,n=r*s*4;if(!i)return;let o=new Uint8Array(this.imageBuffer,0,n),a=new Uint8ClampedArray(this.imageBuffer,0,n);t.readPixels(0,0,r,s,t.RGBA,t.UNSIGNED_BYTE,o);let l=new ImageData(a,r,s);i.putImageData(l,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;let t=this.gl,e={renderer:"",vendor:""};if(!t)return e;let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),s=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),s&&(e.vendor=s.toLowerCase())}return this.gpuInfo=e,e}}function nM(){return n||arguments.length>0&&void 0!==arguments[0]&&!arguments[0]||(n=function(){let{WebGLProbe:t}=y();return t.queryWebGL(tf()),d.enableGLFiltering&&t.isSupported(d.textureSize)?new nk({tileSize:d.textureSize}):new nD}()),n}let nE=["filters","resizeFilter","src","crossOrigin","type"],nP=["cropX","cropY"];class nA extends i4{static getDefaults(){return l(l({},super.getDefaults()),nA.ownDefaults)}constructor(t,e){super(),o(this,"_lastScaleX",1),o(this,"_lastScaleY",1),o(this,"_filterScalingX",1),o(this,"_filterScalingY",1),this.filters=[],Object.assign(this,nA.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(tg()),this.setElement("string"==typeof t?(this.canvas&&t3(this.canvas.getElement())||x()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(i),null===(e=t.classList)||void 0===e||e.add(nA.CSS_CANVAS),0!==this.filters.length&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){let e=nM(!1);e instanceof nk&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(t=>{let e=this[t];e&&y().dispose(e),this[t]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){let t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||0===this.strokeWidth)return;let e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,-i),t.lineTo(e,-i),t.lineTo(e,i),t.lineTo(-e,i),t.lineTo(-e,-i),t.closePath()}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=[];return this.filters.forEach(t=>{t&&e.push(t.toObject())}),l(l({},super.toObject([...nP,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width\n',' \n',"\n"),o=' clip-path="url(#imageCrop_'+t+')" '}if(this.imageSmoothing||(a=' image-rendering="optimizeSpeed"'),t.push(" \n")),this.stroke||this.strokeDashArray){let t=this.fill;this.fill=null,n=[' \n')],this.fill=t}return this.paintFirst!==K?s.concat(n,t):s.concat(t,n)}getSrc(t){let e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:i}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return tR(t,{crossOrigin:e,signal:i}).then(t=>{void 0!==e&&this.set({crossOrigin:e}),this.setElement(t)})}toString(){return'#')}applyResizeFilters(){let t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.x,s=i.y,n=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&s>e)return this._element=n,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=s);let o=tm(n),{width:a,height:l}=n;this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=s,nM().applyFilters([t],n,a,l,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.filters||[];if(t=t.filter(t=>t&&!t.isNeutralState()),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),0===t.length)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);let e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){let t=tm({width:i,height:r});this._element=t,this._filteredEl=t}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1);nM().applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){let e=this._element;if(!e)return;let i=this._filterScalingX,r=this._filterScalingY,s=this.width,n=this.height,o=Math.max(this.cropX,0),a=Math.max(this.cropY,0),l=e.naturalWidth||e.width,h=e.naturalHeight||e.height,c=o*i,u=a*r,d=Math.min(s*i,l-c),g=Math.min(n*r,h-u),f=Math.min(s,l/i-o),p=Math.min(n,h/r-a);e&&t.drawImage(e,c,u,d,g,-s/2,-n/2,f,p)}_needsResize(){let t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=this.getOriginalSize();this.width=t||i.width,this.height=e||i.height}parsePreserveAspectRatioAttribute(){let t=tJ(this.preserveAspectRatio||""),e=this.width,i=this.height,r={width:e,height:i},s,n=this._element.width,o=this._element.height,a=1,l=1,h=0,c=0,u=0,d=0;return t&&(t.alignX!==F||t.alignY!==F)?("meet"===t.meetOrSlice&&(s=(e-n*(a=l=rU(this._element,r)))/2,"Min"===t.alignX&&(h=-s),"Max"===t.alignX&&(h=s),s=(i-o*l)/2,"Min"===t.alignY&&(c=-s),"Max"===t.alignY&&(c=s)),"slice"===t.meetOrSlice&&(s=n-e/(a=l=rq(this._element,r)),"Mid"===t.alignX&&(u=s/2),"Max"===t.alignX&&(u=s),s=o-i/l,"Mid"===t.alignY&&(d=s/2),"Max"===t.alignY&&(d=s),n=e/a,o=i/l)):(a=e/n,l=i/o),{width:n,height:o,scaleX:a,scaleY:l,offsetLeft:h,offsetTop:c,cropX:u,cropY:d}}static fromObject(t,e){let{filters:i,resizeFilter:r,src:s,crossOrigin:n,type:o}=t,a=h(t,nE);return Promise.all([tR(s,l(l({},e),{},{crossOrigin:n})),i&&tI(i,e),r&&tI([r],e),tB(a,e)]).then(t=>{let[e,i=[],[r]=[],n={}]=t;return new this(e,l(l({},a),{},{src:s,filters:i,resizeFilter:r},n))})}static fromURL(t){let{crossOrigin:e=null,signal:i}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return tR(t,{crossOrigin:e,signal:i}).then(t=>new this(t,r))}static async fromElement(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0,r=rM(t,this.ATTRIBUTE_NAMES,i);return this.fromURL(r["xlink:href"],e,r).catch(t=>(g("log","Unable to parse Image",t),null))}}function nj(t){if(!eR.test(t.nodeName))return{};let e=t.getAttribute("viewBox"),i,r,s=1,n=1,o=0,a=0,l=t.getAttribute("width"),h=t.getAttribute("height"),c=t.getAttribute("x")||0,u=t.getAttribute("y")||0,d=!(e&&eB.test(e)),g=!l||!h||"100%"===l||"100%"===h,f="",p=0,m=0;if(d&&(c||u)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(f=" translate("+tK(c||"0")+" "+tK(u||"0")+") ",i=(t.getAttribute("transform")||"")+f,t.setAttribute("transform",i),t.removeAttribute("x"),t.removeAttribute("y")),d&&g)return{width:0,height:0};let v={width:0,height:0};if(d)return v.width=tK(l),v.height=tK(h),v;let _=e.match(eB);o=-parseFloat(_[1]),a=-parseFloat(_[2]);let y=parseFloat(_[3]),x=parseFloat(_[4]);v.minX=o,v.minY=a,v.viewBoxWidth=y,v.viewBoxHeight=x,g?(v.width=y,v.height=x):(v.width=tK(l),v.height=tK(h),s=v.width/y,n=v.height/x);let C=tJ(t.getAttribute("preserveAspectRatio")||"");if(C.alignX!==F&&("meet"===C.meetOrSlice&&(n=s=s>n?n:s),"slice"===C.meetOrSlice&&(n=s=s>n?s:n),p=v.width-y*s,m=v.height-x*s,"Mid"===C.alignX&&(p/=2),"Mid"===C.alignY&&(m/=2),"Min"===C.alignX&&(p=0),"Min"===C.alignY&&(m=0)),1===s&&1===n&&0===o&&0===a&&0===c&&0===u)return v;if((c||u)&&"#document"!==t.parentNode.nodeName&&(f=" translate("+tK(c||"0")+" "+tK(u||"0")+") "),i=f+" matrix("+s+" 0 0 "+n+" "+(o*s+p)+" "+(a*n+m)+") ","svg"===t.nodeName){for(r=t.ownerDocument.createElementNS(eE,"g");t.firstChild;)r.appendChild(t.firstChild);t.appendChild(r)}else(r=t).removeAttribute("x"),r.removeAttribute("y"),i=r.getAttribute("transform")+i;return r.setAttribute("transform",i),v}o(nA,"type","Image"),o(nA,"cacheProperties",[...e2,...nP]),o(nA,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),o(nA,"CSS_CANVAS","canvas-img"),o(nA,"ATTRIBUTE_NAMES",[...rc,"x","y","width","height","preserveAspectRatio","xlink:href","crossOrigin","image-rendering"]),$.setClass(nA),$.setSVGClass(nA);let nF=t=>t.tagName.replace("svg:",""),nL=ek(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function nR(t,e){let i,r,s,n,o=[];for(s=0,n=e.length;s$.getSVGClass(nF(t).toLowerCase());class nX{constructor(t,e,i,r,s){this.elements=t,this.options=e,this.reviver=i,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=r,this.clipPaths=s,this.gradientDefs=function(t){let e=nR(t,null),i={},r=e.length;for(;r--;){let s=e[r];s.getAttribute("xlink:href")&&function t(e,i){var r;let s=(null===(r=i.getAttribute(nI))||void 0===r?void 0:r.slice(1))||"",n=e.getElementById(s);if(n&&n.getAttribute(nI)&&t(e,n),n&&(null.forEach(t=>{let e=n.getAttribute(t);!i.hasAttribute(t)&&e&&i.setAttribute(t,e)}),!i.children.length)){let t=n.cloneNode(!0);for(;t.firstChild;)i.appendChild(t.firstChild)}i.removeAttribute(nI)}(t,s);let n=s.getAttribute("id");n&&(i[n]=s)}return i}(r),this.cssRules=function(t){let e,i;let r=t.getElementsByTagName("style"),s={};for(e=0,i=r.length;ei.length>1&&t.trim()).forEach(t=>{if((t.match(/{/g)||[]).length>1&&t.trim().startsWith("@"))return;let r=t.split("{"),n={},o=r[1].trim().split(";").filter(function(t){return t.trim()});for(e=0,i=o.length;e{""!==(t=t.replace(/^svg/i,"").trim())&&(s[t]=l(l({},s[t]||{}),n))})})}return s}(r)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){let e=nB(t);if(e){let i=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(i,t,K),this.resolveGradient(i,t,J),i instanceof nA&&i._originalElement?sf(i,i.parsePreserveAspectRatioAttribute()):sf(i),await this.resolveClipPath(i,t),this.reviver&&this.reviver(t,i),i}return null}extractPropertyDefinition(t,e,i){let r=t[e],s=this.regexUrl;if(!s.test(r))return;s.lastIndex=0;let n=s.exec(r)[1];return s.lastIndex=0,i[n]}resolveGradient(t,e,i){let r=this.extractPropertyDefinition(t,i,this.gradientDefs);if(r){let s=e.getAttribute(i+"-opacity"),n=sR.fromElement(r,t,l(l({},this.options),{},{opacity:s}));t.set(i,n)}}async resolveClipPath(t,e,i){let r=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(r){let s=tS(t.calcTransformMatrix()),n=r[0].parentElement,o=e;for(;!i&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(n);let a=rO("".concat(o.getAttribute("transform")||""," ").concat(n.getAttribute("originalTransform")||""));n.setAttribute("transform","matrix(".concat(a.join(","),")"));let l=await Promise.all(r.map(t=>nB(t).fromElement(t,this.options,this.cssRules).then(t=>(sf(t),t.fillRule=t.clipRule,delete t.clipRule,t)))),h=1===l.length?l[0]:new rN(l),c=tw(s,h.calcTransformMatrix());h.clipPath&&await this.resolveClipPath(h,o,n.getAttribute("clip-path")?o:void 0);let{scaleX:u,scaleY:d,angle:g,skewX:f,translateX:p,translateY:m}=tD(c);h.set({flipX:!1,flipY:!1}),h.set({scaleX:u,scaleY:d,angle:g,skewX:f,skewY:0}),h.setPositionByOrigin(new tn(p,m),E,E),t.clipPath=h}else delete t.clipPath}}let nY=t=>eL.test(nF(t)),nW=()=>({objects:[],elements:[],options:{},allElements:[]}),nV=t=>function(e,i,r){let{points:s,pathOffset:n}=r;return new tn(s[t]).subtract(n).transform(tw(r.getViewportTransform(),r.calcTransformMatrix()))},nH=(t,e,i,r)=>{let{target:s,pointIndex:n}=e,o=ef(new tn(i,r),void 0,s.calcOwnMatrix());return s.points[n]=o.add(s.pathOffset),s.setDimensions(),!0},nz=(t,e)=>function(i,r,s,n){let o=r.target,a=new tn(o.points[(t>0?t:o.points.length)-1]),h=a.subtract(o.pathOffset).transform(o.calcOwnMatrix()),c=e(i,l(l({},r),{},{pointIndex:t}),s,n),u=a.subtract(o.pathOffset).transform(o.calcOwnMatrix()).subtract(h);return o.left-=u.x,o.top-=u.y,c},nG=t=>iO(V,nz(t,nH)),nN=(t,e,i)=>{let{path:r,pathOffset:s}=t,n=r[e];return new tn(n[i]-s.x,n[i+1]-s.y).transform(tw(t.getViewportTransform(),t.calcTransformMatrix()))};function nU(t,e,i){let{commandIndex:r,pointIndex:s}=this;return nN(i,r,s)}function nq(t,e,i,r){let{target:s}=e,{commandIndex:n,pointIndex:o}=this,a=((t,e,i,r,s)=>{let{path:n,pathOffset:o}=t,a=n[(r>0?r:n.length)-1],l=new tn(a[s],a[s+1]),h=l.subtract(o).transform(t.calcOwnMatrix()),c=ef(new tn(e,i),void 0,t.calcOwnMatrix());n[r][s]=c.x+o.x,n[r][s+1]=c.y+o.y,t.setDimensions();let u=l.subtract(t.pathOffset).transform(t.calcOwnMatrix()).subtract(h);return t.left-=u.x,t.top-=u.y,t.set("dirty",!0),!0})(s,i,r,n,o);return ev(this.actionName,l(l({},eS(t,e,i,r)),{},{commandIndex:n,pointIndex:o})),a}class nK extends iP{constructor(t){super(t)}render(t,e,i,r,s){let n=l(l({},r),{},{cornerColor:this.controlFill,cornerStrokeColor:this.controlStroke,transparentCorners:!this.controlFill});super.render(t,e,i,n,s)}}class nJ extends nK{constructor(t){super(t)}render(t,e,i,r,s){let{path:n}=s,{commandIndex:o,pointIndex:a,connectToCommandIndex:l,connectToPointIndex:h}=this;t.save(),t.strokeStyle=this.controlStroke,this.connectionDashArray&&t.setLineDash(this.connectionDashArray);let[c]=n[o],u=nN(s,l,h);if("Q"===c){let r=nN(s,o,a+2);t.moveTo(r.x,r.y),t.lineTo(e,i)}else t.moveTo(e,i);t.lineTo(u.x,u.y),t.stroke(),t.restore(),super.render(t,e,i,r,s)}}let nQ=(t,e,i,r,s,n)=>new(i?nJ:nK)(l(l({commandIndex:t,pointIndex:e,actionName:"modifyPath",positionHandler:nU,actionHandler:nq,connectToCommandIndex:s,connectToPointIndex:n},r),i?r.controlPointStyle:r.pointStyle));Object.freeze({__proto__:null,changeWidth:ik,createObjectDefaultControls:i0,createPathControls:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={},r="M";return t.path.forEach((t,s)=>{let n=t[0];switch("Z"!==n&&(i["c_".concat(s,"_").concat(n)]=nQ(s,t.length-2,!1,e)),n){case"C":let o;i["c_".concat(s,"_C_CP_1")]=nQ(s,1,!0,e,s-1,"C"===(o=r)?5:"Q"===o?3:1),i["c_".concat(s,"_C_CP_2")]=nQ(s,3,!0,e,s,5);break;case"Q":i["c_".concat(s,"_Q_CP_1")]=nQ(s,1,!0,e,s,3)}r=n}),i},createPolyActionHandler:nG,createPolyControls:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};for(let r=0;r<("number"==typeof t?t:t.points.length);r++)i["p".concat(r)]=new iP(l({actionName:V,positionHandler:nV(r),actionHandler:nG(r)},e));return i},createPolyPositionHandler:nV,createResizeControls:i1,createTextboxDefaultControls:i2,dragHandler:eO,factoryPolyActionHandler:nz,getLocalPoint:eT,polyActionHandler:nH,renderCircleControl:iM,renderSquareControl:iE,rotationStyleHandler:iA,rotationWithSnapping:ij,scaleCursorStyleHandler:iI,scaleOrSkewActionName:iJ,scaleSkewCursorStyleHandler:iQ,scalingEqually:iX,scalingX:iY,scalingXOrSkewingY:iZ,scalingY:iW,scalingYOrSkewingX:i$,skewCursorStyleHandler:iG,skewHandlerX:iU,skewHandlerY:iq,wrapWithFireEvent:iO,wrapWithFixedAnchor:iD});let nZ=t=>void 0!==t.webgl,n$="precision highp float",n0="\n ".concat(n$,";\n varying vec2 vTexCoord;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n }"),n1=["type"],n2=["type"],n5=RegExp(n$,"g");class n3{get type(){return this.constructor.type}constructor(){let t=h(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n1);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return n0}getVertexSource(){return"\n attribute vec2 aPosition;\n varying vec2 vTexCoord;\n void main() {\n vTexCoord = aPosition;\n gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n }"}createProgram(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.getFragmentSource(),i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.getVertexSource(),{WebGLProbe:{GLPrecision:r="highp"}}=y();"highp"!==r&&(e=e.replace(n5,n$.replace("highp",r)));let s=t.createShader(t.VERTEX_SHADER),n=t.createShader(t.FRAGMENT_SHADER),o=t.createProgram();if(!s||!n||!o)throw new f("Vertex, fragment shader or program creation error");if(t.shaderSource(s,i),t.compileShader(s),!t.getShaderParameter(s,t.COMPILE_STATUS))throw new f("Vertex shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(s)));if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new f("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(n)));if(t.attachShader(o,s),t.attachShader(o,n),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new f('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(o)));let a=this.getUniformLocations(t,o)||{};return a.uStepW=t.getUniformLocation(o,"uStepW"),a.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),uniformLocations:a}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){let i=this.constructor.uniformLocations,r={};for(let s=0;s1){let i=t.destinationWidth,r=t.destinationHeight;t.sourceWidth===i&&t.sourceHeight===r||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,i,r)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;let e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){nZ(t)?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){}getCacheKey(){return this.type}retrieveShader(t){let e=this.getCacheKey();return t.programCache[e]||(t.programCache[e]=this.createProgram(t.context)),t.programCache[e]}applyToWebGL(t){let e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){let{sourceWidth:e,sourceHeight:i}=t,r=tm({width:e,height:i});t.helpLayer=r}}toObject(){let t=Object.keys(this.constructor.defaults||{});return l({type:this.type},t.reduce((t,e)=>(t[e]=this[e],t),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(h(t,n2))}}o(n3,"type","BaseFilter"),o(n3,"uniformLocations",[]);let n4={multiply:"gl_FragColor.rgb *= uColor.rgb;\n",screen:"gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n",add:"gl_FragColor.rgb += uColor.rgb;\n",difference:"gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n",subtract:"gl_FragColor.rgb -= uColor.rgb;\n",lighten:"gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n",darken:"gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n",exclusion:"gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n",overlay:"\n if (uColor.r < 0.5) {\n gl_FragColor.r *= 2.0 * uColor.r;\n } else {\n gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n }\n if (uColor.g < 0.5) {\n gl_FragColor.g *= 2.0 * uColor.g;\n } else {\n gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n }\n if (uColor.b < 0.5) {\n gl_FragColor.b *= 2.0 * uColor.b;\n } else {\n gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n }\n ",tint:"\n gl_FragColor.rgb *= (1.0 - uColor.a);\n gl_FragColor.rgb += uColor.rgb;\n "};class n8 extends n3{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n gl_FragColor = color;\n if (color.a > 0.0) {\n ".concat(n4[this.mode],"\n }\n }\n ")}applyTo2d(t){let{imageData:{data:e}}=t,i=new tU(this.color).getSource(),r=this.alpha,s=i[0]*r,n=i[1]*r,o=i[2]*r,a=1-r;for(let t=0;tnew this(l(l({},s),{},{image:t})))}}o(n7,"type","BlendImage"),o(n7,"defaults",{mode:"multiply",alpha:1}),o(n7,"uniformLocations",["uTransformMatrix","uImage"]),$.setClass(n7);class ot extends n3{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n const float nSamples = 15.0;\n vec3 v3offset = vec3(12.9898, 78.233, 151.7182);\n float random(vec3 scale) {\n /* use the fragment position for a different seed per-pixel */\n return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n }\n void main() {\n vec4 color = vec4(0.0);\n float total = 0.0;\n float offset = random(v3offset);\n for (float t = -nSamples; t <= nSamples; t++) {\n float percent = (t + offset - 0.5) / nSamples;\n float weight = 1.0 - abs(percent);\n color += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\n total += weight;\n }\n gl_FragColor = color / total;\n }\n "}applyTo(t){nZ(t)?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){t.imageData=this.simpleBlur(t)}simpleBlur(t){let e,i,r,s,{ctx:n,imageData:o,filterBackend:{resources:a}}=t,{width:l,height:h}=o;a.blurLayer1||(a.blurLayer1=tf(),a.blurLayer2=tf());let c=a.blurLayer1,u=a.blurLayer2;c.width===l&&c.height===h||(u.width=c.width=l,u.height=c.height=h);let d=c.getContext("2d"),g=u.getContext("2d"),f=.06*this.blur*.5;for(d.putImageData(o,0,0),g.clearRect(0,0,l,h),s=-15;s<=15;s++)e=(Math.random()-.5)/4,r=f*(i=s/15)*l+e,g.globalAlpha=1-Math.abs(i),g.drawImage(c,r,e),d.drawImage(u,0,0),g.globalAlpha=1,g.clearRect(0,0,u.width,u.height);for(s=-15;s<=15;s++)e=(Math.random()-.5)/4,r=f*(i=s/15)*h+e,g.globalAlpha=1-Math.abs(i),g.drawImage(c,e,r),d.drawImage(u,0,0),g.globalAlpha=1,g.clearRect(0,0,u.width,u.height);n.drawImage(c,0,0);let p=n.getImageData(0,0,c.width,c.height);return d.globalAlpha=1,d.clearRect(0,0,c.width,c.height),p}sendUniformData(t,e){let i=this.chooseRightDelta();t.uniform2fv(e.uDelta,i)}isNeutralState(){return 0===this.blur}chooseRightDelta(){let t=1,e=[0,0];this.horizontal?this.aspectRatio>1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio);let i=t*this.blur*.12;return this.horizontal?e[0]=i:e[1]=i,e}}o(ot,"type","Blur"),o(ot,"defaults",{blur:0}),o(ot,"uniformLocations",["uDelta"]),$.setClass(ot);class oe extends n3{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uBrightness;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color.rgb += uBrightness;\n gl_FragColor = color;\n }\n"}applyTo2d(t){let{imageData:{data:e}}=t,i=Math.round(255*this.brightness);for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){nZ(t)&&(t.passes+=this.subFilters.length-1),this.subFilters.forEach(e=>{e.applyTo(t)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(t=>t.toObject())}}isNeutralState(){return!this.subFilters.some(t=>!t.isNeutralState())}static fromObject(t,e){return Promise.all((t.subFilters||[]).map(t=>$.getClass(t.type).fromObject(t,e))).then(t=>new this({subFilters:t}))}}o(od,"type","Composed"),$.setClass(od);class og extends n3{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uContrast;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\n color.rgb = contrastF * (color.rgb - 0.5) + 0.5;\n gl_FragColor = color;\n }"}isNeutralState(){return 0===this.contrast}applyTo2d(t){let{imageData:{data:e}}=t,i=Math.floor(255*this.contrast),r=259*(i+255)/(255*(259-i));for(let t=0;t=x||o<0||o>=y||(l=4*(a*y+o),h=m[g*v+d],e+=p[l]*h,i+=p[l+1]*h,r+=p[l+2]*h,S||(s+=p[l+3]*h));b[n]=e,b[n+1]=i,b[n+2]=r,b[n+3]=S?p[n+3]:s}t.imageData=C}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return l(l({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}o(op,"type","Convolute"),o(op,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),o(op,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),$.setClass(op);let om="Gamma";class ov extends n3{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec3 uGamma;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec3 correction = (1.0 / uGamma);\n color.r = pow(color.r, correction.r);\n color.g = pow(color.g, correction.g);\n color.b = pow(color.b, correction.b);\n gl_FragColor = color;\n gl_FragColor.rgb *= color.a;\n }\n"}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t,i=this.gamma,r=1/i[0],s=1/i[1],n=1/i[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});let o=this.rgbValues;for(let t=0;t<256;t++)o.r[t]=255*Math.pow(t/255,r),o.g[t]=255*Math.pow(t/255,s),o.b[t]=255*Math.pow(t/255,n);for(let t=0;ts[0]&&r>s[1]&&o>s[2]&&i"\n color += texture2D(uTexture, vTexCoord + ".concat(t,") * uTaps[").concat(e,"] + texture2D(uTexture, vTexCoord - ").concat(t,") * uTaps[").concat(e,"];\n sum += 2.0 * uTaps[").concat(e,"];\n ")).join("\n"),"\n gl_FragColor = color / sum;\n }\n ")}applyToForWebgl(t){t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,super.applyTo(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){nZ(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return 1===this.scaleX&&1===this.scaleY}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<11920929e-14&&e>-11920929e-14)return 1;let i=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(i)/i}}applyTo2d(t){let e;let i=t.imageData,r=this.scaleX,s=this.scaleY;this.rcpScaleX=1/r,this.rcpScaleY=1/s;let n=i.width,o=i.height,a=Math.round(n*r),l=Math.round(o*s);e="sliceHack"===this.resizeType?this.sliceByTwo(t,n,o,a,l):"hermite"===this.resizeType?this.hermiteFastResize(t,n,o,a,l):"bilinear"===this.resizeType?this.bilinearFiltering(t,n,o,a,l):"lanczos"===this.resizeType?this.lanczosResize(t,n,o,a,l):new ImageData(a,l),t.imageData=e}sliceByTwo(t,e,i,r,s){let n=t.imageData,o=!1,a=!1,l=.5*e,h=.5*i,c=t.filterBackend.resources,u=0,d=0,g=e,f=0;c.sliceByTwo||(c.sliceByTwo=tf());let p=c.sliceByTwo;(p.width<1.5*e||p.height=e)){p[k=Math.floor(1e3*Math.abs(x-m.x))]||(p[k]={});for(let t=v.y-f;t<=v.y+f;t++)t<0||t>=i||(M=Math.floor(1e3*Math.abs(t-m.y)),p[k][M]||(p[k][M]=l(Math.sqrt(Math.pow(k*u,2)+Math.pow(M*d,2))/1e3)),(C=p[k][M])>0&&(b=4*(t*e+x),S+=C,w+=C*n[b],T+=C*n[b+1],O+=C*n[b+2],D+=C*n[b+3]))}a[b=4*(y*r+_)]=w/S,a[b+1]=T/S,a[b+2]=O/S,a[b+3]=D/S}return++_1&&n<-1||(c=2*n*n*n-3*n*n+1)>0&&(v+=c*h[(i=4*(t+r*e))+3],g+=c,h[i+3]<255&&(c=c*h[i+3]/250),f+=c*h[i],p+=c*h[i+1],m+=c*h[i+2],d+=c)}}u[s]=f/d,u[s+1]=p/d,u[s+2]=m/d,u[s+3]=v/g}return c}}o(oO,"type","Resize"),o(oO,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),o(oO,"uniformLocations",["uDelta","uTaps"]),$.setClass(oO);class oD extends n3{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uSaturation;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float rgMax = max(color.r, color.g);\n float rgbMax = max(rgMax, color.b);\n color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\n color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\n color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\n gl_FragColor = color;\n }\n"}applyTo2d(t){let{imageData:{data:e}}=t,i=-this.saturation;for(let t=0;t{var r,l=t(7358),a=t(1507),o=t(2115),u=t(7650);function i(e){var n="https://react.dev/errors/"+e;if(1I||(e.current=R[I],R[I]=null,I--)}function j(e,n){R[++I]=e.current,e.current=n}var H=U(null),Q=U(null),$=U(null),B=U(null);function W(e,n){switch(j($,n),j(Q,e),j(H,null),n.nodeType){case 9:case 11:e=(e=n.documentElement)&&(e=e.namespaceURI)?si(e):0;break;default:if(e=n.tagName,n=n.namespaceURI)e=ss(n=si(n),e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}V(H),j(H,e)}function q(){V(H),V(Q),V($)}function K(e){null!==e.memoizedState&&j(B,e);var n=H.current,t=ss(n,e.type);n!==t&&(j(Q,e),j(H,t))}function Y(e){Q.current===e&&(V(H),V(Q)),B.current===e&&(V(B),sZ._currentValue=A)}var X=Object.prototype.hasOwnProperty,G=a.unstable_scheduleCallback,Z=a.unstable_cancelCallback,J=a.unstable_shouldYield,ee=a.unstable_requestPaint,en=a.unstable_now,et=a.unstable_getCurrentPriorityLevel,er=a.unstable_ImmediatePriority,el=a.unstable_UserBlockingPriority,ea=a.unstable_NormalPriority,eo=a.unstable_LowPriority,eu=a.unstable_IdlePriority,ei=a.log,es=a.unstable_setDisableYieldValue,ec=null,ef=null;function ed(e){if("function"==typeof ei&&es(e),ef&&"function"==typeof ef.setStrictMode)try{ef.setStrictMode(ec,e)}catch(e){}}var ep=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(em(e)/eh|0)|0},em=Math.log,eh=Math.LN2,eg=256,ey=4194304;function ev(e){var n=42&e;if(0!==n)return n;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194048&e;case 4194304:case 8388608:case 0x1000000:case 0x2000000:return 0x3c00000&e;case 0x4000000:return 0x4000000;case 0x8000000:return 0x8000000;case 0x10000000:return 0x10000000;case 0x20000000:return 0x20000000;case 0x40000000:return 0;default:return e}}function eb(e,n,t){var r=e.pendingLanes;if(0===r)return 0;var l=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var u=0x7ffffff&r;return 0!==u?0!=(r=u&~a)?l=ev(r):0!=(o&=u)?l=ev(o):t||0!=(t=u&~e)&&(l=ev(t)):0!=(u=r&~a)?l=ev(u):0!==o?l=ev(o):t||0!=(t=r&~e)&&(l=ev(t)),0===l?0:0!==n&&n!==l&&0==(n&a)&&((a=l&-l)>=(t=n&-n)||32===a&&0!=(4194048&t))?n:l}function ek(e,n){return 0==(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&n)}function ew(){var e=eg;return 0==(4194048&(eg<<=1))&&(eg=256),e}function eS(){var e=ey;return 0==(0x3c00000&(ey<<=1))&&(ey=4194304),e}function ex(e){for(var n=[],t=0;31>t;t++)n.push(e);return n}function eE(e,n){e.pendingLanes|=n,0x10000000!==n&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function eC(e,n,t){e.pendingLanes|=n,e.suspendedLanes&=~n;var r=31-ep(n);e.entangledLanes|=n,e.entanglements[r]=0x40000000|e.entanglements[r]|4194090&t}function ez(e,n){var t=e.entangledLanes|=n;for(e=e.entanglements;t;){var r=31-ep(t),l=1<)":-1l||i[r]!==s[l]){var c="\n"+i[r].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=r&&0<=l);break}}}finally{e2=!1,Error.prepareStackTrace=t}return(t=e?e.displayName||e.name:"")?e1(t):""}function e3(e){try{var n="";do n+=function(e){switch(e.tag){case 26:case 27:case 5:return e1(e.type);case 16:return e1("Lazy");case 13:return e1("Suspense");case 19:return e1("SuspenseList");case 0:case 15:return e4(e.type,!1);case 11:return e4(e.type.render,!1);case 1:return e4(e.type,!0);default:return""}}(e),e=e.return;while(e);return n}catch(e){return"\nError generating stack: "+e.message+"\n"+e.stack}}function e8(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function e6(e){var n=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===n||"radio"===n)}function e5(e){e._valueTracker||(e._valueTracker=function(e){var n=e6(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&void 0!==t&&"function"==typeof t.get&&"function"==typeof t.set){var l=t.get,a=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(e){r=""+e,a.call(this,e)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}(e))}function e9(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=e6(e)?e.checked?"true":"false":e.value),(e=r)!==t&&(n.setValue(e),!0)}function e7(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(n){return e.body}}var ne=/[\n"\\]/g;function nn(e){return e.replace(ne,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function nt(e,n,t,r,l,a,o,u){e.name="",null!=o&&"function"!=typeof o&&"symbol"!=typeof o&&"boolean"!=typeof o?e.type=o:e.removeAttribute("type"),null!=n?"number"===o?(0===n&&""===e.value||e.value!=n)&&(e.value=""+e8(n)):e.value!==""+e8(n)&&(e.value=""+e8(n)):"submit"!==o&&"reset"!==o||e.removeAttribute("value"),null!=n?nl(e,o,e8(n)):null!=t?nl(e,o,e8(t)):null!=r&&e.removeAttribute("value"),null==l&&null!=a&&(e.defaultChecked=!!a),null!=l&&(e.checked=l&&"function"!=typeof l&&"symbol"!=typeof l),null!=u&&"function"!=typeof u&&"symbol"!=typeof u&&"boolean"!=typeof u?e.name=""+e8(u):e.removeAttribute("name")}function nr(e,n,t,r,l,a,o,u){if(null!=a&&"function"!=typeof a&&"symbol"!=typeof a&&"boolean"!=typeof a&&(e.type=a),null!=n||null!=t){if(("submit"===a||"reset"===a)&&null==n)return;t=null!=t?""+e8(t):"",n=null!=n?""+e8(n):t,u||n===e.value||(e.value=n),e.defaultValue=n}r="function"!=typeof(r=null!=r?r:l)&&"symbol"!=typeof r&&!!r,e.checked=u?e.checked:!!r,e.defaultChecked=!!r,null!=o&&"function"!=typeof o&&"symbol"!=typeof o&&"boolean"!=typeof o&&(e.name=o)}function nl(e,n,t){"number"===n&&e7(e.ownerDocument)===e||e.defaultValue===""+t||(e.defaultValue=""+t)}function na(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l=te),tr=!1;function tl(e,n){switch(e){case"keyup":return -1!==n9.indexOf(n.keyCode);case"keydown":return 229!==n.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ta(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var to=!1,tu={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function ti(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===n?!!tu[e.type]:"textarea"===n}function ts(e,n,t,r){nv?nb?nb.push(r):nb=[r]:nv=r,0<(n=i3(n,"onChange")).length&&(t=new nj("onChange","change",null,t,r),e.push({event:t,listeners:n}))}var tc=null,tf=null;function td(e){iX(e,0)}function tp(e){if(e9(eH(e)))return e}function tm(e,n){if("change"===e)return n}var th=!1;if(nE){if(nE){var tg="oninput"in document;if(!tg){var ty=document.createElement("div");ty.setAttribute("oninput","return;"),tg="function"==typeof ty.oninput}r=tg}else r=!1;th=r&&(!document.documentMode||9=n)return{node:r,offset:n-e};e=t}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=tz(r)}}function tN(e){e=null!=e&&null!=e.ownerDocument&&null!=e.ownerDocument.defaultView?e.ownerDocument.defaultView:window;for(var n=e7(e.document);n instanceof e.HTMLIFrameElement;){try{var t="string"==typeof n.contentWindow.location.href}catch(e){t=!1}if(t)e=n.contentWindow;else break;n=e7(e.document)}return n}function tL(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&("input"===n&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===n||"true"===e.contentEditable)}var tT=nE&&"documentMode"in document&&11>=document.documentMode,t_=null,tF=null,tD=null,tM=!1;function tO(e,n,t){var r=t.window===t?t.document:9===t.nodeType?t:t.ownerDocument;tM||null==t_||t_!==e7(r)||(r="selectionStart"in(r=t_)&&tL(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},tD&&tC(tD,r)||(tD=r,0<(r=i3(tF,"onSelect")).length&&(n=new nj("onSelect","select",null,n,t),e.push({event:n,listeners:r}),n.target=t_)))}function tA(e,n){var t={};return t[e.toLowerCase()]=n.toLowerCase(),t["Webkit"+e]="webkit"+n,t["Moz"+e]="moz"+n,t}var tR={animationend:tA("Animation","AnimationEnd"),animationiteration:tA("Animation","AnimationIteration"),animationstart:tA("Animation","AnimationStart"),transitionrun:tA("Transition","TransitionRun"),transitionstart:tA("Transition","TransitionStart"),transitioncancel:tA("Transition","TransitionCancel"),transitionend:tA("Transition","TransitionEnd")},tI={},tU={};function tV(e){if(tI[e])return tI[e];if(!tR[e])return e;var n,t=tR[e];for(n in t)if(t.hasOwnProperty(n)&&n in tU)return tI[e]=t[n];return e}nE&&(tU=document.createElement("div").style,"AnimationEvent"in window||(delete tR.animationend.animation,delete tR.animationiteration.animation,delete tR.animationstart.animation),"TransitionEvent"in window||delete tR.transitionend.transition);var tj=tV("animationend"),tH=tV("animationiteration"),tQ=tV("animationstart"),t$=tV("transitionrun"),tB=tV("transitionstart"),tW=tV("transitioncancel"),tq=tV("transitionend"),tK=new Map,tY="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll scrollEnd toggle touchMove waiting wheel".split(" ");function tX(e,n){tK.set(e,n),eq(n,[e])}var tG=new WeakMap;function tZ(e,n){if("object"==typeof e&&null!==e){var t=tG.get(e);return void 0!==t?t:(n={value:e,source:n,stack:e3(n)},tG.set(e,n),n)}return{value:e,source:n,stack:e3(n)}}var tJ=[],t0=0,t1=0;function t2(){for(var e=t0,n=t1=t0=0;n>=o,l-=o,rq=1<<32-ep(n)+l|t<a?a:8;var o=M.T,u={};M.T=u,ax(e,!1,n,t);try{var i=l(),s=M.S;if(null!==s&&s(u,i),null!==i&&"object"==typeof i&&"function"==typeof i.then){var c,f,d=(c=[],f={status:"pending",value:null,reason:null,then:function(e){c.push(e)}},i.then(function(){f.status="fulfilled",f.value=r;for(var e=0;eh?(g=f,f=null):g=f.sibling;var y=p(l,f,u[h],i);if(null===y){null===f&&(f=g);break}e&&f&&null===y.alternate&&n(l,f),o=a(y,o,h),null===c?s=y:c.sibling=y,c=y,f=g}if(h===u.length)return t(l,f),ui&&rY(l,h),s;if(null===f){for(;hg?(y=h,h=null):y=h.sibling;var b=p(l,h,v.value,s);if(null===b){null===h&&(h=y);break}e&&h&&null===b.alternate&&n(l,h),o=a(b,o,g),null===f?c=b:f.sibling=b,f=b,h=y}if(v.done)return t(l,h),ui&&rY(l,g),c;if(null===h){for(;!v.done;g++,v=u.next())null!==(v=d(l,v.value,s))&&(o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return ui&&rY(l,g),c}for(h=r(h);!v.done;g++,v=u.next())null!==(v=m(h,l,g,v.value,s))&&(e&&null!==v.alternate&&h.delete(null===v.key?g:v.key),o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return e&&h.forEach(function(e){return n(l,e)}),ui&&rY(l,g),c}(s,c,f=b.call(f),v)}if("function"==typeof f.then)return u(s,c,aD(f),v);if(f.$$typeof===S)return u(s,c,rc(s,f),v);aO(s,f)}return"string"==typeof f&&""!==f||"number"==typeof f||"bigint"==typeof f?(f=""+f,null!==c&&6===c.tag?(t(s,c.sibling),(v=l(c,f)).return=s):(t(s,c),(v=ul(f,s.mode,v)).return=s),o(s=v)):t(s,c)}(u,s,c,f);return a_=null,v}catch(e){if(e===rJ||e===r1)throw e;var b=o5(29,e,null,u.mode);return b.lanes=f,b.return=u,b}finally{}}}var aI=aR(!0),aU=aR(!1),aV=U(null),aj=null;function aH(e){var n=e.alternate;j(aW,1&aW.current),j(aV,e),null===aj&&(null===n||null!==r7.current?aj=e:null!==n.memoizedState&&(aj=e))}function aQ(e){if(22===e.tag){if(j(aW,aW.current),j(aV,e),null===aj){var n=e.alternate;null!==n&&null!==n.memoizedState&&(aj=e)}}else a$(e)}function a$(){j(aW,aW.current),j(aV,aV.current)}function aB(e){V(aV),aj===e&&(aj=null),V(aW)}var aW=U(0);function aq(e){for(var n=e;null!==n;){if(13===n.tag){var t=n.memoizedState;if(null!==t&&(null===(t=t.dehydrated)||"$?"===t.data||sk(t)))return n}else if(19===n.tag&&void 0!==n.memoizedProps.revealOrder){if(0!=(128&n.flags))return n}else if(null!==n.child){n.child.return=n,n=n.child;continue}if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}var aK="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var n=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(n))return}else if("object"==typeof l&&"function"==typeof l.emit){l.emit("uncaughtException",e);return}console.error(e)};function aY(e){aK(e)}function aX(e){console.error(e)}function aG(e){aK(e)}function aZ(e,n){try{(0,e.onUncaughtError)(n.value,{componentStack:n.stack})}catch(e){setTimeout(function(){throw e})}}function aJ(e,n,t){try{(0,e.onCaughtError)(t.value,{componentStack:t.stack,errorBoundary:1===n.tag?n.stateNode:null})}catch(e){setTimeout(function(){throw e})}}function a0(e,n,t){return(t=rk(t)).tag=3,t.payload={element:null},t.callback=function(){aZ(e,n)},t}function a1(e){return(e=rk(e)).tag=3,e}function a2(e,n,t,r){var l=t.type.getDerivedStateFromError;if("function"==typeof l){var a=r.value;e.payload=function(){return l(a)},e.callback=function(){aJ(n,t,r)}}var o=t.stateNode;null!==o&&"function"==typeof o.componentDidCatch&&(e.callback=function(){aJ(n,t,r),"function"!=typeof l&&(null===uY?uY=new Set([this]):uY.add(this));var e=r.stack;this.componentDidCatch(r.value,{componentStack:null!==e?e:""})})}var a4=Error(i(461)),a3=!1;function a8(e,n,t,r){n.child=null===e?aU(n,null,t,r):aI(n,e.child,t,r)}function a6(e,n,t,r,l){t=t.render;var a=n.ref;if("ref"in r){var o={};for(var u in r)"ref"!==u&&(o[u]=r[u])}else o=r;return(ri(n),r=lS(e,n,t,o,a,l),u=lz(),null===e||a3)?(ui&&u&&rG(n),n.flags|=1,a8(e,n,r,l),n.child):(lP(e,n,l),og(e,n,l))}function a5(e,n,t,r,l){if(null===e){var a=t.type;return"function"!=typeof a||o9(a)||void 0!==a.defaultProps||null!==t.compare?((e=un(t.type,null,r,n,n.mode,l)).ref=n.ref,e.return=n,n.child=e):(n.tag=15,n.type=a,a9(e,n,a,r,l))}if(a=e.child,!oy(e,l)){var o=a.memoizedProps;if((t=null!==(t=t.compare)?t:tC)(o,r)&&e.ref===n.ref)return og(e,n,l)}return n.flags|=1,(e=o7(a,r)).ref=n.ref,e.return=n,n.child=e}function a9(e,n,t,r,l){if(null!==e){var a=e.memoizedProps;if(tC(a,r)&&e.ref===n.ref){if(a3=!1,n.pendingProps=r=a,!oy(e,l))return n.lanes=e.lanes,og(e,n,l);0!=(131072&e.flags)&&(a3=!0)}}return ot(e,n,t,r,l)}function a7(e,n,t){var r=n.pendingProps,l=r.children,a=0!=(2&n.stateNode._pendingVisibility),o=null!==e?e.memoizedState:null;if(on(e,n),"hidden"===r.mode||a){if(0!=(128&n.flags)){if(r=null!==o?o.baseLanes|t:t,null!==e){for(a=0,l=n.child=e.child;null!==l;)a=a|l.lanes|l.childLanes,l=l.sibling;n.childLanes=a&~r}else n.childLanes=0,n.child=null;return oe(e,n,r,t)}if(0==(0x20000000&t))return n.lanes=n.childLanes=0x20000000,oe(e,n,null!==o?o.baseLanes|t:t,t);n.memoizedState={baseLanes:0,cachePool:null},null!==e&&lu(n,null!==o?o.cachePool:null),null!==o?ln(n,o):lt(),aQ(n)}else null!==o?(lu(n,o.cachePool),ln(n,o),a$(n),n.memoizedState=null):(null!==e&&lu(n,null),lt(),a$(n));return a8(e,n,l,t),n.child}function oe(e,n,t,r){var l=lo();return l=null===l?null:{parent:rF._currentValue,pool:l},n.memoizedState={baseLanes:t,cachePool:l},null!==e&&lu(n,null),lt(),aQ(n),null!==e&&ro(e,n,r,!0),null}function on(e,n){var t=n.ref;if(null===t)null!==e&&null!==e.ref&&(n.flags|=4194816);else{if("function"!=typeof t&&"object"!=typeof t)throw Error(i(284));(null===e||e.ref!==t)&&(n.flags|=4194816)}}function ot(e,n,t,r,l){return(ri(n),t=lS(e,n,t,r,void 0,l),r=lz(),null===e||a3)?(ui&&r&&rG(n),n.flags|=1,a8(e,n,t,l),n.child):(lP(e,n,l),og(e,n,l))}function or(e,n,t,r,l,a){return(ri(n),n.updateQueue=null,t=lE(n,r,t,l),lx(e),r=lz(),null===e||a3)?(ui&&r&&rG(n),n.flags|=1,a8(e,n,t,a),n.child):(lP(e,n,a),og(e,n,a))}function ol(e,n,t,r,l){if(ri(n),null===n.stateNode){var a=t9,o=t.contextType;"object"==typeof o&&null!==o&&(a=rs(o)),a=new t(r,a),n.memoizedState=null!==a.state&&void 0!==a.state?a.state:null,a.updater=rA,n.stateNode=a,a._reactInternals=n,(a=n.stateNode).props=r,a.state=n.memoizedState,a.refs={},rv(n),o=t.contextType,a.context="object"==typeof o&&null!==o?rs(o):t9,a.state=n.memoizedState,"function"==typeof(o=t.getDerivedStateFromProps)&&(rO(n,t,o,r),a.state=n.memoizedState),"function"==typeof t.getDerivedStateFromProps||"function"==typeof a.getSnapshotBeforeUpdate||"function"!=typeof a.UNSAFE_componentWillMount&&"function"!=typeof a.componentWillMount||(o=a.state,"function"==typeof a.componentWillMount&&a.componentWillMount(),"function"==typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),o!==a.state&&rA.enqueueReplaceState(a,a.state,null),rz(n,r,a,l),rC(),a.state=n.memoizedState),"function"==typeof a.componentDidMount&&(n.flags|=4194308),r=!0}else if(null===e){a=n.stateNode;var u=n.memoizedProps,i=rU(t,u);a.props=i;var s=a.context,c=t.contextType;o=t9,"object"==typeof c&&null!==c&&(o=rs(c));var f=t.getDerivedStateFromProps;c="function"==typeof f||"function"==typeof a.getSnapshotBeforeUpdate,u=n.pendingProps!==u,c||"function"!=typeof a.UNSAFE_componentWillReceiveProps&&"function"!=typeof a.componentWillReceiveProps||(u||s!==o)&&rI(n,a,r,o),ry=!1;var d=n.memoizedState;a.state=d,rz(n,r,a,l),rC(),s=n.memoizedState,u||d!==s||ry?("function"==typeof f&&(rO(n,t,f,r),s=n.memoizedState),(i=ry||rR(n,t,i,r,d,s,o))?(c||"function"!=typeof a.UNSAFE_componentWillMount&&"function"!=typeof a.componentWillMount||("function"==typeof a.componentWillMount&&a.componentWillMount(),"function"==typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount()),"function"==typeof a.componentDidMount&&(n.flags|=4194308)):("function"==typeof a.componentDidMount&&(n.flags|=4194308),n.memoizedProps=r,n.memoizedState=s),a.props=r,a.state=s,a.context=o,r=i):("function"==typeof a.componentDidMount&&(n.flags|=4194308),r=!1)}else{a=n.stateNode,rb(e,n),c=rU(t,o=n.memoizedProps),a.props=c,f=n.pendingProps,d=a.context,s=t.contextType,i=t9,"object"==typeof s&&null!==s&&(i=rs(s)),(s="function"==typeof(u=t.getDerivedStateFromProps)||"function"==typeof a.getSnapshotBeforeUpdate)||"function"!=typeof a.UNSAFE_componentWillReceiveProps&&"function"!=typeof a.componentWillReceiveProps||(o!==f||d!==i)&&rI(n,a,r,i),ry=!1,d=n.memoizedState,a.state=d,rz(n,r,a,l),rC();var p=n.memoizedState;o!==f||d!==p||ry||null!==e&&null!==e.dependencies&&ru(e.dependencies)?("function"==typeof u&&(rO(n,t,u,r),p=n.memoizedState),(c=ry||rR(n,t,c,r,d,p,i)||null!==e&&null!==e.dependencies&&ru(e.dependencies))?(s||"function"!=typeof a.UNSAFE_componentWillUpdate&&"function"!=typeof a.componentWillUpdate||("function"==typeof a.componentWillUpdate&&a.componentWillUpdate(r,p,i),"function"==typeof a.UNSAFE_componentWillUpdate&&a.UNSAFE_componentWillUpdate(r,p,i)),"function"==typeof a.componentDidUpdate&&(n.flags|=4),"function"==typeof a.getSnapshotBeforeUpdate&&(n.flags|=1024)):("function"!=typeof a.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=4),"function"!=typeof a.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=1024),n.memoizedProps=r,n.memoizedState=p),a.props=r,a.state=p,a.context=i,r=c):("function"!=typeof a.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=4),"function"!=typeof a.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=1024),r=!1)}return a=r,on(e,n),r=0!=(128&n.flags),a||r?(a=n.stateNode,t=r&&"function"!=typeof t.getDerivedStateFromError?null:a.render(),n.flags|=1,null!==e&&r?(n.child=aI(n,e.child,null,l),n.child=aI(n,null,t,l)):a8(e,n,t,l),n.memoizedState=a.state,e=n.child):e=og(e,n,l),e}function oa(e,n,t,r){return ug(),n.flags|=256,a8(e,n,t,r),n.child}var oo={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function ou(e){return{baseLanes:e,cachePool:li()}}function oi(e,n,t){return e=null!==e?e.childLanes&~t:0,n&&(e|=uj),e}function os(e,n,t){var r,l=n.pendingProps,a=!1,o=0!=(128&n.flags);if((r=o)||(r=(null===e||null!==e.memoizedState)&&0!=(2&aW.current)),r&&(a=!0,n.flags&=-129),r=0!=(32&n.flags),n.flags&=-33,null===e){if(ui){if(a?aH(n):a$(n),ui){var u,s=uu;if(u=s){t:{for(u=s,s=uc;8!==u.nodeType;)if(!s||null===(u=sw(u.nextSibling))){s=null;break t}s=u}null!==s?(n.memoizedState={dehydrated:s,treeContext:null!==rW?{id:rq,overflow:rK}:null,retryLane:0x20000000,hydrationErrors:null},(u=o5(18,null,null,0)).stateNode=s,u.return=n,n.child=u,uo=n,uu=null,u=!0):u=!1}u||ud(n)}if(null!==(s=n.memoizedState)&&null!==(s=s.dehydrated))return sk(s)?n.lanes=32:n.lanes=0x20000000,null;aB(n)}return(s=l.children,l=l.fallback,a)?(a$(n),s=of({mode:"hidden",children:s},a=n.mode),l=ut(l,a,t,null),s.return=n,l.return=n,s.sibling=l,n.child=s,(a=n.child).memoizedState=ou(t),a.childLanes=oi(e,r,t),n.memoizedState=oo,l):(aH(n),oc(n,s))}if(null!==(u=e.memoizedState)&&null!==(s=u.dehydrated)){if(o)256&n.flags?(aH(n),n.flags&=-257,n=od(e,n,t)):null!==n.memoizedState?(a$(n),n.child=e.child,n.flags|=128,n=null):(a$(n),a=l.fallback,s=n.mode,l=of({mode:"visible",children:l.children},s),a=ut(a,s,t,null),a.flags|=2,l.return=n,a.return=n,l.sibling=a,n.child=l,aI(n,e.child,null,t),(l=n.child).memoizedState=ou(t),l.childLanes=oi(e,r,t),n.memoizedState=oo,n=a);else if(aH(n),sk(s)){if(r=s.nextSibling&&s.nextSibling.dataset)var c=r.dgst;r=c,(l=Error(i(419))).stack="",l.digest=r,uv({value:l,source:null,stack:null}),n=od(e,n,t)}else if(a3||ro(e,n,t,!1),r=0!=(t&e.childLanes),a3||r){if(null!==(r=uN)&&0!==(l=0!=((l=0!=(42&(l=t&-t))?1:eP(l))&(r.suspendedLanes|t))?0:l)&&l!==u.retryLane)throw u.retryLane=l,t8(e,l),u5(r,e,l),a4;"$?"===s.data||ii(),n=od(e,n,t)}else"$?"===s.data?(n.flags|=192,n.child=e.child,n=null):(e=u.treeContext,uu=sw(s.nextSibling),uo=n,ui=!0,us=null,uc=!1,null!==e&&(r$[rB++]=rq,r$[rB++]=rK,r$[rB++]=rW,rq=e.id,rK=e.overflow,rW=n),n=oc(n,l.children),n.flags|=4096);return n}return a?(a$(n),a=l.fallback,s=n.mode,c=(u=e.child).sibling,(l=o7(u,{mode:"hidden",children:l.children})).subtreeFlags=0x3e00000&u.subtreeFlags,null!==c?a=o7(c,a):(a=ut(a,s,t,null),a.flags|=2),a.return=n,l.return=n,l.sibling=a,n.child=l,l=a,a=n.child,null===(s=e.child.memoizedState)?s=ou(t):(null!==(u=s.cachePool)?(c=rF._currentValue,u=u.parent!==c?{parent:c,pool:c}:u):u=li(),s={baseLanes:s.baseLanes|t,cachePool:u}),a.memoizedState=s,a.childLanes=oi(e,r,t),n.memoizedState=oo,l):(aH(n),e=(t=e.child).sibling,(t=o7(t,{mode:"visible",children:l.children})).return=n,t.sibling=null,null!==e&&(null===(r=n.deletions)?(n.deletions=[e],n.flags|=16):r.push(e)),n.child=t,n.memoizedState=null,t)}function oc(e,n){return(n=of({mode:"visible",children:n},e.mode)).return=e,e.child=n}function of(e,n){return ur(e,n,0,null)}function od(e,n,t){return aI(n,e.child,null,t),e=oc(n,n.pendingProps.children),e.flags|=2,n.memoizedState=null,e}function op(e,n,t){e.lanes|=n;var r=e.alternate;null!==r&&(r.lanes|=n),rl(e.return,n,t)}function om(e,n,t,r,l){var a=e.memoizedState;null===a?e.memoizedState={isBackwards:n,rendering:null,renderingStartTime:0,last:r,tail:t,tailMode:l}:(a.isBackwards=n,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=t,a.tailMode=l)}function oh(e,n,t){var r=n.pendingProps,l=r.revealOrder,a=r.tail;if(a8(e,n,r.children,t),0!=(2&(r=aW.current)))r=1&r|2,n.flags|=128;else{if(null!==e&&0!=(128&e.flags))e:for(e=n.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&op(e,t,n);else if(19===e.tag)op(e,t,n);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===n)break;for(;null===e.sibling;){if(null===e.return||e.return===n)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}switch(j(aW,r),l){case"forwards":for(l=null,t=n.child;null!==t;)null!==(e=t.alternate)&&null===aq(e)&&(l=t),t=t.sibling;null===(t=l)?(l=n.child,n.child=null):(l=t.sibling,t.sibling=null),om(n,!1,l,t,a);break;case"backwards":for(t=null,l=n.child,n.child=null;null!==l;){if(null!==(e=l.alternate)&&null===aq(e)){n.child=l;break}e=l.sibling,l.sibling=t,t=l,l=e}om(n,!0,t,null,a);break;case"together":om(n,!1,null,null,void 0);break;default:n.memoizedState=null}return n.child}function og(e,n,t){if(null!==e&&(n.dependencies=e.dependencies),uI|=n.lanes,0==(t&n.childLanes)){if(null===e)return null;if(ro(e,n,t,!1),0==(t&n.childLanes))return null}if(null!==e&&n.child!==e.child)throw Error(i(153));if(null!==n.child){for(t=o7(e=n.child,e.pendingProps),n.child=t,t.return=n;null!==e.sibling;)e=e.sibling,(t=t.sibling=o7(e,e.pendingProps)).return=n;t.sibling=null}return n.child}function oy(e,n){return 0!=(e.lanes&n)||!!(null!==(e=e.dependencies)&&ru(e))}function ov(e,n,t){if(null!==e){if(e.memoizedProps!==n.pendingProps)a3=!0;else{if(!oy(e,t)&&0==(128&n.flags))return a3=!1,function(e,n,t){switch(n.tag){case 3:W(n,n.stateNode.containerInfo),rt(n,rF,e.memoizedState.cache),ug();break;case 27:case 5:K(n);break;case 4:W(n,n.stateNode.containerInfo);break;case 10:rt(n,n.type,n.memoizedProps.value);break;case 13:var r=n.memoizedState;if(null!==r){if(null!==r.dehydrated)return aH(n),n.flags|=128,null;if(0!=(t&n.child.childLanes))return os(e,n,t);return aH(n),null!==(e=og(e,n,t))?e.sibling:null}aH(n);break;case 19:var l=0!=(128&e.flags);if((r=0!=(t&n.childLanes))||(ro(e,n,t,!1),r=0!=(t&n.childLanes)),l){if(r)return oh(e,n,t);n.flags|=128}if(null!==(l=n.memoizedState)&&(l.rendering=null,l.tail=null,l.lastEffect=null),j(aW,aW.current),!r)return null;break;case 22:case 23:return n.lanes=0,a7(e,n,t);case 24:rt(n,rF,e.memoizedState.cache)}return og(e,n,t)}(e,n,t);a3=0!=(131072&e.flags)}}else a3=!1,ui&&0!=(1048576&n.flags)&&rX(n,rQ,n.index);switch(n.lanes=0,n.tag){case 16:e:{e=n.pendingProps;var r=n.elementType,l=r._init;if(r=l(r._payload),n.type=r,"function"==typeof r)o9(r)?(e=rU(r,e),n.tag=1,n=ol(null,n,r,e,t)):(n.tag=0,n=ot(null,n,r,e,t));else{if(null!=r){if((l=r.$$typeof)===x){n.tag=11,n=a6(null,n,r,e,t);break e}if(l===z){n.tag=14,n=a5(null,n,r,e,t);break e}}throw Error(i(306,n=function e(n){if(null==n)return null;if("function"==typeof n)return n.$$typeof===F?null:n.displayName||n.name||null;if("string"==typeof n)return n;switch(n){case y:return"Fragment";case g:return"Portal";case b:return"Profiler";case v:return"StrictMode";case E:return"Suspense";case C:return"SuspenseList"}if("object"==typeof n)switch(n.$$typeof){case S:return(n.displayName||"Context")+".Provider";case w:return(n._context.displayName||"Context")+".Consumer";case x:var t=n.render;return(n=n.displayName)||(n=""!==(n=t.displayName||t.name||"")?"ForwardRef("+n+")":"ForwardRef"),n;case z:return null!==(t=n.displayName||null)?t:e(n.type)||"Memo";case P:t=n._payload,n=n._init;try{return e(n(t))}catch(e){}}return null}(r)||r,""))}}return n;case 0:return ot(e,n,n.type,n.pendingProps,t);case 1:return l=rU(r=n.type,n.pendingProps),ol(e,n,r,l,t);case 3:e:{if(W(n,n.stateNode.containerInfo),null===e)throw Error(i(387));r=n.pendingProps;var a=n.memoizedState;l=a.element,rb(e,n),rz(n,r,null,t);var o=n.memoizedState;if(rt(n,rF,r=o.cache),r!==a.cache&&ra(n,[rF],t,!0),rC(),r=o.element,a.isDehydrated){if(a={element:r,isDehydrated:!1,cache:o.cache},n.updateQueue.baseState=a,n.memoizedState=a,256&n.flags){n=oa(e,n,r,t);break e}if(r!==l){uv(l=tZ(Error(i(424)),n)),n=oa(e,n,r,t);break e}else for(uu=sw((e=9===(e=n.stateNode.containerInfo).nodeType?e.body:"HTML"===e.nodeName?e.ownerDocument.body:e).firstChild),uo=n,ui=!0,us=null,uc=!0,t=aU(n,null,r,t),n.child=t;t;)t.flags=-3&t.flags|4096,t=t.sibling}else{if(ug(),r===l){n=og(e,n,t);break e}a8(e,n,r,t)}n=n.child}return n;case 26:return on(e,n),null===e?(t=sF(n.type,null,n.pendingProps,null))?n.memoizedState=t:ui||(t=n.type,e=n.pendingProps,(r=su($.current).createElement(t))[e_]=n,r[eF]=e,sl(r,t,e),e$(r),n.stateNode=r):n.memoizedState=sF(n.type,e.memoizedProps,n.pendingProps,e.memoizedState),null;case 27:return K(n),null===e&&ui&&(r=n.stateNode=sE(n.type,n.pendingProps,$.current),uo=n,uc=!0,l=uu,sy(n.type)?(sS=l,uu=sw(r.firstChild)):uu=l),a8(e,n,n.pendingProps.children,t),on(e,n),null===e&&(n.flags|=4194304),n.child;case 5:return null===e&&ui&&((l=!(r=uu))||(null!==(r=function(e,n,t,r){for(;1===e.nodeType;){if(e.nodeName.toLowerCase()!==n.toLowerCase()){if(!r&&("INPUT"!==e.nodeName||"hidden"!==e.type))break}else if(r){if(!e[eI])switch(n){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if("stylesheet"===(l=e.getAttribute("rel"))&&e.hasAttribute("data-precedence")||l!==t.rel||e.getAttribute("href")!==(null==t.href||""===t.href?null:t.href)||e.getAttribute("crossorigin")!==(null==t.crossOrigin?null:t.crossOrigin)||e.getAttribute("title")!==(null==t.title?null:t.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(((l=e.getAttribute("src"))!==(null==t.src?null:t.src)||e.getAttribute("type")!==(null==t.type?null:t.type)||e.getAttribute("crossorigin")!==(null==t.crossOrigin?null:t.crossOrigin))&&l&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else{if("input"!==n||"hidden"!==e.type)return e;var l=null==t.name?null:""+t.name;if("hidden"===t.type&&e.getAttribute("name")===l)return e}if(null===(e=sw(e.nextSibling)))break}return null}(r,n.type,n.pendingProps,uc))?(n.stateNode=r,uo=n,uu=sw(r.firstChild),uc=!1,r=!0):r=!1,l=!r),l&&ud(n)),K(n),l=n.type,a=n.pendingProps,o=null!==e?e.memoizedProps:null,r=a.children,sc(l,a)?r=null:null!==o&&sc(l,o)&&(n.flags|=32),null!==n.memoizedState&&(l=lS(e,n,lC,null,null,t),sZ._currentValue=l),on(e,n),a8(e,n,r,t),n.child;case 6:return null===e&&ui&&((e=!(t=uu))||(null!==(t=function(e,n,t){if(""===n)return null;for(;3!==e.nodeType;)if((1!==e.nodeType||"INPUT"!==e.nodeName||"hidden"!==e.type)&&!t||null===(e=sw(e.nextSibling)))return null;return e}(t,n.pendingProps,uc))?(n.stateNode=t,uo=n,uu=null,t=!0):t=!1,e=!t),e&&ud(n)),null;case 13:return os(e,n,t);case 4:return W(n,n.stateNode.containerInfo),r=n.pendingProps,null===e?n.child=aI(n,null,r,t):a8(e,n,r,t),n.child;case 11:return a6(e,n,n.type,n.pendingProps,t);case 7:return a8(e,n,n.pendingProps,t),n.child;case 8:case 12:return a8(e,n,n.pendingProps.children,t),n.child;case 10:return r=n.pendingProps,rt(n,n.type,r.value),a8(e,n,r.children,t),n.child;case 9:return l=n.type._context,r=n.pendingProps.children,ri(n),r=r(l=rs(l)),n.flags|=1,a8(e,n,r,t),n.child;case 14:return a5(e,n,n.type,n.pendingProps,t);case 15:return a9(e,n,n.type,n.pendingProps,t);case 19:return oh(e,n,t);case 22:return a7(e,n,t);case 24:return ri(n),r=rs(rF),null===e?(null===(l=lo())&&(l=uN,a=rD(),l.pooledCache=a,a.refCount++,null!==a&&(l.pooledCacheLanes|=t),l=a),n.memoizedState={parent:r,cache:l},rv(n),rt(n,rF,l)):(0!=(e.lanes&t)&&(rb(e,n),rz(n,null,null,t),rC()),l=e.memoizedState,a=n.memoizedState,l.parent!==r?(l={parent:r,cache:r},n.memoizedState=l,0===n.lanes&&(n.memoizedState=n.updateQueue.baseState=l),rt(n,rF,r)):(rt(n,rF,r=a.cache),r!==l.cache&&ra(n,[rF],t,!0))),a8(e,n,n.pendingProps.children,t),n.child;case 29:throw n.pendingProps}throw Error(i(156,n.tag))}function ob(e,n){try{var t=n.updateQueue,r=null!==t?t.lastEffect:null;if(null!==r){var l=r.next;t=l;do{if((t.tag&e)===e){r=void 0;var a=t.create,o=t.inst;r=a(),o.destroy=r}t=t.next}while(t!==l)}}catch(e){iE(n,n.return,e)}}function ok(e,n,t){try{var r=n.updateQueue,l=null!==r?r.lastEffect:null;if(null!==l){var a=l.next;r=a;do{if((r.tag&e)===e){var o=r.inst,u=o.destroy;if(void 0!==u){o.destroy=void 0,l=n;try{u()}catch(e){iE(l,t,e)}}}r=r.next}while(r!==a)}}catch(e){iE(n,n.return,e)}}function ow(e){var n=e.updateQueue;if(null!==n){var t=e.stateNode;try{rN(n,t)}catch(n){iE(e,e.return,n)}}}function oS(e,n,t){t.props=rU(e.type,e.memoizedProps),t.state=e.memoizedState;try{t.componentWillUnmount()}catch(t){iE(e,n,t)}}function ox(e,n){try{var t=e.ref;if(null!==t){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;default:r=e.stateNode}"function"==typeof t?e.refCleanup=t(r):t.current=r}}catch(t){iE(e,n,t)}}function oE(e,n){var t=e.ref,r=e.refCleanup;if(null!==t){if("function"==typeof r)try{r()}catch(t){iE(e,n,t)}finally{e.refCleanup=null,null!=(e=e.alternate)&&(e.refCleanup=null)}else if("function"==typeof t)try{t(null)}catch(t){iE(e,n,t)}else t.current=null}}function oC(e){var n=e.type,t=e.memoizedProps,r=e.stateNode;try{switch(n){case"button":case"input":case"select":case"textarea":t.autoFocus&&r.focus();break;case"img":t.src?r.src=t.src:t.srcSet&&(r.srcset=t.srcSet)}}catch(n){iE(e,e.return,n)}}function oz(e,n,t){try{var r=e.stateNode;(function(e,n,t,r){switch(n){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var l=null,a=null,o=null,u=null,s=null,c=null,f=null;for(m in t){var d=t[m];if(t.hasOwnProperty(m)&&null!=d)switch(m){case"checked":case"value":break;case"defaultValue":s=d;default:r.hasOwnProperty(m)||st(e,n,m,null,r,d)}}for(var p in r){var m=r[p];if(d=t[p],r.hasOwnProperty(p)&&(null!=m||null!=d))switch(p){case"type":a=m;break;case"name":l=m;break;case"checked":c=m;break;case"defaultChecked":f=m;break;case"value":o=m;break;case"defaultValue":u=m;break;case"children":case"dangerouslySetInnerHTML":if(null!=m)throw Error(i(137,n));break;default:m!==d&&st(e,n,p,m,r,d)}}nt(e,o,u,s,c,f,a,l);return;case"select":for(a in m=o=u=p=null,t)if(s=t[a],t.hasOwnProperty(a)&&null!=s)switch(a){case"value":break;case"multiple":m=s;default:r.hasOwnProperty(a)||st(e,n,a,null,r,s)}for(l in r)if(a=r[l],s=t[l],r.hasOwnProperty(l)&&(null!=a||null!=s))switch(l){case"value":p=a;break;case"defaultValue":u=a;break;case"multiple":o=a;default:a!==s&&st(e,n,l,a,r,s)}n=u,t=o,r=m,null!=p?na(e,!!t,p,!1):!!r!=!!t&&(null!=n?na(e,!!t,n,!0):na(e,!!t,t?[]:"",!1));return;case"textarea":for(u in m=p=null,t)if(l=t[u],t.hasOwnProperty(u)&&null!=l&&!r.hasOwnProperty(u))switch(u){case"value":case"children":break;default:st(e,n,u,null,r,l)}for(o in r)if(l=r[o],a=t[o],r.hasOwnProperty(o)&&(null!=l||null!=a))switch(o){case"value":p=l;break;case"defaultValue":m=l;break;case"children":break;case"dangerouslySetInnerHTML":if(null!=l)throw Error(i(91));break;default:l!==a&&st(e,n,o,l,r,a)}no(e,p,m);return;case"option":for(var h in t)p=t[h],t.hasOwnProperty(h)&&null!=p&&!r.hasOwnProperty(h)&&("selected"===h?e.selected=!1:st(e,n,h,null,r,p));for(s in r)p=r[s],m=t[s],r.hasOwnProperty(s)&&p!==m&&(null!=p||null!=m)&&("selected"===s?e.selected=p&&"function"!=typeof p&&"symbol"!=typeof p:st(e,n,s,p,r,m));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var g in t)p=t[g],t.hasOwnProperty(g)&&null!=p&&!r.hasOwnProperty(g)&&st(e,n,g,null,r,p);for(c in r)if(p=r[c],m=t[c],r.hasOwnProperty(c)&&p!==m&&(null!=p||null!=m))switch(c){case"children":case"dangerouslySetInnerHTML":if(null!=p)throw Error(i(137,n));break;default:st(e,n,c,p,r,m)}return;default:if(nd(n)){for(var y in t)p=t[y],t.hasOwnProperty(y)&&void 0!==p&&!r.hasOwnProperty(y)&&sr(e,n,y,void 0,r,p);for(f in r)p=r[f],m=t[f],r.hasOwnProperty(f)&&p!==m&&(void 0!==p||void 0!==m)&&sr(e,n,f,p,r,m);return}}for(var v in t)p=t[v],t.hasOwnProperty(v)&&null!=p&&!r.hasOwnProperty(v)&&st(e,n,v,null,r,p);for(d in r)p=r[d],m=t[d],r.hasOwnProperty(d)&&p!==m&&(null!=p||null!=m)&&st(e,n,d,p,r,m)})(r,e.type,t,n),r[eF]=n}catch(n){iE(e,e.return,n)}}function oP(e){return 5===e.tag||3===e.tag||26===e.tag||27===e.tag&&sy(e.type)||4===e.tag}function oN(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||oP(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(27===e.tag&&sy(e.type)||2&e.flags||null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function oL(e,n,t){var r=e.tag;if(5===r||6===r)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(4!==r&&(27===r&&sy(e.type)&&(t=e.stateNode),null!==(e=e.child)))for(oL(e,n,t),e=e.sibling;null!==e;)oL(e,n,t),e=e.sibling}function oT(e){var n=e.stateNode,t=e.memoizedProps;try{for(var r=e.type,l=n.attributes;l.length;)n.removeAttributeNode(l[0]);sl(n,r,t),n[e_]=e,n[eF]=t}catch(n){iE(e,e.return,n)}}var o_=!1,oF=!1,oD=!1,oM="function"==typeof WeakSet?WeakSet:Set,oO=null;function oA(e,n,t){var r=t.flags;switch(t.tag){case 0:case 11:case 15:oq(e,t),4&r&&ob(5,t);break;case 1:if(oq(e,t),4&r){if(e=t.stateNode,null===n)try{e.componentDidMount()}catch(e){iE(t,t.return,e)}else{var l=rU(t.type,n.memoizedProps);n=n.memoizedState;try{e.componentDidUpdate(l,n,e.__reactInternalSnapshotBeforeUpdate)}catch(e){iE(t,t.return,e)}}}64&r&&ow(t),512&r&&ox(t,t.return);break;case 3:if(oq(e,t),64&r&&null!==(r=t.updateQueue)){if(e=null,null!==t.child)switch(t.child.tag){case 27:case 5:case 1:e=t.child.stateNode}try{rN(r,e)}catch(e){iE(t,t.return,e)}}break;case 27:null===n&&4&r&&oT(t);case 26:case 5:oq(e,t),null===n&&4&r&&oC(t),512&r&&ox(t,t.return);break;case 12:default:oq(e,t);break;case 13:oq(e,t),4&r&&oj(e,t),64&r&&null!==(r=t.memoizedState)&&null!==(r=r.dehydrated)&&function(e,n){var t=e.ownerDocument;if("$?"!==e.data||"complete"===t.readyState)n();else{var r=function(){n(),t.removeEventListener("DOMContentLoaded",r)};t.addEventListener("DOMContentLoaded",r),e._reactRetry=r}}(r,t=iN.bind(null,t));break;case 22:if(!(l=null!==t.memoizedState||o_)){n=null!==n&&null!==n.memoizedState||oF;var a=o_,o=oF;o_=l,(oF=n)&&!o?function e(n,t,r){for(r=r&&0!=(8772&t.subtreeFlags),t=t.child;null!==t;){var l=t.alternate,a=n,o=t,u=o.flags;switch(o.tag){case 0:case 11:case 15:e(a,o,r),ob(4,o);break;case 1:if(e(a,o,r),"function"==typeof(a=(l=o).stateNode).componentDidMount)try{a.componentDidMount()}catch(e){iE(l,l.return,e)}if(null!==(a=(l=o).updateQueue)){var i=l.stateNode;try{var s=a.shared.hiddenCallbacks;if(null!==s)for(a.shared.hiddenCallbacks=null,a=0;a title"))),sl(a,r,t),a[e_]=e,e$(a),r=a;break e;case"link":var o=sQ("link","href",l).get(r+(t.href||""));if(o){for(var u=0;u<\/script>",e=e.removeChild(e.firstChild);break;case"select":e="string"==typeof r.is?l.createElement("select",{is:r.is}):l.createElement("select"),r.multiple?e.multiple=!0:r.size&&(e.size=r.size);break;default:e="string"==typeof r.is?l.createElement(t,{is:r.is}):l.createElement(t)}}e[e_]=n,e[eF]=r;e:for(l=n.child;null!==l;){if(5===l.tag||6===l.tag)e.appendChild(l.stateNode);else if(4!==l.tag&&27!==l.tag&&null!==l.child){l.child.return=l,l=l.child;continue}if(l===n)break;for(;null===l.sibling;){if(null===l.return||l.return===n)break e;l=l.return}l.sibling.return=l.return,l=l.sibling}switch(n.stateNode=e,sl(e,t,r),t){case"button":case"input":case"select":case"textarea":e=!!r.autoFocus;break;case"img":e=!0;break;default:e=!1}e&&ub(n)}}return ux(n),n.flags&=-0x1000001,null;case 6:if(e&&null!=n.stateNode)e.memoizedProps!==r&&ub(n);else{if("string"!=typeof r&&null===n.stateNode)throw Error(i(166));if(e=$.current,uh(n)){if(e=n.stateNode,t=n.memoizedProps,r=null,null!==(l=uo))switch(l.tag){case 27:case 5:r=l.memoizedProps}e[e_]=n,(e=!!(e.nodeValue===t||null!==r&&!0===r.suppressHydrationWarning||se(e.nodeValue,t)))||ud(n)}else(e=su(e).createTextNode(r))[e_]=n,n.stateNode=e}return ux(n),null;case 13:if(r=n.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(l=uh(n),null!==r&&null!==r.dehydrated){if(null===e){if(!l)throw Error(i(318));if(!(l=null!==(l=n.memoizedState)?l.dehydrated:null))throw Error(i(317));l[e_]=n}else ug(),0==(128&n.flags)&&(n.memoizedState=null),n.flags|=4;ux(n),l=!1}else l=uy(),null!==e&&null!==e.memoizedState&&(e.memoizedState.hydrationErrors=l),l=!0;if(!l){if(256&n.flags)return aB(n),n;return aB(n),null}}if(aB(n),0!=(128&n.flags))return n.lanes=t,n;if(t=null!==r,e=null!==e&&null!==e.memoizedState,t){r=n.child,l=null,null!==r.alternate&&null!==r.alternate.memoizedState&&null!==r.alternate.memoizedState.cachePool&&(l=r.alternate.memoizedState.cachePool.pool);var a=null;null!==r.memoizedState&&null!==r.memoizedState.cachePool&&(a=r.memoizedState.cachePool.pool),a!==l&&(r.flags|=2048)}return t!==e&&t&&(n.child.flags|=8192),uw(n,n.updateQueue),ux(n),null;case 4:return q(),null===e&&i0(n.stateNode.containerInfo),ux(n),null;case 10:return rr(n.type),ux(n),null;case 19:if(V(aW),null===(l=n.memoizedState))return ux(n),null;if(r=0!=(128&n.flags),null===(a=l.rendering)){if(r)uS(l,!1);else{if(0!==uR||null!==e&&0!=(128&e.flags))for(e=n.child;null!==e;){if(null!==(a=aq(e))){for(n.flags|=128,uS(l,!1),e=a.updateQueue,n.updateQueue=e,uw(n,e),n.subtreeFlags=0,e=t,t=n.child;null!==t;)ue(t,e),t=t.sibling;return j(aW,1&aW.current|2),n.child}e=e.sibling}null!==l.tail&&en()>uq&&(n.flags|=128,r=!0,uS(l,!1),n.lanes=4194304)}}else{if(!r){if(null!==(e=aq(a))){if(n.flags|=128,r=!0,e=e.updateQueue,n.updateQueue=e,uw(n,e),uS(l,!0),null===l.tail&&"hidden"===l.tailMode&&!a.alternate&&!ui)return ux(n),null}else 2*en()-l.renderingStartTime>uq&&0x20000000!==t&&(n.flags|=128,r=!0,uS(l,!1),n.lanes=4194304)}l.isBackwards?(a.sibling=n.child,n.child=a):(null!==(e=l.last)?e.sibling=a:n.child=a,l.last=a)}if(null!==l.tail)return n=l.tail,l.rendering=n,l.tail=n.sibling,l.renderingStartTime=en(),n.sibling=null,e=aW.current,j(aW,r?1&e|2:1&e),n;return ux(n),null;case 22:case 23:return aB(n),lr(),r=null!==n.memoizedState,null!==e?null!==e.memoizedState!==r&&(n.flags|=8192):r&&(n.flags|=8192),r?0!=(0x20000000&t)&&0==(128&n.flags)&&(ux(n),6&n.subtreeFlags&&(n.flags|=8192)):ux(n),null!==(t=n.updateQueue)&&uw(n,t.retryQueue),t=null,null!==e&&null!==e.memoizedState&&null!==e.memoizedState.cachePool&&(t=e.memoizedState.cachePool.pool),r=null,null!==n.memoizedState&&null!==n.memoizedState.cachePool&&(r=n.memoizedState.cachePool.pool),r!==t&&(n.flags|=2048),null!==e&&V(la),null;case 24:return t=null,null!==e&&(t=e.memoizedState.cache),n.memoizedState.cache!==t&&(n.flags|=2048),rr(rF),ux(n),null;case 25:case 30:return null}throw Error(i(156,n.tag))}(n.alternate,n,uA);if(null!==t){uL=t;return}if(null!==(n=n.sibling)){uL=n;return}uL=n=e}while(null!==n);0===uR&&(uR=5)}function ih(e,n){do{var t=function(e,n){switch(rZ(n),n.tag){case 1:return 65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 3:return rr(rF),q(),0!=(65536&(e=n.flags))&&0==(128&e)?(n.flags=-65537&e|128,n):null;case 26:case 27:case 5:return Y(n),null;case 13:if(aB(n),null!==(e=n.memoizedState)&&null!==e.dehydrated){if(null===n.alternate)throw Error(i(340));ug()}return 65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 19:return V(aW),null;case 4:return q(),null;case 10:return rr(n.type),null;case 22:case 23:return aB(n),lr(),null!==e&&V(la),65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 24:return rr(rF),null;default:return null}}(e.alternate,e);if(null!==t){t.flags&=32767,uL=t;return}if(null!==(t=e.return)&&(t.flags|=32768,t.subtreeFlags=0,t.deletions=null),!n&&null!==(e=e.sibling)){uL=e;return}uL=e=t}while(null!==e);uR=6,uL=null}function ig(e,n,t,r,l,a,o,u,s){e.cancelPendingCommit=null;do iw();while(0!==uX);if(0!=(6&uP))throw Error(i(327));if(null!==n){if(n===e.current)throw Error(i(177));if(!function(e,n,t,r,l,a){var o=e.pendingLanes;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=t,e.entangledLanes&=t,e.errorRecoveryDisabledLanes&=t,e.shellSuspendCounter=0;var u=e.entanglements,i=e.expirationTimes,s=e.hiddenUpdates;for(t=o&~t;0g&&(o=g,g=h,h=o);var y=tP(u,h),v=tP(u,g);if(y&&v&&(1!==p.rangeCount||p.anchorNode!==y.node||p.anchorOffset!==y.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var b=f.createRange();b.setStart(y.node,y.offset),p.removeAllRanges(),h>g?(p.addRange(b),p.extend(v.node,v.offset)):(b.setEnd(v.node,v.offset),p.addRange(b))}}}}for(f=[],p=u;p=p.parentNode;)1===p.nodeType&&f.push({element:p,left:p.scrollLeft,top:p.scrollTop});for("function"==typeof u.focus&&u.focus(),u=0;ut?32:t,M.T=null,t=u1,u1=null;var a=uG,o=uJ;if(uX=0,uG=null,uJ=0,0!=(6&uP))throw Error(i(331));var u=uP;if(uP|=4,o3(a.current),oG(a,a.current,o,t),uP=u,iR(0,!1),ef&&"function"==typeof ef.onPostCommitFiberRoot)try{ef.onPostCommitFiberRoot(ec,a)}catch(e){}return!0}finally{O.p=l,M.T=r,ik(e,n)}}function ix(e,n,t){n=tZ(t,n),n=a0(e.stateNode,n,2),null!==(e=rw(e,n,2))&&(eE(e,2),iA(e))}function iE(e,n,t){if(3===e.tag)ix(e,e,t);else for(;null!==n;){if(3===n.tag){ix(n,e,t);break}if(1===n.tag){var r=n.stateNode;if("function"==typeof n.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===uY||!uY.has(r))){e=tZ(t,e),null!==(r=rw(n,t=a1(2),2))&&(a2(t,r,n,e),eE(r,2),iA(r));break}}n=n.return}}function iC(e,n,t){var r=e.pingCache;if(null===r){r=e.pingCache=new uz;var l=new Set;r.set(n,l)}else void 0===(l=r.get(n))&&(l=new Set,r.set(n,l));l.has(t)||(uO=!0,l.add(t),e=iz.bind(null,e,n,t),n.then(e,e))}function iz(e,n,t){var r=e.pingCache;null!==r&&r.delete(n),e.pingedLanes|=e.suspendedLanes&t,e.warmLanes&=~t,uN===e&&(uT&t)===t&&(4===uR||3===uR&&(0x3c00000&uT)===uT&&300>en()-uW?0==(2&uP)&&il(e,0):uV|=t,uH===uT&&(uH=0)),iA(e)}function iP(e,n){0===n&&(n=eS()),null!==(e=t8(e,n))&&(eE(e,n),iA(e))}function iN(e){var n=e.memoizedState,t=0;null!==n&&(t=n.retryLane),iP(e,t)}function iL(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;null!==l&&(t=l.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}null!==r&&r.delete(n),iP(e,t)}var iT=null,i_=null,iF=!1,iD=!1,iM=!1,iO=0;function iA(e){e!==i_&&null===e.next&&(null===i_?iT=i_=e:i_=i_.next=e),iD=!0,iF||(iF=!0,sh(function(){0!=(6&uP)?G(er,iI):iU()}))}function iR(e,n){if(!iM&&iD){iM=!0;do for(var t=!1,r=iT;null!==r;){if(!n){if(0!==e){var l=r.pendingLanes;if(0===l)var a=0;else{var o=r.suspendedLanes,u=r.pingedLanes;a=0xc000095&(a=(1<<31-ep(42|e)+1)-1&(l&~(o&~u)))?0xc000095&a|1:a?2|a:0}0!==a&&(t=!0,iH(r,a))}else a=uT,0==(3&(a=eb(r,r===uN?a:0,null!==r.cancelPendingCommit||-1!==r.timeoutHandle)))||ek(r,a)||(t=!0,iH(r,a))}r=r.next}while(t);iM=!1}}function iI(){iU()}function iU(){iD=iF=!1;var e,n=0;0!==iO&&(((e=window.event)&&"popstate"===e.type?e===sf||(sf=e,0):(sf=null,1))||(n=iO),iO=0);for(var t=en(),r=null,l=iT;null!==l;){var a=l.next,o=iV(l,t);0===o?(l.next=null,null===r?iT=a:r.next=a,null===a&&(i_=r)):(r=l,(0!==n||0!=(3&o))&&(iD=!0)),l=a}iR(n,!1)}function iV(e,n){for(var t=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=-0x3c00001&e.pendingLanes;0r){t=r;var o=e.ownerDocument;if(1&t&&sC(o.documentElement),2&t&&sC(o.body),4&t)for(sC(t=o.head),o=t.firstChild;o;){var u=o.nextSibling,i=o.nodeName;o[eI]||"SCRIPT"===i||"STYLE"===i||"LINK"===i&&"stylesheet"===o.rel.toLowerCase()||t.removeChild(o),o=u}}if(0===l){e.removeChild(a),cw(n);return}l--}else"$"===t||"$?"===t||"$!"===t?l++:r=t.charCodeAt(0)-48}else r=0;t=a}while(t);cw(n)}function sb(e){var n=e.firstChild;for(n&&10===n.nodeType&&(n=n.nextSibling);n;){var t=n;switch(n=n.nextSibling,t.nodeName){case"HTML":case"HEAD":case"BODY":sb(t),eU(t);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if("stylesheet"===t.rel.toLowerCase())continue}e.removeChild(t)}}function sk(e){return"$!"===e.data||"$?"===e.data&&"complete"===e.ownerDocument.readyState}function sw(e){for(;null!=e;e=e.nextSibling){var n=e.nodeType;if(1===n||3===n)break;if(8===n){if("$"===(n=e.data)||"$!"===n||"$?"===n||"F!"===n||"F"===n)break;if("/$"===n)return null}}return e}var sS=null;function sx(e){e=e.previousSibling;for(var n=0;e;){if(8===e.nodeType){var t=e.data;if("$"===t||"$!"===t||"$?"===t){if(0===n)return e;n--}else"/$"===t&&n++}e=e.previousSibling}return null}function sE(e,n,t){switch(n=su(t),e){case"html":if(!(e=n.documentElement))throw Error(i(452));return e;case"head":if(!(e=n.head))throw Error(i(453));return e;case"body":if(!(e=n.body))throw Error(i(454));return e;default:throw Error(i(451))}}function sC(e){for(var n=e.attributes;n.length;)e.removeAttributeNode(n[0]);eU(e)}var sz=new Map,sP=new Set;function sN(e){return"function"==typeof e.getRootNode?e.getRootNode():9===e.nodeType?e:e.ownerDocument}var sL=O.d;O.d={f:function(){var e=sL.f(),n=it();return e||n},r:function(e){var n=ej(e);null!==n&&5===n.tag&&"form"===n.type?ah(n):sL.r(e)},D:function(e){sL.D(e),s_("dns-prefetch",e,null)},C:function(e,n){sL.C(e,n),s_("preconnect",e,n)},L:function(e,n,t){if(sL.L(e,n,t),sT&&e&&n){var r='link[rel="preload"][as="'+nn(n)+'"]';"image"===n&&t&&t.imageSrcSet?(r+='[imagesrcset="'+nn(t.imageSrcSet)+'"]',"string"==typeof t.imageSizes&&(r+='[imagesizes="'+nn(t.imageSizes)+'"]')):r+='[href="'+nn(e)+'"]';var l=r;switch(n){case"style":l=sD(e);break;case"script":l=sA(e)}sz.has(l)||(e=p({rel:"preload",href:"image"===n&&t&&t.imageSrcSet?void 0:e,as:n},t),sz.set(l,e),null!==sT.querySelector(r)||"style"===n&&sT.querySelector(sM(l))||"script"===n&&sT.querySelector(sR(l))||(sl(n=sT.createElement("link"),"link",e),e$(n),sT.head.appendChild(n)))}},m:function(e,n){if(sL.m(e,n),sT&&e){var t=n&&"string"==typeof n.as?n.as:"script",r='link[rel="modulepreload"][as="'+nn(t)+'"][href="'+nn(e)+'"]',l=r;switch(t){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":l=sA(e)}if(!sz.has(l)&&(e=p({rel:"modulepreload",href:e},n),sz.set(l,e),null===sT.querySelector(r))){switch(t){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(sT.querySelector(sR(l)))return}sl(t=sT.createElement("link"),"link",e),e$(t),sT.head.appendChild(t)}}},X:function(e,n){if(sL.X(e,n),sT&&e){var t=eQ(sT).hoistableScripts,r=sA(e),l=t.get(r);l||((l=sT.querySelector(sR(r)))||(e=p({src:e,async:!0},n),(n=sz.get(r))&&sj(e,n),e$(l=sT.createElement("script")),sl(l,"link",e),sT.head.appendChild(l)),l={type:"script",instance:l,count:1,state:null},t.set(r,l))}},S:function(e,n,t){if(sL.S(e,n,t),sT&&e){var r=eQ(sT).hoistableStyles,l=sD(e);n=n||"default";var a=r.get(l);if(!a){var o={loading:0,preload:null};if(a=sT.querySelector(sM(l)))o.loading=5;else{e=p({rel:"stylesheet",href:e,"data-precedence":n},t),(t=sz.get(l))&&sV(e,t);var u=a=sT.createElement("link");e$(u),sl(u,"link",e),u._p=new Promise(function(e,n){u.onload=e,u.onerror=n}),u.addEventListener("load",function(){o.loading|=1}),u.addEventListener("error",function(){o.loading|=2}),o.loading|=4,sU(a,n,sT)}a={type:"stylesheet",instance:a,count:1,state:o},r.set(l,a)}}},M:function(e,n){if(sL.M(e,n),sT&&e){var t=eQ(sT).hoistableScripts,r=sA(e),l=t.get(r);l||((l=sT.querySelector(sR(r)))||(e=p({src:e,async:!0,type:"module"},n),(n=sz.get(r))&&sj(e,n),e$(l=sT.createElement("script")),sl(l,"link",e),sT.head.appendChild(l)),l={type:"script",instance:l,count:1,state:null},t.set(r,l))}}};var sT="undefined"==typeof document?null:document;function s_(e,n,t){if(sT&&"string"==typeof n&&n){var r=nn(n);r='link[rel="'+e+'"][href="'+r+'"]',"string"==typeof t&&(r+='[crossorigin="'+t+'"]'),sP.has(r)||(sP.add(r),e={rel:e,crossOrigin:t,href:n},null===sT.querySelector(r)&&(sl(n=sT.createElement("link"),"link",e),e$(n),sT.head.appendChild(n)))}}function sF(e,n,t,r){var l=(l=$.current)?sN(l):null;if(!l)throw Error(i(446));switch(e){case"meta":case"title":return null;case"style":return"string"==typeof t.precedence&&"string"==typeof t.href?(n=sD(t.href),(r=(t=eQ(l).hoistableStyles).get(n))||(r={type:"style",instance:null,count:0,state:null},t.set(n,r)),r):{type:"void",instance:null,count:0,state:null};case"link":if("stylesheet"===t.rel&&"string"==typeof t.href&&"string"==typeof t.precedence){e=sD(t.href);var a,o,u,s,c=eQ(l).hoistableStyles,f=c.get(e);if(f||(l=l.ownerDocument||l,f={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},c.set(e,f),(c=l.querySelector(sM(e)))&&!c._p&&(f.instance=c,f.state.loading=5),sz.has(e)||(t={rel:"preload",as:"style",href:t.href,crossOrigin:t.crossOrigin,integrity:t.integrity,media:t.media,hrefLang:t.hrefLang,referrerPolicy:t.referrerPolicy},sz.set(e,t),c||(a=l,o=e,u=t,s=f.state,a.querySelector('link[rel="preload"][as="style"]['+o+"]")?s.loading=1:(o=a.createElement("link"),s.preload=o,o.addEventListener("load",function(){return s.loading|=1}),o.addEventListener("error",function(){return s.loading|=2}),sl(o,"link",u),e$(o),a.head.appendChild(o))))),n&&null===r)throw Error(i(528,""));return f}if(n&&null!==r)throw Error(i(529,""));return null;case"script":return n=t.async,"string"==typeof(t=t.src)&&n&&"function"!=typeof n&&"symbol"!=typeof n?(n=sA(t),(r=(t=eQ(l).hoistableScripts).get(n))||(r={type:"script",instance:null,count:0,state:null},t.set(n,r)),r):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,e))}}function sD(e){return'href="'+nn(e)+'"'}function sM(e){return'link[rel="stylesheet"]['+e+"]"}function sO(e){return p({},e,{"data-precedence":e.precedence,precedence:null})}function sA(e){return'[src="'+nn(e)+'"]'}function sR(e){return"script[async]"+e}function sI(e,n,t){if(n.count++,null===n.instance)switch(n.type){case"style":var r=e.querySelector('style[data-href~="'+nn(t.href)+'"]');if(r)return n.instance=r,e$(r),r;var l=p({},t,{"data-href":t.href,"data-precedence":t.precedence,href:null,precedence:null});return e$(r=(e.ownerDocument||e).createElement("style")),sl(r,"style",l),sU(r,t.precedence,e),n.instance=r;case"stylesheet":l=sD(t.href);var a=e.querySelector(sM(l));if(a)return n.state.loading|=4,n.instance=a,e$(a),a;r=sO(t),(l=sz.get(l))&&sV(r,l),e$(a=(e.ownerDocument||e).createElement("link"));var o=a;return o._p=new Promise(function(e,n){o.onload=e,o.onerror=n}),sl(a,"link",r),n.state.loading|=4,sU(a,t.precedence,e),n.instance=a;case"script":if(a=sA(t.src),l=e.querySelector(sR(a)))return n.instance=l,e$(l),l;return r=t,(l=sz.get(a))&&sj(r=p({},t),l),e$(l=(e=e.ownerDocument||e).createElement("script")),sl(l,"link",r),e.head.appendChild(l),n.instance=l;case"void":return null;default:throw Error(i(443,n.type))}else"stylesheet"===n.type&&0==(4&n.state.loading)&&(r=n.instance,n.state.loading|=4,sU(r,t.precedence,e));return n.instance}function sU(e,n,t){for(var r=t.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),l=r.length?r[r.length-1]:null,a=l,o=0;o title"):null)}function sB(e){return"stylesheet"!==e.type||0!=(3&e.state.loading)}var sW=null;function sq(){}function sK(){if(this.count--,0===this.count){if(this.stylesheets)sX(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var sY=null;function sX(e,n){e.stylesheets=null,null!==e.unsuspend&&(e.count++,sY=new Map,n.forEach(sG,e),sY=null,sK.call(e))}function sG(e,n){if(!(4&n.state.loading)){var t=sY.get(e);if(t)var r=t.get(null);else{t=new Map,sY.set(e,t);for(var l=e.querySelectorAll("link[data-precedence],style[data-precedence]"),a=0;a{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"attachHydrationErrorState",{enumerable:!0,get:function(){return a}});let n=r(5384),o=r(7088);function a(e){let t={},r=(0,n.testReactHydrationWarning)(e.message),a=(0,n.isHydrationError)(e);if(!(a||r))return;let u=(0,o.getReactHydrationDiffSegments)(e.message);if(u){let l=u[1];t={...e.details,...o.hydrationErrorState,warning:(l&&!r?null:o.hydrationErrorState.warning)||[(0,n.getDefaultHydrationErrorMessage)()],notes:r?"":u[0],reactOutputComponentDiff:l},!o.hydrationErrorState.reactOutputComponentDiff&&l&&(o.hydrationErrorState.reactOutputComponentDiff=l),!l&&a&&o.hydrationErrorState.reactOutputComponentDiff&&(t.reactOutputComponentDiff=o.hydrationErrorState.reactOutputComponentDiff)}else o.hydrationErrorState.warning&&(t={...e.details,...o.hydrationErrorState}),o.hydrationErrorState.reactOutputComponentDiff&&(t.reactOutputComponentDiff=o.hydrationErrorState.reactOutputComponentDiff);e.details=t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},179:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNextRouterError",{enumerable:!0,get:function(){return a}});let n=r(2469),o=r(7563);function a(e){return(0,o.isRedirectError)(e)||(0,n.isHTTPAccessFallbackError)(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},180:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{formatUrl:function(){return a},formatWithValidation:function(){return l},urlObjectKeys:function(){return u}});let n=r(9955)._(r(4156)),o=/https?|ftp|gopher|file/;function a(e){let{auth:t,hostname:r}=e,a=e.protocol||"",u=e.pathname||"",l=e.hash||"",i=e.query||"",c=!1;t=t?encodeURIComponent(t).replace(/%3A/i,":")+"@":"",e.host?c=t+e.host:r&&(c=t+(~r.indexOf(":")?"["+r+"]":r),e.port&&(c+=":"+e.port)),i&&"object"==typeof i&&(i=String(n.urlQueryToSearchParams(i)));let s=e.search||i&&"?"+i||"";return a&&!a.endsWith(":")&&(a+=":"),e.slashes||(!a||o.test(a))&&!1!==c?(c="//"+(c||""),u&&"/"!==u[0]&&(u="/"+u)):c||(c=""),l&&"#"!==l[0]&&(l="#"+l),s&&"?"!==s[0]&&(s="?"+s),""+a+c+(u=u.replace(/[?#]/g,encodeURIComponent))+(s=s.replace("#","%23"))+l}let u=["auth","hash","host","hostname","href","path","pathname","port","protocol","query","search","slashes"];function l(e){return a(e)}},223:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return function e(t,r,a,u,l,i){if(0===Object.keys(a[1]).length){t.head=l;return}for(let c in a[1]){let s;let f=a[1][c],d=f[0],p=(0,n.createRouterCacheKey)(d),h=null!==u&&void 0!==u[2][c]?u[2][c]:null;if(r){let n=r.parallelRoutes.get(c);if(n){let r;let a=(null==i?void 0:i.kind)==="auto"&&i.status===o.PrefetchCacheEntryStatus.reusable,u=new Map(n),s=u.get(p);r=null!==h?{lazyData:null,rsc:h[1],prefetchRsc:null,head:null,prefetchHead:null,loading:h[3],parallelRoutes:new Map(null==s?void 0:s.parallelRoutes)}:a&&s?{lazyData:s.lazyData,rsc:s.rsc,prefetchRsc:s.prefetchRsc,head:s.head,prefetchHead:s.prefetchHead,parallelRoutes:new Map(s.parallelRoutes),loading:s.loading}:{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map(null==s?void 0:s.parallelRoutes),loading:null},u.set(p,r),e(r,s,f,h||null,l,i),t.parallelRoutes.set(c,u);continue}}if(null!==h){let e=h[1],t=h[3];s={lazyData:null,rsc:e,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:t}}else s={lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:null};let y=t.parallelRoutes.get(c);y?y.set(p,s):t.parallelRoutes.set(c,new Map([[p,s]])),e(s,void 0,f,h,l,i)}}}});let n=r(5404),o=r(4445);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},243:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HTML_LIMITED_BOT_UA_RE",{enumerable:!0,get:function(){return r}});let r=/Mediapartners-Google|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview/i},306:(e,t,r)=>{"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:()=>n})},406:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DynamicServerError:function(){return n},isDynamicServerError:function(){return o}});let r="DYNAMIC_SERVER_USAGE";class n extends Error{constructor(e){super("Dynamic server usage: "+e),this.description=e,this.digest=r}}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&"string"==typeof e.digest&&e.digest===r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},410:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{createUnhandledError:function(){return o},getUnhandledErrorType:function(){return u},isUnhandledConsoleOrRejection:function(){return a}});let r=Symbol.for("next.console.error.digest"),n=Symbol.for("next.console.error.type");function o(e,t){let o="string"==typeof e?Object.defineProperty(Error(e),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0}):e;return o[r]="NEXT_UNHANDLED_ERROR",o[n]="string"==typeof e?"string":"error",t&&!o.environmentName&&(o.environmentName=t),o}let a=e=>e&&"NEXT_UNHANDLED_ERROR"===e[r],u=e=>e[n];("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},497:()=>{"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var e=/\((.*)\)/.exec(this.toString());return e?e[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(e,t){return t=this.concat.apply([],this),e>1&&t.some(Array.isArray)?t.flat(e-1):t},Array.prototype.flatMap=function(e,t){return this.map(e,t).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(e){if("function"!=typeof e)return this.then(e,e);var t=this.constructor||Promise;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})}),Object.fromEntries||(Object.fromEntries=function(e){return Array.from(e).reduce(function(e,t){return e[t[0]]=t[1],e},{})}),Array.prototype.at||(Array.prototype.at=function(e){var t=Math.trunc(e)||0;if(t<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]}),Object.hasOwn||(Object.hasOwn=function(e,t){if(null==e)throw TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(e),t)}),"canParse"in URL||(URL.canParse=function(e,t){try{return new URL(e,t),!0}catch(e){return!1}})},576:(e,t)=>{"use strict";function r(e,t){var r=e.length;for(e.push(t);0>>1,o=e[n];if(0>>1;na(i,r))ca(s,i)?(e[n]=s,e[c]=r,n=c):(e[n]=i,e[l]=r,n=l);else if(ca(s,r))e[n]=s,e[c]=r,n=c;else break}}return t}function a(e,t){var r=e.sortIndex-t.sortIndex;return 0!==r?r:e.id-t.id}if(t.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var u,l=performance;t.unstable_now=function(){return l.now()}}else{var i=Date,c=i.now();t.unstable_now=function(){return i.now()-c}}var s=[],f=[],d=1,p=null,h=3,y=!1,g=!1,_=!1,b=!1,m="function"==typeof setTimeout?setTimeout:null,v="function"==typeof clearTimeout?clearTimeout:null,E="undefined"!=typeof setImmediate?setImmediate:null;function R(e){for(var t=n(f);null!==t;){if(null===t.callback)o(f);else if(t.startTime<=e)o(f),t.sortIndex=t.expirationTime,r(s,t);else break;t=n(f)}}function O(e){if(_=!1,R(e),!g){if(null!==n(s))g=!0,P||(P=!0,u());else{var t=n(f);null!==t&&A(O,t.startTime-e)}}}var P=!1,S=-1,j=5,T=-1;function w(){return!!b||!(t.unstable_now()-Te&&w());){var l=p.callback;if("function"==typeof l){p.callback=null,h=p.priorityLevel;var i=l(p.expirationTime<=e);if(e=t.unstable_now(),"function"==typeof i){p.callback=i,R(e),r=!0;break t}p===n(s)&&o(s),R(e)}else o(s);p=n(s)}if(null!==p)r=!0;else{var c=n(f);null!==c&&A(O,c.startTime-e),r=!1}}break e}finally{p=null,h=a,y=!1}r=void 0}}finally{r?u():P=!1}}}if("function"==typeof E)u=function(){E(M)};else if("undefined"!=typeof MessageChannel){var x=new MessageChannel,C=x.port2;x.port1.onmessage=M,u=function(){C.postMessage(null)}}else u=function(){m(M,0)};function A(e,r){S=m(function(){e(t.unstable_now())},r)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_forceFrameRate=function(e){0>e||125l?(e.sortIndex=a,r(f,e),null===n(s)&&e===n(f)&&(_?(v(S),S=-1):_=!0,A(O,a-l))):(e.sortIndex=i,r(s,e),g||y||(g=!0,P||(P=!0,u()))),e},t.unstable_shouldYield=w,t.unstable_wrapCallback=function(e){var t=h;return function(){var r=h;h=t;try{return e.apply(this,arguments)}finally{h=r}}}},608:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"clearCacheNodeDataForSegmentPath",{enumerable:!0,get:function(){return function e(t,r,a){let u=a.length<=2,[l,i]=a,c=(0,o.createRouterCacheKey)(i),s=r.parallelRoutes.get(l),f=t.parallelRoutes.get(l);f&&f!==s||(f=new Map(s),t.parallelRoutes.set(l,f));let d=null==s?void 0:s.get(c),p=f.get(c);if(u){p&&p.lazyData&&p!==d||f.set(c,{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:null});return}if(!p||!d){p||f.set(c,{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:null});return}return p===d&&(p={lazyData:p.lazyData,rsc:p.rsc,prefetchRsc:p.prefetchRsc,head:p.head,prefetchHead:p.prefetchHead,parallelRoutes:new Map(p.parallelRoutes),loading:p.loading},f.set(c,p)),e(p,d,(0,n.getNextFlightSegmentPath)(a))}}});let n=r(1648),o=r(5404);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},630:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"assignLocation",{enumerable:!0,get:function(){return o}});let n=r(9544);function o(e,t){if(e.startsWith(".")){let r=t.origin+t.pathname;return new URL((r.endsWith("/")?r:r+"/")+e)}return new URL((0,n.addBasePath)(e),t.href)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},655:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyFlightData",{enumerable:!0,get:function(){return a}});let n=r(223),o=r(8645);function a(e,t,r,a){let{tree:u,seedData:l,head:i,isRootRender:c}=r;if(null===l)return!1;if(c){let r=l[1],o=l[3];t.loading=o,t.rsc=r,t.prefetchRsc=null,(0,n.fillLazyItemsTillLeafWithHead)(t,e,u,l,i,a)}else t.rsc=e.rsc,t.prefetchRsc=e.prefetchRsc,t.parallelRoutes=new Map(e.parallelRoutes),t.loading=e.loading,(0,o.fillCacheWithNewSubTreeData)(t,e,r,a);return!0}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},740:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{METADATA_BOUNDARY_NAME:function(){return r},OUTLET_BOUNDARY_NAME:function(){return o},VIEWPORT_BOUNDARY_NAME:function(){return n}});let r="__next_metadata_boundary__",n="__next_viewport_boundary__",o="__next_outlet_boundary__"},845:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{computeChangedPath:function(){return s},extractPathFromFlightRouterState:function(){return c},getSelectedParams:function(){return function e(t,r){for(let n of(void 0===r&&(r={}),Object.values(t[1]))){let t=n[0],a=Array.isArray(t),u=a?t[1]:t;!(!u||u.startsWith(o.PAGE_SEGMENT_KEY))&&(a&&("c"===t[2]||"oc"===t[2])?r[t[0]]=t[1].split("/"):a&&(r[t[0]]=t[1]),r=e(n,r))}return r}}});let n=r(8456),o=r(6090),a=r(4682),u=e=>"/"===e[0]?e.slice(1):e,l=e=>"string"==typeof e?"children"===e?"":e:e[1];function i(e){return e.reduce((e,t)=>""===(t=u(t))||(0,o.isGroupSegment)(t)?e:e+"/"+t,"")||"/"}function c(e){var t;let r=Array.isArray(e[0])?e[0][1]:e[0];if(r===o.DEFAULT_SEGMENT_KEY||n.INTERCEPTION_ROUTE_MARKERS.some(e=>r.startsWith(e)))return;if(r.startsWith(o.PAGE_SEGMENT_KEY))return"";let a=[l(r)],u=null!=(t=e[1])?t:{},s=u.children?c(u.children):void 0;if(void 0!==s)a.push(s);else for(let[e,t]of Object.entries(u)){if("children"===e)continue;let r=c(t);void 0!==r&&a.push(r)}return i(a)}function s(e,t){let r=function e(t,r){let[o,u]=t,[i,s]=r,f=l(o),d=l(i);if(n.INTERCEPTION_ROUTE_MARKERS.some(e=>f.startsWith(e)||d.startsWith(e)))return"";if(!(0,a.matchSegment)(o,i)){var p;return null!=(p=c(r))?p:""}for(let t in u)if(s[t]){let r=e(u[t],s[t]);if(null!==r)return l(i)+"/"+r}return null}(e,t);return null==r||"/"===r?r:i(r.split("/"))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},847:(e,t,r)=>{"use strict";let n,o;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hydrate",{enumerable:!0,get:function(){return k}});let a=r(306),u=r(9955),l=r(5155);r(497),r(8397),r(9003);let i=a._(r(2669)),c=u._(r(2115)),s=r(4979),f=r(1147),d=r(7251),p=r(862),h=r(9603),y=r(3355),g=r(6833),_=a._(r(3423)),b=r(1386);r(1394);let m=r(8127);r(3633);let v=document,E=new TextEncoder,R=!1,O=!1,P=null;function S(e){if(0===e[0])n=[];else if(1===e[0]){if(!n)throw Object.defineProperty(Error("Unexpected server data: missing bootstrap script."),"__NEXT_ERROR_CODE",{value:"E18",enumerable:!1,configurable:!0});o?o.enqueue(E.encode(e[1])):n.push(e[1])}else if(2===e[0])P=e[1];else if(3===e[0]){if(!n)throw Object.defineProperty(Error("Unexpected server data: missing bootstrap script."),"__NEXT_ERROR_CODE",{value:"E18",enumerable:!1,configurable:!0});let r=atob(e[1]),a=new Uint8Array(r.length);for(var t=0;t{e.enqueue("string"==typeof t?E.encode(t):t)}),R&&!O))null===e.desiredSize||e.desiredSize<0?e.error(Object.defineProperty(Error("The connection to the page was unexpectedly closed, possibly due to the stop button being clicked, loss of Wi-Fi, or an unstable internet connection."),"__NEXT_ERROR_CODE",{value:"E117",enumerable:!1,configurable:!0})):e.close(),O=!0,n=void 0;o=e}(e)}}),M=(0,s.createFromReadableStream)(w,{callServer:h.callServer,findSourceMapURL:y.findSourceMapURL}),x=new Promise((e,t)=>{M.then(t=>{(0,m.setAppBuildId)(t.b),e((0,g.createMutableActionQueue)((0,b.createInitialRouterState)({initialFlightData:t.f,initialCanonicalUrlParts:t.c,initialParallelRoutes:new Map,location:window.location,couldBeIntercepted:t.i,postponed:t.s,prerendered:t.S})))},e=>t(e))});function C(){let e=(0,c.use)(M),t=(0,c.use)(x);return(0,l.jsx)(_.default,{actionQueue:t,globalErrorComponentAndStyles:e.G,assetPrefix:e.p})}let A=c.default.StrictMode;function D(e){let{children:t}=e;return t}let N={onRecoverableError:d.onRecoverableError,onCaughtError:p.onCaughtError,onUncaughtError:p.onUncaughtError};function k(){var e;let t=(0,l.jsx)(A,{children:(0,l.jsx)(f.HeadManagerContext.Provider,{value:{appDir:!0},children:(0,l.jsx)(D,{children:(0,l.jsx)(C,{})})})});"__next_error__"===document.documentElement.id||(null==(e=window.__next_root_layout_missing_tags)?void 0:e.length)?i.default.createRoot(v,N).render(t):c.default.startTransition(()=>{i.default.hydrateRoot(v,t,{...N,formState:P})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},862:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{onCaughtError:function(){return i},onUncaughtError:function(){return c}}),r(8227),r(5597);let n=r(179),o=r(3719),a=r(7489),u=r(5194),l=r(4835);function i(e,t){var r;let a;let i=null==(r=t.errorBoundary)?void 0:r.constructor;if(a=a||i===l.ErrorBoundaryHandler&&t.errorBoundary.props.errorComponent===l.GlobalError)return c(e,t);(0,o.isBailoutToCSRError)(e)||(0,n.isNextRouterError)(e)||(0,u.originConsoleError)(e)}function c(e,t){(0,o.isBailoutToCSRError)(e)||(0,n.isNextRouterError)(e)||(0,a.reportGlobalError)(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},882:(e,t,r)=>{"use strict";function n(){throw Object.defineProperty(Error("`unauthorized()` is experimental and only allowed to be used when `experimental.authInterrupts` is enabled."),"__NEXT_ERROR_CODE",{value:"E411",enumerable:!1,configurable:!0})}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"unauthorized",{enumerable:!0,get:function(){return n}}),r(2469).HTTP_ERROR_FALLBACK_ERROR_CODE,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},941:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasInterceptionRouteInCurrentTree",{enumerable:!0,get:function(){return function e(t){let[r,o]=t;if(Array.isArray(r)&&("di"===r[2]||"ci"===r[2])||"string"==typeof r&&(0,n.isInterceptionRouteAppPath)(r))return!0;if(o){for(let t in o)if(e(o[t]))return!0}return!1}}});let n=r(8456);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1042:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ReflectAdapter",{enumerable:!0,get:function(){return r}});class r{static get(e,t,r){let n=Reflect.get(e,t,r);return"function"==typeof n?n.bind(e):n}static set(e,t,r,n){return Reflect.set(e,t,r,n)}static has(e,t){return Reflect.has(e,t)}static deleteProperty(e,t){return Reflect.deleteProperty(e,t)}}},1053:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return function e(t,r,n,i){let c;let[s,f,d,p,h]=r;if(1===t.length){let e=l(r,n);return(0,u.addRefreshMarkerToActiveParallelSegments)(e,i),e}let[y,g]=t;if(!(0,a.matchSegment)(y,s))return null;if(2===t.length)c=l(f[g],n);else if(null===(c=e((0,o.getNextFlightSegmentPath)(t),f[g],n,i)))return null;let _=[t[0],{...f,[g]:c},d,p];return h&&(_[4]=!0),(0,u.addRefreshMarkerToActiveParallelSegments)(_,i),_}}});let n=r(6090),o=r(1648),a=r(4682),u=r(1387);function l(e,t){let[r,o]=e,[u,i]=t;if(u===n.DEFAULT_SEGMENT_KEY&&r!==n.DEFAULT_SEGMENT_KEY)return e;if((0,a.matchSegment)(r,u)){let t={};for(let e in o)void 0!==i[e]?t[e]=l(o[e],i[e]):t[e]=o[e];for(let e in i)!t[e]&&(t[e]=i[e]);let n=[r,t];return e[2]&&(n[2]=e[2]),e[3]&&(n[3]=e[3]),e[4]&&(n[4]=e[4]),n}return t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1096:(e,t)=>{"use strict";function r(e,t){let r=null,o=!1,a=0;function u(e){let t=e.next,n=e.prev;null!==t&&null!==n&&(a-=e.size,e.next=null,e.prev=null,r===e?r=t===r?null:t:(n.next=t,t.prev=n))}function l(){!o&&!(a<=e)&&(o=!0,n(i))}function i(){o=!1;let n=.9*e;for(;a>n&&null!==r;){let e=r.prev;u(e),t(e)}}return{put:function(e){if(r===e)return;let t=e.prev,n=e.next;if(null===n||null===t?(a+=e.size,l()):(t.next=n,n.prev=t),null===r)e.prev=e,e.next=e;else{let t=r.prev;e.prev=t,t.next=e,e.next=r,r.prev=e}r=e},delete:u,updateSize:function(e,t){let r=e.size;e.size=t,null!==e.next&&(a=a-r+t,l())}}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createLRU",{enumerable:!0,get:function(){return r}});let n="function"==typeof requestIdleCallback?requestIdleCallback:e=>setTimeout(e,0);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1129:(e,t,r)=>{"use strict";function n(e){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return n}}),r(6003),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1142:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{describeHasCheckingStringProperty:function(){return l},describeStringPropertyAccess:function(){return u},isRequestAPICallableInsideAfter:function(){return f},throwForSearchParamsAccessInUseCache:function(){return s},throwWithStaticGenerationBailoutError:function(){return i},throwWithStaticGenerationBailoutErrorWithDynamicError:function(){return c},wellKnownProperties:function(){return d}});let n=r(6830),o=r(8140),a=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function u(e,t){return a.test(t)?`\`${e}.${t}\``:`\`${e}[${JSON.stringify(t)}]\``}function l(e,t){let r=JSON.stringify(t);return`\`Reflect.has(${e}, ${r})\`, \`${r} in ${e}\`, or similar`}function i(e,t){throw Object.defineProperty(new n.StaticGenBailoutError(`Route ${e} couldn't be rendered statically because it used ${t}. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E576",enumerable:!1,configurable:!0})}function c(e,t){throw Object.defineProperty(new n.StaticGenBailoutError(`Route ${e} with \`dynamic = "error"\` couldn't be rendered statically because it used ${t}. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E543",enumerable:!1,configurable:!0})}function s(e){throw Object.defineProperty(Error(`Route ${e} used "searchParams" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "searchParams" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`),"__NEXT_ERROR_CODE",{value:"E634",enumerable:!1,configurable:!0})}function f(){let e=o.afterTaskAsyncStorage.getStore();return(null==e?void 0:e.rootTaskSpawnPhase)==="action"}let d=new Set(["hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toString","valueOf","toLocaleString","then","catch","finally","status","displayName","toJSON","$$typeof","__esModule"])},1147:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HeadManagerContext",{enumerable:!0,get:function(){return n}});let n=r(306)._(r(2115)).default.createContext({})},1233:(e,t)=>{"use strict";function r(e){let t=5381;for(let r=0;r>>0}function n(e){return r(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{djb2Hash:function(){return r},hexHash:function(){return n}})},1246:(e,t)=>{"use strict";function r(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return r}})},1386:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInitialRouterState",{enumerable:!0,get:function(){return s}});let n=r(3436),o=r(223),a=r(845),u=r(1893),l=r(4445),i=r(1387),c=r(1648);function s(e){var t,r;let{initialFlightData:s,initialCanonicalUrlParts:f,initialParallelRoutes:d,location:p,couldBeIntercepted:h,postponed:y,prerendered:g}=e,_=f.join("/"),b=(0,c.getFlightDataPartsFromPath)(s[0]),{tree:m,seedData:v,head:E}=b,R={lazyData:null,rsc:null==v?void 0:v[1],prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:d,loading:null!=(t=null==v?void 0:v[3])?t:null},O=p?(0,n.createHrefFromUrl)(p):_;(0,i.addRefreshMarkerToActiveParallelSegments)(m,O);let P=new Map;(null===d||0===d.size)&&(0,o.fillLazyItemsTillLeafWithHead)(R,void 0,m,v,E,void 0);let S={tree:m,cache:R,prefetchCache:P,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:O,nextUrl:null!=(r=(0,a.extractPathFromFlightRouterState)(m)||(null==p?void 0:p.pathname))?r:null};if(p){let e=new URL(""+p.pathname+p.search,p.origin);(0,u.createSeededPrefetchCacheEntry)({url:e,data:{flightData:[b],canonicalUrl:void 0,couldBeIntercepted:!!h,prerendered:g,postponed:y,staleTime:-1},tree:S.tree,prefetchCache:S.prefetchCache,nextUrl:S.nextUrl,kind:g?l.PrefetchKind.FULL:l.PrefetchKind.AUTO})}return S}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1387:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{addRefreshMarkerToActiveParallelSegments:function(){return function e(t,r){let[n,o,,u]=t;for(let l in n.includes(a.PAGE_SEGMENT_KEY)&&"refresh"!==u&&(t[2]=r,t[3]="refresh"),o)e(o[l],r)}},refreshInactiveParallelSegments:function(){return u}});let n=r(655),o=r(4091),a=r(6090);async function u(e){let t=new Set;await l({...e,rootTree:e.updatedTree,fetchedSegments:t})}async function l(e){let{state:t,updatedTree:r,updatedCache:a,includeNextUrl:u,fetchedSegments:i,rootTree:c=r,canonicalUrl:s}=e,[,f,d,p]=r,h=[];if(d&&d!==s&&"refresh"===p&&!i.has(d)){i.add(d);let e=(0,o.fetchServerResponse)(new URL(d,location.origin),{flightRouterState:[c[0],c[1],c[2],"refetch"],nextUrl:u?t.nextUrl:null}).then(e=>{let{flightData:t}=e;if("string"!=typeof t)for(let e of t)(0,n.applyFlightData)(a,a,e)});h.push(e)}for(let e in f){let r=l({state:t,updatedTree:f[e],updatedCache:a,includeNextUrl:u,fetchedSegments:i,rootTree:c,canonicalUrl:s});h.push(r)}await Promise.all(h)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1394:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{AppRouterContext:function(){return o},GlobalLayoutRouterContext:function(){return u},LayoutRouterContext:function(){return a},MissingSlotContext:function(){return i},TemplateContext:function(){return l}});let n=r(306)._(r(2115)),o=n.default.createContext(null),a=n.default.createContext(null),u=n.default.createContext(null),l=n.default.createContext(null),i=n.default.createContext(new Set)},1426:(e,t,r)=>{"use strict";var n=r(7358),o=Symbol.for("react.transitional.element"),a=Symbol.for("react.portal"),u=Symbol.for("react.fragment"),l=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),s=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),y=Symbol.iterator,g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,b={};function m(e,t,r){this.props=e,this.context=t,this.refs=b,this.updater=r||g}function v(){}function E(e,t,r){this.props=e,this.context=t,this.refs=b,this.updater=r||g}m.prototype.isReactComponent={},m.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},m.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},v.prototype=m.prototype;var R=E.prototype=new v;R.constructor=E,_(R,m.prototype),R.isPureReactComponent=!0;var O=Array.isArray,P={H:null,A:null,T:null,S:null,V:null},S=Object.prototype.hasOwnProperty;function j(e,t,r,n,a,u){return{$$typeof:o,type:e,key:t,ref:void 0!==(r=u.ref)?r:null,props:u}}function T(e){return"object"==typeof e&&null!==e&&e.$$typeof===o}var w=/\/+/g;function M(e,t){var r,n;return"object"==typeof e&&null!==e&&null!=e.key?(r=""+e.key,n={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,function(e){return n[e]})):t.toString(36)}function x(){}function C(e,t,r){if(null==e)return e;var n=[],u=0;return!function e(t,r,n,u,l){var i,c,s,f=typeof t;("undefined"===f||"boolean"===f)&&(t=null);var d=!1;if(null===t)d=!0;else switch(f){case"bigint":case"string":case"number":d=!0;break;case"object":switch(t.$$typeof){case o:case a:d=!0;break;case h:return e((d=t._init)(t._payload),r,n,u,l)}}if(d)return l=l(t),d=""===u?"."+M(t,0):u,O(l)?(n="",null!=d&&(n=d.replace(w,"$&/")+"/"),e(l,r,n,"",function(e){return e})):null!=l&&(T(l)&&(i=l,c=n+(null==l.key||t&&t.key===l.key?"":(""+l.key).replace(w,"$&/")+"/")+d,l=j(i.type,c,void 0,void 0,void 0,i.props)),r.push(l)),1;d=0;var p=""===u?".":u+":";if(O(t))for(var g=0;g{"use strict";e.exports=r(576)},1648:(e,t)=>{"use strict";function r(e){var t;let[r,n,o,a]=e.slice(-4),u=e.slice(0,-4);return{pathToSegment:u.slice(0,-1),segmentPath:u,segment:null!=(t=u[u.length-1])?t:"",tree:r,seedData:n,head:o,isHeadPartial:a,isRootRender:4===e.length}}function n(e){return e.slice(2)}function o(e){return"string"==typeof e?e:e.map(r)}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getFlightDataPartsFromPath:function(){return r},getNextFlightSegmentPath:function(){return n},normalizeFlightData:function(){return o}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1677:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return f}});let n=r(4445),o=r(2603),a=r(6976),u=r(1752),l=r(5025),i=r(8455),c=r(7359),s=r(8514),f="undefined"==typeof window?function(e,t){return e}:function(e,t){switch(t.type){case n.ACTION_NAVIGATE:return(0,o.navigateReducer)(e,t);case n.ACTION_SERVER_PATCH:return(0,a.serverPatchReducer)(e,t);case n.ACTION_RESTORE:return(0,u.restoreReducer)(e,t);case n.ACTION_REFRESH:return(0,l.refreshReducer)(e,t);case n.ACTION_HMR_REFRESH:return(0,c.hmrRefreshReducer)(e,t);case n.ACTION_PREFETCH:return(0,i.prefetchReducer)(e,t);case n.ACTION_SERVER_ACTION:return(0,s.serverActionReducer)(e,t);default:throw Object.defineProperty(Error("Unknown action"),"__NEXT_ERROR_CODE",{value:"E295",enumerable:!1,configurable:!0})}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1752:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"restoreReducer",{enumerable:!0,get:function(){return a}});let n=r(3436),o=r(845);function a(e,t){var r;let{url:a,tree:u}=t,l=(0,n.createHrefFromUrl)(a),i=u||e.tree,c=e.cache;return{canonicalUrl:l,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:e.focusAndScrollRef,cache:c,prefetchCache:e.prefetchCache,tree:i,nextUrl:null!=(r=(0,o.extractPathFromFlightRouterState)(i))?r:a.pathname}}r(3223),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1893:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{STATIC_STALETIME_MS:function(){return p},createSeededPrefetchCacheEntry:function(){return c},getOrCreatePrefetchCacheEntry:function(){return i},prunePrefetchCache:function(){return f}});let n=r(4091),o=r(4445),a=r(8455);function u(e,t,r){let n=e.pathname;return(t&&(n+=e.search),r)?""+r+"%"+n:n}function l(e,t,r){return u(e,t===o.PrefetchKind.FULL,r)}function i(e){let{url:t,nextUrl:r,tree:n,prefetchCache:a,kind:l,allowAliasing:i=!0}=e,c=function(e,t,r,n,a){for(let l of(void 0===t&&(t=o.PrefetchKind.TEMPORARY),[r,null])){let r=u(e,!0,l),i=u(e,!1,l),c=e.search?r:i,s=n.get(c);if(s&&a){if(s.url.pathname===e.pathname&&s.url.search!==e.search)return{...s,aliased:!0};return s}let f=n.get(i);if(a&&e.search&&t!==o.PrefetchKind.FULL&&f&&!f.key.includes("%"))return{...f,aliased:!0}}if(t!==o.PrefetchKind.FULL&&a){for(let t of n.values())if(t.url.pathname===e.pathname&&!t.key.includes("%"))return{...t,aliased:!0}}}(t,l,r,a,i);return c?(c.status=h(c),c.kind!==o.PrefetchKind.FULL&&l===o.PrefetchKind.FULL&&c.data.then(e=>{if(!(Array.isArray(e.flightData)&&e.flightData.some(e=>e.isRootRender&&null!==e.seedData)))return s({tree:n,url:t,nextUrl:r,prefetchCache:a,kind:null!=l?l:o.PrefetchKind.TEMPORARY})}),l&&c.kind===o.PrefetchKind.TEMPORARY&&(c.kind=l),c):s({tree:n,url:t,nextUrl:r,prefetchCache:a,kind:l||o.PrefetchKind.TEMPORARY})}function c(e){let{nextUrl:t,tree:r,prefetchCache:n,url:a,data:u,kind:i}=e,c=u.couldBeIntercepted?l(a,i,t):l(a,i),s={treeAtTimeOfPrefetch:r,data:Promise.resolve(u),kind:i,prefetchTime:Date.now(),lastUsedTime:Date.now(),staleTime:-1,key:c,status:o.PrefetchCacheEntryStatus.fresh,url:a};return n.set(c,s),s}function s(e){let{url:t,kind:r,tree:u,nextUrl:i,prefetchCache:c}=e,s=l(t,r),f=a.prefetchQueue.enqueue(()=>(0,n.fetchServerResponse)(t,{flightRouterState:u,nextUrl:i,prefetchKind:r}).then(e=>{let r;if(e.couldBeIntercepted&&(r=function(e){let{url:t,nextUrl:r,prefetchCache:n,existingCacheKey:o}=e,a=n.get(o);if(!a)return;let u=l(t,a.kind,r);return n.set(u,{...a,key:u}),n.delete(o),u}({url:t,existingCacheKey:s,nextUrl:i,prefetchCache:c})),e.prerendered){let t=c.get(null!=r?r:s);t&&(t.kind=o.PrefetchKind.FULL,-1!==e.staleTime&&(t.staleTime=e.staleTime))}return e})),d={treeAtTimeOfPrefetch:u,data:f,kind:r,prefetchTime:Date.now(),lastUsedTime:null,staleTime:-1,key:s,status:o.PrefetchCacheEntryStatus.fresh,url:t};return c.set(s,d),d}function f(e){for(let[t,r]of e)h(r)===o.PrefetchCacheEntryStatus.expired&&e.delete(t)}let d=1e3*Number("0"),p=1e3*Number("300");function h(e){let{kind:t,prefetchTime:r,lastUsedTime:n,staleTime:a}=e;return -1!==a?Date.now(){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"actionAsyncStorageInstance",{enumerable:!0,get:function(){return n}});let n=(0,r(4054).createAsyncLocalStorage)()},2115:(e,t,r)=>{"use strict";e.exports=r(1426)},2130:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{createPrerenderSearchParamsForClientPage:function(){return p},createSearchParamsFromClient:function(){return s},createServerSearchParamsForMetadata:function(){return f},createServerSearchParamsForServerPage:function(){return d},makeErroringExoticSearchParamsForUseCache:function(){return b}});let n=r(1042),o=r(6378),a=r(5938),u=r(4940),l=r(3649),i=r(6431),c=r(1142);function s(e,t){let r=a.workUnitAsyncStorage.getStore();if(r)switch(r.type){case"prerender":case"prerender-ppr":case"prerender-legacy":return h(t,r)}return y(e,t)}r(2301);let f=d;function d(e,t){let r=a.workUnitAsyncStorage.getStore();if(r)switch(r.type){case"prerender":case"prerender-ppr":case"prerender-legacy":return h(t,r)}return y(e,t)}function p(e){if(e.forceStatic)return Promise.resolve({});let t=a.workUnitAsyncStorage.getStore();return t&&"prerender"===t.type?(0,l.makeHangingPromise)(t.renderSignal,"`searchParams`"):Promise.resolve({})}function h(e,t){return e.forceStatic?Promise.resolve({}):"prerender"===t.type?function(e,t){let r=g.get(t);if(r)return r;let a=(0,l.makeHangingPromise)(t.renderSignal,"`searchParams`"),u=new Proxy(a,{get(r,u,l){if(Object.hasOwn(a,u))return n.ReflectAdapter.get(r,u,l);switch(u){case"then":return(0,o.annotateDynamicAccess)("`await searchParams`, `searchParams.then`, or similar",t),n.ReflectAdapter.get(r,u,l);case"status":return(0,o.annotateDynamicAccess)("`use(searchParams)`, `searchParams.status`, or similar",t),n.ReflectAdapter.get(r,u,l);default:if("string"==typeof u&&!c.wellKnownProperties.has(u)){let r=(0,c.describeStringPropertyAccess)("searchParams",u),n=E(e,r);(0,o.abortAndThrowOnSynchronousRequestDataAccess)(e,r,n,t)}return n.ReflectAdapter.get(r,u,l)}},has(r,a){if("string"==typeof a){let r=(0,c.describeHasCheckingStringProperty)("searchParams",a),n=E(e,r);(0,o.abortAndThrowOnSynchronousRequestDataAccess)(e,r,n,t)}return n.ReflectAdapter.has(r,a)},ownKeys(){let r="`{...searchParams}`, `Object.keys(searchParams)`, or similar",n=E(e,r);(0,o.abortAndThrowOnSynchronousRequestDataAccess)(e,r,n,t)}});return g.set(t,u),u}(e.route,t):function(e,t){let r=g.get(e);if(r)return r;let a=Promise.resolve({}),u=new Proxy(a,{get(r,u,l){if(Object.hasOwn(a,u))return n.ReflectAdapter.get(r,u,l);switch(u){case"then":{let r="`await searchParams`, `searchParams.then`, or similar";e.dynamicShouldError?(0,c.throwWithStaticGenerationBailoutErrorWithDynamicError)(e.route,r):"prerender-ppr"===t.type?(0,o.postponeWithTracking)(e.route,r,t.dynamicTracking):(0,o.throwToInterruptStaticGeneration)(r,e,t);return}case"status":{let r="`use(searchParams)`, `searchParams.status`, or similar";e.dynamicShouldError?(0,c.throwWithStaticGenerationBailoutErrorWithDynamicError)(e.route,r):"prerender-ppr"===t.type?(0,o.postponeWithTracking)(e.route,r,t.dynamicTracking):(0,o.throwToInterruptStaticGeneration)(r,e,t);return}default:if("string"==typeof u&&!c.wellKnownProperties.has(u)){let r=(0,c.describeStringPropertyAccess)("searchParams",u);e.dynamicShouldError?(0,c.throwWithStaticGenerationBailoutErrorWithDynamicError)(e.route,r):"prerender-ppr"===t.type?(0,o.postponeWithTracking)(e.route,r,t.dynamicTracking):(0,o.throwToInterruptStaticGeneration)(r,e,t)}return n.ReflectAdapter.get(r,u,l)}},has(r,a){if("string"==typeof a){let r=(0,c.describeHasCheckingStringProperty)("searchParams",a);return e.dynamicShouldError?(0,c.throwWithStaticGenerationBailoutErrorWithDynamicError)(e.route,r):"prerender-ppr"===t.type?(0,o.postponeWithTracking)(e.route,r,t.dynamicTracking):(0,o.throwToInterruptStaticGeneration)(r,e,t),!1}return n.ReflectAdapter.has(r,a)},ownKeys(){let r="`{...searchParams}`, `Object.keys(searchParams)`, or similar";e.dynamicShouldError?(0,c.throwWithStaticGenerationBailoutErrorWithDynamicError)(e.route,r):"prerender-ppr"===t.type?(0,o.postponeWithTracking)(e.route,r,t.dynamicTracking):(0,o.throwToInterruptStaticGeneration)(r,e,t)}});return g.set(e,u),u}(e,t)}function y(e,t){return t.forceStatic?Promise.resolve({}):function(e,t){let r=g.get(e);if(r)return r;let n=Promise.resolve(e);return g.set(e,n),Object.keys(e).forEach(r=>{c.wellKnownProperties.has(r)||Object.defineProperty(n,r,{get(){let n=a.workUnitAsyncStorage.getStore();return(0,o.trackDynamicDataInDynamicRender)(t,n),e[r]},set(e){Object.defineProperty(n,r,{value:e,writable:!0,enumerable:!0})},enumerable:!0,configurable:!0})}),n}(e,t)}let g=new WeakMap,_=new WeakMap;function b(e){let t=_.get(e);if(t)return t;let r=Promise.resolve({}),o=new Proxy(r,{get:(t,o,a)=>(Object.hasOwn(r,o)||"string"!=typeof o||"then"!==o&&c.wellKnownProperties.has(o)||(0,c.throwForSearchParamsAccessInUseCache)(e.route),n.ReflectAdapter.get(t,o,a)),has:(t,r)=>("string"!=typeof r||"then"!==r&&c.wellKnownProperties.has(r)||(0,c.throwForSearchParamsAccessInUseCache)(e.route),n.ReflectAdapter.has(t,r)),ownKeys(){(0,c.throwForSearchParamsAccessInUseCache)(e.route)}});return _.set(e,o),o}let m=(0,i.createDedupedByCallsiteServerErrorLoggerDev)(E),v=(0,i.createDedupedByCallsiteServerErrorLoggerDev)(function(e,t,r){let n=e?`Route "${e}" `:"This route ";return Object.defineProperty(Error(`${n}used ${t}. \`searchParams\` should be awaited before using its properties. The following properties were not available through enumeration because they conflict with builtin or well-known property names: ${function(e){switch(e.length){case 0:throw Object.defineProperty(new u.InvariantError("Expected describeListOfPropertyNames to be called with a non-empty list of strings."),"__NEXT_ERROR_CODE",{value:"E531",enumerable:!1,configurable:!0});case 1:return`\`${e[0]}\``;case 2:return`\`${e[0]}\` and \`${e[1]}\``;default:{let t="";for(let r=0;r{"use strict";function n(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}r.r(t),r.d(t,{_:()=>n})},2170:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DecodeError:function(){return h},MiddlewareNotFoundError:function(){return b},MissingStaticPage:function(){return _},NormalizeError:function(){return y},PageNotFoundError:function(){return g},SP:function(){return d},ST:function(){return p},WEB_VITALS:function(){return r},execOnce:function(){return n},getDisplayName:function(){return i},getLocationOrigin:function(){return u},getURL:function(){return l},isAbsoluteUrl:function(){return a},isResSent:function(){return c},loadGetInitialProps:function(){return f},normalizeRepeatedSlashes:function(){return s},stringifyError:function(){return m}});let r=["CLS","FCP","FID","INP","LCP","TTFB"];function n(e){let t,r=!1;return function(){for(var n=arguments.length,o=Array(n),a=0;ao.test(e);function u(){let{protocol:e,hostname:t,port:r}=window.location;return e+"//"+t+(r?":"+r:"")}function l(){let{href:e}=window.location,t=u();return e.substring(t.length)}function i(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function c(e){return e.finished||e.headersSent}function s(e){let t=e.split("?");return t[0].replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function f(e,t){let r=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await f(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(r&&c(r))return n;if(!n)throw Object.defineProperty(Error('"'+i(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.'),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return n}let d="undefined"!=typeof performance,p=d&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);class h extends Error{}class y extends Error{}class g extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}}class _ extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}}class b extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}}function m(e){return JSON.stringify({message:e.message,stack:e.stack})}},2301:(e,t,r)=>{"use strict";var n=r(7358);Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{atLeastOneTask:function(){return u},scheduleImmediate:function(){return a},scheduleOnNextTick:function(){return o},waitAtLeastOneReactRenderTask:function(){return l}});let o=e=>{Promise.resolve().then(()=>{n.nextTick(e)})},a=e=>{setImmediate(e)};function u(){return new Promise(e=>a(e))}function l(){return new Promise(e=>setImmediate(e))}},2328:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HTTPAccessFallbackBoundary",{enumerable:!0,get:function(){return s}});let n=r(9955),o=r(5155),a=n._(r(2115)),u=r(2380),l=r(2469);r(2363);let i=r(1394);class c extends a.default.Component{componentDidCatch(){}static getDerivedStateFromError(e){if((0,l.isHTTPAccessFallbackError)(e))return{triggeredStatus:(0,l.getAccessFallbackHTTPStatus)(e)};throw e}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.triggeredStatus?{triggeredStatus:void 0,previousPathname:e.pathname}:{triggeredStatus:t.triggeredStatus,previousPathname:e.pathname}}render(){let{notFound:e,forbidden:t,unauthorized:r,children:n}=this.props,{triggeredStatus:a}=this.state,u={[l.HTTPAccessErrorStatus.NOT_FOUND]:e,[l.HTTPAccessErrorStatus.FORBIDDEN]:t,[l.HTTPAccessErrorStatus.UNAUTHORIZED]:r};if(a){let i=a===l.HTTPAccessErrorStatus.NOT_FOUND&&e,c=a===l.HTTPAccessErrorStatus.FORBIDDEN&&t,s=a===l.HTTPAccessErrorStatus.UNAUTHORIZED&&r;return i||c||s?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("meta",{name:"robots",content:"noindex"}),!1,u[a]]}):n}return n}constructor(e){super(e),this.state={triggeredStatus:void 0,previousPathname:e.pathname}}}function s(e){let{notFound:t,forbidden:r,unauthorized:n,children:l}=e,s=(0,u.useUntrackedPathname)(),f=(0,a.useContext)(i.MissingSlotContext);return t||r||n?(0,o.jsx)(c,{pathname:s,notFound:t,forbidden:r,unauthorized:n,missingSlots:f,children:l}):(0,o.jsx)(o.Fragment,{children:l})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2344:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{addSearchParamsToPageSegments:function(){return f},handleAliasedPrefetchEntry:function(){return s}});let n=r(6090),o=r(3423),a=r(1053),u=r(3436),l=r(5404),i=r(8645),c=r(7344);function s(e,t,r,s){let d,p=e.tree,h=e.cache,y=(0,u.createHrefFromUrl)(r);for(let e of t){if(!function e(t){if(!t)return!1;let r=t[2];if(t[3])return!0;for(let t in r)if(e(r[t]))return!0;return!1}(e.seedData))continue;let t=e.tree;t=f(t,Object.fromEntries(r.searchParams));let{seedData:u,isRootRender:c,pathToSegment:s}=e,g=["",...s];t=f(t,Object.fromEntries(r.searchParams));let _=(0,a.applyRouterStatePatchToTree)(g,p,t,y),b=(0,o.createEmptyCacheNode)();if(c&&u){let e=u[1],r=u[3];b.loading=r,b.rsc=e,function e(t,r,o,a){if(0!==Object.keys(o[1]).length)for(let u in o[1]){let i;let c=o[1][u],s=c[0],f=(0,l.createRouterCacheKey)(s),d=null!==a&&void 0!==a[2][u]?a[2][u]:null;if(null!==d){let e=d[1],t=d[3];i={lazyData:null,rsc:s.includes(n.PAGE_SEGMENT_KEY)?null:e,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:t}}else i={lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:null};let p=t.parallelRoutes.get(u);p?p.set(f,i):t.parallelRoutes.set(u,new Map([[f,i]])),e(i,r,c,d)}}(b,h,t,u)}else b.rsc=h.rsc,b.prefetchRsc=h.prefetchRsc,b.loading=h.loading,b.parallelRoutes=new Map(h.parallelRoutes),(0,i.fillCacheWithNewSubTreeDataButOnlyLoading)(b,h,e);_&&(p=_,h=b,d=!0)}return!!d&&(s.patchedTree=p,s.cache=h,s.canonicalUrl=y,s.hashFragment=r.hash,(0,c.handleMutable)(e,s))}function f(e,t){let[r,o,...a]=e;if(r.includes(n.PAGE_SEGMENT_KEY))return[(0,n.addSearchParamsIfPageSegment)(r,t),o,...a];let u={};for(let[e,r]of Object.entries(o))u[e]=f(r,t);return[r,u,...a]}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2363:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return r}});let r=e=>{}},2380:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"useUntrackedPathname",{enumerable:!0,get:function(){return a}});let n=r(2115),o=r(8703);function a(){return!function(){if("undefined"==typeof window){let{workAsyncStorage:e}=r(5861),t=e.getStore();if(!t)return!1;let{fallbackRouteParams:n}=t;return!!n&&0!==n.size}return!1}()?(0,n.useContext)(o.PathnameContext):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2469:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{HTTPAccessErrorStatus:function(){return r},HTTP_ERROR_FALLBACK_ERROR_CODE:function(){return o},getAccessFallbackErrorTypeByStatus:function(){return l},getAccessFallbackHTTPStatus:function(){return u},isHTTPAccessFallbackError:function(){return a}});let r={NOT_FOUND:404,FORBIDDEN:403,UNAUTHORIZED:401},n=new Set(Object.values(r)),o="NEXT_HTTP_ERROR_FALLBACK";function a(e){if("object"!=typeof e||null===e||!("digest"in e)||"string"!=typeof e.digest)return!1;let[t,r]=e.digest.split(";");return t===o&&n.has(Number(r))}function u(e){return Number(e.digest.split(";")[1])}function l(e){switch(e){case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";default:return}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2603:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleExternalUrl:function(){return m},navigateReducer:function(){return function e(t,r){let{url:E,isExternalUrl:R,navigateType:O,shouldScroll:P,allowAliasing:S}=r,j={},{hash:T}=E,w=(0,o.createHrefFromUrl)(E),M="push"===O;if((0,g.prunePrefetchCache)(t.prefetchCache),j.preserveCustomHistoryState=!1,j.pendingPush=M,R)return m(t,j,E.toString(),M);if(document.getElementById("__next-page-redirect"))return m(t,j,w,M);let x=(0,g.getOrCreatePrefetchCacheEntry)({url:E,nextUrl:t.nextUrl,tree:t.tree,prefetchCache:t.prefetchCache,allowAliasing:S}),{treeAtTimeOfPrefetch:C,data:A}=x;return d.prefetchQueue.bump(A),A.then(d=>{let{flightData:g,canonicalUrl:R,postponed:O}=d,S=!1;if(x.lastUsedTime||(x.lastUsedTime=Date.now(),S=!0),"string"==typeof g)return m(t,j,g,M);let A=R?(0,o.createHrefFromUrl)(R):w;if(T&&t.canonicalUrl.split("#",1)[0]===A.split("#",1)[0])return j.onlyHashChange=!0,j.canonicalUrl=A,j.shouldScroll=P,j.hashFragment=T,j.scrollableSegments=[],(0,s.handleMutable)(t,j);if(x.aliased){let n=(0,b.handleAliasedPrefetchEntry)(t,g,E,j);return!1===n?e(t,{...r,allowAliasing:!1}):n}let D=t.tree,N=t.cache,k=[];for(let e of g){let{pathToSegment:r,seedData:o,head:s,isHeadPartial:d,isRootRender:g}=e,b=e.tree,R=["",...r],P=(0,u.applyRouterStatePatchToTree)(R,D,b,w);if(null===P&&(P=(0,u.applyRouterStatePatchToTree)(R,C,b,w)),null!==P){if(o&&g&&O){let e=(0,y.startPPRNavigation)(N,D,b,o,s,d,k);if(null!==e){if(null===e.route)return m(t,j,w,M);P=e.route;let r=e.node;null!==r&&(j.cache=r);let o=e.dynamicRequestTree;if(null!==o){let r=(0,n.fetchServerResponse)(E,{flightRouterState:o,nextUrl:t.nextUrl});(0,y.listenForDynamicRequest)(e,r)}}else P=b}else{if((0,i.isNavigatingToNewRootLayout)(D,P))return m(t,j,w,M);let n=(0,p.createEmptyCacheNode)(),o=!1;for(let t of(x.status!==c.PrefetchCacheEntryStatus.stale||S?o=(0,f.applyFlightData)(N,n,e,x):(o=function(e,t,r,n){let o=!1;for(let a of(e.rsc=t.rsc,e.prefetchRsc=t.prefetchRsc,e.loading=t.loading,e.parallelRoutes=new Map(t.parallelRoutes),v(n).map(e=>[...r,...e])))(0,_.clearCacheNodeDataForSegmentPath)(e,t,a),o=!0;return o}(n,N,r,b),x.lastUsedTime=Date.now()),(0,l.shouldHardNavigate)(R,D)?(n.rsc=N.rsc,n.prefetchRsc=N.prefetchRsc,(0,a.invalidateCacheBelowFlightSegmentPath)(n,N,r),j.cache=n):o&&(j.cache=n,N=n),v(b))){let e=[...r,...t];e[e.length-1]!==h.DEFAULT_SEGMENT_KEY&&k.push(e)}}D=P}}return j.patchedTree=D,j.canonicalUrl=A,j.scrollableSegments=k,j.hashFragment=T,j.shouldScroll=P,(0,s.handleMutable)(t,j)},()=>t)}}});let n=r(4091),o=r(3436),a=r(5411),u=r(1053),l=r(8500),i=r(6449),c=r(4445),s=r(7344),f=r(655),d=r(8455),p=r(3423),h=r(6090),y=r(3223),g=r(1893),_=r(608),b=r(2344);function m(e,t,r,n){return t.mpaNavigation=!0,t.canonicalUrl=r,t.pendingPush=n,t.scrollableSegments=void 0,(0,s.handleMutable)(e,t)}function v(e){let t=[],[r,n]=e;if(0===Object.keys(n).length)return[[r]];for(let[e,o]of Object.entries(n))for(let n of v(o))""===r?t.push([e,...n]):t.push([r,e,...n]);return t}r(5245),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2633:(e,t)=>{"use strict";function r(e,t){let r=new URL(e);return r.search="",{href:r.href,nextUrl:t}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createCacheKey",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2669:(e,t,r)=>{"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=r(9248)},2707:(e,t)=>{"use strict";function r(e){return null!==e&&"object"==typeof e&&"then"in e&&"function"==typeof e.then}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isThenable",{enumerable:!0,get:function(){return r}})},2836:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ACTION_HEADER:function(){return n},FLIGHT_HEADERS:function(){return s},NEXT_DID_POSTPONE_HEADER:function(){return p},NEXT_HMR_REFRESH_HEADER:function(){return l},NEXT_IS_PRERENDER_HEADER:function(){return g},NEXT_REWRITTEN_PATH_HEADER:function(){return h},NEXT_REWRITTEN_QUERY_HEADER:function(){return y},NEXT_ROUTER_PREFETCH_HEADER:function(){return a},NEXT_ROUTER_SEGMENT_PREFETCH_HEADER:function(){return u},NEXT_ROUTER_STALE_TIME_HEADER:function(){return d},NEXT_ROUTER_STATE_TREE_HEADER:function(){return o},NEXT_RSC_UNION_QUERY:function(){return f},NEXT_URL:function(){return i},RSC_CONTENT_TYPE_HEADER:function(){return c},RSC_HEADER:function(){return r}});let r="RSC",n="Next-Action",o="Next-Router-State-Tree",a="Next-Router-Prefetch",u="Next-Router-Segment-Prefetch",l="Next-HMR-Refresh",i="Next-Url",c="text/x-component",s=[r,o,a,l,u],f="_rsc",d="x-nextjs-stale-time",p="x-nextjs-postponed",h="x-nextjs-rewritten-path",y="x-nextjs-rewritten-query",g="x-nextjs-prerender";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3099:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{EntryStatus:function(){return h},FetchStrategy:function(){return y},convertRouteTreeToFlightRouterState:function(){return function e(t){let r={};if(null!==t.slots)for(let n in t.slots)r[n]=e(t.slots[n]);return[t.segment,r,null,null,t.isRootLayout]}},createDetachedSegmentCacheEntry:function(){return C},fetchRouteOnCacheMiss:function(){return X},fetchSegmentOnCacheMiss:function(){return K},fetchSegmentPrefetchesUsingDynamicRequest:function(){return G},getCurrentCacheVersion:function(){return E},readExactRouteCacheEntry:function(){return O},readOrCreateRevalidatingSegmentEntry:function(){return M},readOrCreateRouteCacheEntry:function(){return T},readOrCreateSegmentCacheEntry:function(){return w},readRouteCacheEntry:function(){return P},readSegmentCacheEntry:function(){return S},resetRevalidatingSegmentEntry:function(){return k},revalidateEntireCache:function(){return R},upgradeToPendingSegment:function(){return A},upsertSegmentEntry:function(){return x},waitForSegmentCacheEntry:function(){return j}});let n=r(2836),o=r(4091),a=r(8592),u=r(8127),l=r(3436),i=r(7864),c=r(1096),s=r(6127),f=r(1648),d=r(1893),p=r(8173);var h=function(e){return e[e.Empty=0]="Empty",e[e.Pending=1]="Pending",e[e.Fulfilled=2]="Fulfilled",e[e.Rejected=3]="Rejected",e}({}),y=function(e){return e[e.PPR=0]="PPR",e[e.Full=1]="Full",e[e.LoadingBoundary=2]="LoadingBoundary",e}({});let g=(0,i.createTupleMap)(),_=(0,c.createLRU)(0xa00000,U),b=new Map,m=(0,c.createLRU)(0x3200000,I),v=0;function E(){return v}function R(e,t){v++,g=(0,i.createTupleMap)(),_=(0,c.createLRU)(0xa00000,U),b=new Map,m=(0,c.createLRU)(0x3200000,I),(0,p.pingVisibleLinks)(e,t)}function O(e,t,r){let n=null===r?[t]:[t,r],o=g.get(n);if(null!==o){var a,u;if(o.staleAt>e)return _.put(o),o;a=o,u=n,F(a),g.delete(u),_.delete(a)}return null}function P(e,t){let r=O(e,t.href,null);return null===r||r.couldBeIntercepted?O(e,t.href,t.nextUrl):r}function S(e,t){let r=b.get(t);if(void 0!==r){if(r.staleAt>e)return m.put(r),r;{let n=r.revalidating;if(null!==n){let r=x(e,t,n);if(null!==r&&r.staleAt>e)return r}else D(r,t)}}return null}function j(e){let t=e.promise;return null===t&&(t=e.promise=J()),t.promise}function T(e,t){let r=t.key,n=P(e,r);if(null!==n)return n;let o={canonicalUrl:null,status:0,blockedTasks:null,tree:null,head:null,isHeadPartial:!0,staleAt:1/0,couldBeIntercepted:!0,isPPREnabled:!1,keypath:null,next:null,prev:null,size:0},a=null===r.nextUrl?[r.href]:[r.href,r.nextUrl];return g.set(a,o),o.keypath=a,_.put(o),o}function w(e,t,r){let n=S(e,r);if(null!==n)return n;let o=C(t.staleAt);return b.set(r,o),o.key=r,m.put(o),o}function M(e,t){let r=function(e,t){let r=t.revalidating;if(null!==r){if(r.staleAt>e)return r;N(t)}return null}(e,t);if(null!==r)return r;let n=C(t.staleAt);return t.revalidating=n,n}function x(e,t,r){let n=S(e,t);if(null!==n){if(r.isPartial&&!n.isPartial)return r.status=3,r.loading=null,r.rsc=null,null;D(n,t)}return b.set(t,r),r.key=t,m.put(r),r}function C(e){return{status:0,fetchStrategy:0,revalidating:null,rsc:null,loading:null,staleAt:e,isPartial:!0,promise:null,key:null,next:null,prev:null,size:0}}function A(e,t){return e.status=1,e.fetchStrategy=t,e}function D(e,t){L(e),b.delete(t),m.delete(e),N(e)}function N(e){let t=e.revalidating;null!==t&&(L(t),e.revalidating=null)}function k(e){N(e);let t=C(e.staleAt);return e.revalidating=t,t}function U(e){let t=e.keypath;null!==t&&(e.keypath=null,F(e),g.delete(t))}function I(e){let t=e.key;null!==t&&(e.key=null,L(e),b.delete(t))}function L(e){1===e.status&&null!==e.promise&&(e.promise.resolve(null),e.promise=null)}function F(e){let t=e.blockedTasks;if(null!==t){for(let e of t)(0,a.pingPrefetchTask)(e);e.blockedTasks=null}}function H(e,t,r,n,o,a,u,l){return e.status=2,e.tree=t,e.head=r,e.isHeadPartial=n,e.staleAt=o,e.couldBeIntercepted=a,e.canonicalUrl=u,e.isPPREnabled=l,F(e),e}function B(e,t,r,n,o){return e.status=2,e.rsc=t,e.loading=r,e.staleAt=n,e.isPartial=o,null!==e.promise&&(e.promise.resolve(e),e.promise=null),e}function $(e,t){e.status=3,e.staleAt=t,F(e)}function W(e,t){e.status=3,e.staleAt=t,null!==e.promise&&(e.promise.resolve(null),e.promise=null)}async function X(e,t){let r=t.key,a=r.href,i=r.nextUrl;try{let t=await q(a,"/_tree",i);if(!t||!t.ok||204===t.status||!t.body)return $(e,Date.now()+1e4),null;let r=t.redirected?(0,l.createHrefFromUrl)((0,o.urlToUrlWithoutFlightMarker)(t.url)):a,c=t.headers.get("vary"),p=null!==c&&c.includes(n.NEXT_URL),h=J(),y="2"===t.headers.get(n.NEXT_DID_POSTPONE_HEADER);if(y){let n=Y(t.body,h.resolve,function(t){_.updateSize(e,t)}),a=await (0,o.createFromNextReadableStream)(n);if(a.buildId!==(0,u.getAppBuildId)())return $(e,Date.now()+1e4),null;let l=1e3*a.staleTime;H(e,function e(t,r){let n=null,o=t.slots;if(null!==o)for(let t in n={},o){let a=o[t],u=a.segment,l=(0,s.encodeChildSegmentKey)(r,t,(0,s.encodeSegment)(u));n[t]=e(a,l)}return{key:r,segment:t.segment,slots:n,isRootLayout:t.isRootLayout}}(a.tree,s.ROOT_SEGMENT_KEY),a.head,a.isHeadPartial,Date.now()+l,p,r,y)}else{let a=Y(t.body,h.resolve,function(t){_.updateSize(e,t)}),l=await (0,o.createFromNextReadableStream)(a);!function(e,t,r,o,a,l,i){if(r.b!==(0,u.getAppBuildId)()){$(o,e+1e4);return}let c=(0,f.normalizeFlightData)(r.f);if("string"==typeof c||1!==c.length){$(o,e+1e4);return}let p=c[0];if(!p.isRootRender){$(o,e+1e4);return}let h=p.tree,y=t.headers.get(n.NEXT_ROUTER_STALE_TIME_HEADER),g=null!==y?1e3*parseInt(y,10):d.STATIC_STALETIME_MS;H(o,function e(t,r){let n=null,o=t[1];for(let t in o){let a=o[t],u=a[0],l=e(a,(0,s.encodeChildSegmentKey)(r,t,(0,s.encodeSegment)(u)));null===n?n={[t]:l}:n[t]=l}return{key:r,segment:t[0],slots:n,isRootLayout:!0===t[4]}}(h,s.ROOT_SEGMENT_KEY),p.head,p.isHeadPartial,e+g,a,l,i)}(Date.now(),t,l,e,p,r,y)}if(!p&&null!==i){let t=[a,i];if(g.get(t)===e){g.delete(t);let r=[a];g.set(r,e),e.keypath=r}}return{value:null,closed:h.promise}}catch(t){return $(e,Date.now()+1e4),null}}async function K(e,t,r,a){let l=r.href;try{let i=await q(l,a===s.ROOT_SEGMENT_KEY?"/_index":a,r.nextUrl);if(!i||!i.ok||204===i.status||"2"!==i.headers.get(n.NEXT_DID_POSTPONE_HEADER)||!i.body)return W(t,Date.now()+1e4),null;let c=J(),f=Y(i.body,c.resolve,function(e){m.updateSize(t,e)}),d=await (0,o.createFromNextReadableStream)(f);if(d.buildId!==(0,u.getAppBuildId)())return W(t,Date.now()+1e4),null;return{value:B(t,d.rsc,d.loading,e.staleAt,d.isPartial),closed:c.promise}}catch(e){return W(t,Date.now()+1e4),null}}async function G(e,t,r,a,l){let i=e.key.href,c=e.key.nextUrl,p={[n.RSC_HEADER]:"1",[n.NEXT_ROUTER_STATE_TREE_HEADER]:encodeURIComponent(JSON.stringify(a))};null!==c&&(p[n.NEXT_URL]=c),1!==r&&(p[n.NEXT_ROUTER_PREFETCH_HEADER]="1");try{let e=await V(i,p);if(!e||!e.ok||!e.body)return z(l,Date.now()+1e4),null;let r=J(),a=null,c=Y(e.body,r.resolve,function(e){if(null===a)return;let t=e/a.length;for(let e of a)m.updateSize(e,t)}),h=await (0,o.createFromNextReadableStream)(c);return a=function(e,t,r,o,a){if(r.b!==(0,u.getAppBuildId)())return z(a,e+1e4),null;let l=(0,f.normalizeFlightData)(r.f);if("string"==typeof l)return null;for(let r of l){let u=r.seedData;if(null!==u){let l=r.segmentPath,i=s.ROOT_SEGMENT_KEY;for(let e=0;e{e=r,t=n});return{resolve:e,reject:t,promise:r}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3223:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{abortTask:function(){return p},listenForDynamicRequest:function(){return d},startPPRNavigation:function(){return i},updateCacheNodeOnPopstateRestoration:function(){return function e(t,r){let n=r[1],o=t.parallelRoutes,u=new Map(o);for(let t in n){let r=n[t],l=r[0],i=(0,a.createRouterCacheKey)(l),c=o.get(t);if(void 0!==c){let n=c.get(i);if(void 0!==n){let o=e(n,r),a=new Map(c);a.set(i,o),u.set(t,a)}}}let l=t.rsc,i=g(l)&&"pending"===l.status;return{lazyData:null,rsc:l,head:t.head,prefetchHead:i?t.prefetchHead:[null,null],prefetchRsc:i?t.prefetchRsc:null,loading:t.loading,parallelRoutes:u}}}});let n=r(6090),o=r(4682),a=r(5404),u=r(6449),l={route:null,node:null,dynamicRequestTree:null,children:null};function i(e,t,r,u,i,f,d){return function e(t,r,u,i,f,d,p,h,y){let g=r[1],_=u[1],b=null!==f?f[2]:null;i||!0!==u[4]||(i=!0);let m=t.parallelRoutes,v=new Map(m),E={},R=null,O=!1,P={};for(let t in _){let r;let u=_[t],s=g[t],f=m.get(t),S=null!==b?b[t]:null,j=u[0],T=h.concat([t,j]),w=(0,a.createRouterCacheKey)(j),M=void 0!==s?s[0]:void 0,x=void 0!==f?f.get(w):void 0;if(null!==(r=j===n.DEFAULT_SEGMENT_KEY?void 0!==s?{route:s,node:null,dynamicRequestTree:null,children:null}:c(s,u,i,void 0!==S?S:null,d,p,T,y):void 0!==s&&void 0!==M&&(0,o.matchSegment)(j,M)&&void 0!==x&&void 0!==s?e(x,s,u,i,S,d,p,T,y):c(s,u,i,void 0!==S?S:null,d,p,T,y))){if(null===r.route)return l;null===R&&(R=new Map),R.set(t,r);let e=r.node;if(null!==e){let r=new Map(f);r.set(w,e),v.set(t,r)}let n=r.route;E[t]=n;let o=r.dynamicRequestTree;null!==o?(O=!0,P[t]=o):P[t]=n}else E[t]=u,P[t]=u}if(null===R)return null;let S={lazyData:null,rsc:t.rsc,prefetchRsc:t.prefetchRsc,head:t.head,prefetchHead:t.prefetchHead,loading:t.loading,parallelRoutes:v};return{route:s(u,E),node:S,dynamicRequestTree:O?s(u,P):null,children:R}}(e,t,r,!1,u,i,f,[],d)}function c(e,t,r,n,o,i,c,d){return!r&&(void 0===e||(0,u.isNavigatingToNewRootLayout)(e,t))?l:function e(t,r,n,o,u,l){if(null===r)return f(t,null,n,o,u,l);let i=t[1],c=r[4],d=0===Object.keys(i).length;if(c||o&&d)return f(t,r,n,o,u,l);let p=r[2],h=new Map,y=new Map,g={},_=!1;if(d)l.push(u);else for(let t in i){let r=i[t],c=null!==p?p[t]:null,s=r[0],f=u.concat([t,s]),d=(0,a.createRouterCacheKey)(s),b=e(r,c,n,o,f,l);h.set(t,b);let m=b.dynamicRequestTree;null!==m?(_=!0,g[t]=m):g[t]=r;let v=b.node;if(null!==v){let e=new Map;e.set(d,v),y.set(t,e)}}return{route:t,node:{lazyData:null,rsc:r[1],prefetchRsc:null,head:d?n:null,prefetchHead:null,loading:r[3],parallelRoutes:y},dynamicRequestTree:_?s(t,g):null,children:h}}(t,n,o,i,c,d)}function s(e,t){let r=[e[0],t];return 2 in e&&(r[2]=e[2]),3 in e&&(r[3]=e[3]),4 in e&&(r[4]=e[4]),r}function f(e,t,r,n,o,u){let l=s(e,e[1]);return l[3]="refetch",{route:e,node:function e(t,r,n,o,u,l){let i=t[1],c=null!==r?r[2]:null,s=new Map;for(let t in i){let r=i[t],f=null!==c?c[t]:null,d=r[0],p=u.concat([t,d]),h=(0,a.createRouterCacheKey)(d),y=e(r,void 0===f?null:f,n,o,p,l),g=new Map;g.set(h,y),s.set(t,g)}let f=0===s.size;f&&l.push(u);let d=null!==r?r[1]:null,p=null!==r?r[3]:null;return{lazyData:null,parallelRoutes:s,prefetchRsc:void 0!==d?d:null,prefetchHead:f?n:[null,null],loading:void 0!==p?p:null,rsc:_(),head:f?_():null}}(e,t,r,n,o,u),dynamicRequestTree:l,children:null}}function d(e,t){t.then(t=>{let{flightData:r}=t;if("string"!=typeof r){for(let t of r){let{segmentPath:r,tree:n,seedData:u,head:l}=t;u&&!function(e,t,r,n,u){let l=e;for(let e=0;e{p(e,t)})}function p(e,t){let r=e.node;if(null===r)return;let n=e.children;if(null===n)h(e.route,r,t);else for(let e of n.values())p(e,t);e.dynamicRequestTree=null}function h(e,t,r){let n=e[1],o=t.parallelRoutes;for(let e in n){let t=n[e],u=o.get(e);if(void 0===u)continue;let l=t[0],i=(0,a.createRouterCacheKey)(l),c=u.get(i);void 0!==c&&h(t,c,r)}let u=t.rsc;g(u)&&(null===r?u.resolve(null):u.reject(r));let l=t.head;g(l)&&l.resolve(null)}let y=Symbol();function g(e){return e&&e.tag===y}function _(){let e,t;let r=new Promise((r,n)=>{e=r,t=n});return r.status="pending",r.resolve=t=>{"pending"===r.status&&(r.status="fulfilled",r.value=t,e(t))},r.reject=e=>{"pending"===r.status&&(r.status="rejected",r.reason=e,t(e))},r.tag=y,r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3355:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"findSourceMapURL",{enumerable:!0,get:function(){return r}});let r=void 0;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3423:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{createEmptyCacheNode:function(){return x},createPrefetchURL:function(){return w},default:function(){return N}});let n=r(9955),o=r(5155),a=n._(r(2115)),u=r(1394),l=r(4445),i=r(3436),c=r(8703),s=r(6494),f=n._(r(4835)),d=r(4283),p=r(9544),h=r(8262),y=r(6501),g=r(6674),_=r(9321),b=r(1129),m=r(6003),v=r(845),E=r(9935),R=r(9603);r(9824);let O=r(9100),P=r(7563),S=r(8455);r(8173);let j={};function T(e){return e.origin!==window.location.origin}function w(e){let t;if((0,d.isBot)(window.navigator.userAgent))return null;try{t=new URL((0,p.addBasePath)(e),window.location.href)}catch(t){throw Object.defineProperty(Error("Cannot prefetch '"+e+"' because it cannot be converted to a URL."),"__NEXT_ERROR_CODE",{value:"E234",enumerable:!1,configurable:!0})}return T(t)?null:t}function M(e){let{appRouterState:t}=e;return(0,a.useInsertionEffect)(()=>{let{tree:e,pushRef:r,canonicalUrl:n}=t,o={...r.preserveCustomHistoryState?window.history.state:{},__NA:!0,__PRIVATE_NEXTJS_INTERNALS_TREE:e};r.pendingPush&&(0,i.createHrefFromUrl)(new URL(window.location.href))!==n?(r.pendingPush=!1,window.history.pushState(o,"",n)):window.history.replaceState(o,"",n)},[t]),(0,a.useEffect)(()=>{},[t.nextUrl,t.tree]),null}function x(){return{lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:null}}function C(e){null==e&&(e={});let t=window.history.state,r=null==t?void 0:t.__NA;r&&(e.__NA=r);let n=null==t?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE;return n&&(e.__PRIVATE_NEXTJS_INTERNALS_TREE=n),e}function A(e){let{headCacheNode:t}=e,r=null!==t?t.head:null,n=null!==t?t.prefetchHead:null,o=null!==n?n:r;return(0,a.useDeferredValue)(r,o)}function D(e){let t,{actionQueue:r,assetPrefix:n,globalError:i}=e,[d,E]=(0,s.useReducer)(r),{canonicalUrl:x}=(0,s.useUnwrapState)(d),{searchParams:D,pathname:N}=(0,a.useMemo)(()=>{let e=new URL(x,"undefined"==typeof window?"http://n":window.location.href);return{searchParams:e.searchParams,pathname:(0,m.hasBasePath)(e.pathname)?(0,b.removeBasePath)(e.pathname):e.pathname}},[x]),k=(0,a.useCallback)(e=>{let{previousTree:t,serverResponse:r}=e;(0,a.startTransition)(()=>{E({type:l.ACTION_SERVER_PATCH,previousTree:t,serverResponse:r})})},[E]),U=(0,a.useCallback)((e,t,r)=>{let n=new URL((0,p.addBasePath)(e),location.href);return E({type:l.ACTION_NAVIGATE,url:n,isExternalUrl:T(n),locationSearch:location.search,shouldScroll:null==r||r,navigateType:t,allowAliasing:!0})},[E]);(0,R.useServerActionDispatcher)(E);let L=(0,a.useMemo)(()=>({back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(e,t)=>{let n=w(e);if(null!==n){var o;(0,S.prefetchReducer)(r.state,{type:l.ACTION_PREFETCH,url:n,kind:null!=(o=null==t?void 0:t.kind)?o:l.PrefetchKind.FULL})}},replace:(e,t)=>{void 0===t&&(t={}),(0,a.startTransition)(()=>{var r;U(e,"replace",null==(r=t.scroll)||r)})},push:(e,t)=>{void 0===t&&(t={}),(0,a.startTransition)(()=>{var r;U(e,"push",null==(r=t.scroll)||r)})},refresh:()=>{(0,a.startTransition)(()=>{E({type:l.ACTION_REFRESH,origin:window.location.origin})})},hmrRefresh:()=>{throw Object.defineProperty(Error("hmrRefresh can only be used in development mode. Please use refresh instead."),"__NEXT_ERROR_CODE",{value:"E485",enumerable:!1,configurable:!0})}}),[r,E,U]);(0,a.useEffect)(()=>{window.next&&(window.next.router=L)},[L]),(0,a.useEffect)(()=>{function e(e){var t;e.persisted&&(null==(t=window.history.state)?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE)&&(j.pendingMpaPath=void 0,E({type:l.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE}))}return window.addEventListener("pageshow",e),()=>{window.removeEventListener("pageshow",e)}},[E]),(0,a.useEffect)(()=>{function e(e){let t="reason"in e?e.reason:e.error;if((0,P.isRedirectError)(t)){e.preventDefault();let r=(0,O.getURLFromRedirectError)(t);(0,O.getRedirectTypeFromError)(t)===P.RedirectType.push?L.push(r,{}):L.replace(r,{})}}return window.addEventListener("error",e),window.addEventListener("unhandledrejection",e),()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",e)}},[L]);let{pushRef:F}=(0,s.useUnwrapState)(d);if(F.mpaNavigation){if(j.pendingMpaPath!==x){let e=window.location;F.pendingPush?e.assign(x):e.replace(x),j.pendingMpaPath=x}(0,a.use)(_.unresolvedThenable)}(0,a.useEffect)(()=>{let e=window.history.pushState.bind(window.history),t=window.history.replaceState.bind(window.history),r=e=>{var t;let r=window.location.href,n=null==(t=window.history.state)?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE;(0,a.startTransition)(()=>{E({type:l.ACTION_RESTORE,url:new URL(null!=e?e:r,r),tree:n})})};window.history.pushState=function(t,n,o){return(null==t?void 0:t.__NA)||(null==t?void 0:t._N)||(t=C(t),o&&r(o)),e(t,n,o)},window.history.replaceState=function(e,n,o){return(null==e?void 0:e.__NA)||(null==e?void 0:e._N)||(e=C(e),o&&r(o)),t(e,n,o)};let n=e=>{if(e.state){if(!e.state.__NA){window.location.reload();return}(0,a.startTransition)(()=>{E({type:l.ACTION_RESTORE,url:new URL(window.location.href),tree:e.state.__PRIVATE_NEXTJS_INTERNALS_TREE})})}};return window.addEventListener("popstate",n),()=>{window.history.pushState=e,window.history.replaceState=t,window.removeEventListener("popstate",n)}},[E]);let{cache:H,tree:B,nextUrl:$,focusAndScrollRef:W}=(0,s.useUnwrapState)(d),X=(0,a.useMemo)(()=>(0,g.findHeadInCache)(H,B[1]),[H,B]),K=(0,a.useMemo)(()=>(0,v.getSelectedParams)(B),[B]),G=(0,a.useMemo)(()=>({parentTree:B,parentCacheNode:H,parentSegmentPath:null,url:x}),[B,H,x]),z=(0,a.useMemo)(()=>({changeByServerResponse:k,tree:B,focusAndScrollRef:W,nextUrl:$}),[k,B,W,$]);if(null!==X){let[e,r]=X;t=(0,o.jsx)(A,{headCacheNode:e},r)}else t=null;let q=(0,o.jsxs)(y.RedirectBoundary,{children:[t,H.rsc,(0,o.jsx)(h.AppRouterAnnouncer,{tree:B})]});return q=(0,o.jsx)(f.ErrorBoundary,{errorComponent:i[0],errorStyles:i[1],children:q}),(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(M,{appRouterState:(0,s.useUnwrapState)(d)}),(0,o.jsx)(I,{}),(0,o.jsx)(c.PathParamsContext.Provider,{value:K,children:(0,o.jsx)(c.PathnameContext.Provider,{value:N,children:(0,o.jsx)(c.SearchParamsContext.Provider,{value:D,children:(0,o.jsx)(u.GlobalLayoutRouterContext.Provider,{value:z,children:(0,o.jsx)(u.AppRouterContext.Provider,{value:L,children:(0,o.jsx)(u.LayoutRouterContext.Provider,{value:G,children:q})})})})})})]})}function N(e){let{actionQueue:t,globalErrorComponentAndStyles:[r,n],assetPrefix:a}=e;return(0,E.useNavFailureHandler)(),(0,o.jsx)(f.ErrorBoundary,{errorComponent:f.default,children:(0,o.jsx)(D,{actionQueue:t,assetPrefix:a,globalError:[r,n]})})}let k=new Set,U=new Set;function I(){let[,e]=a.default.useState(0),t=k.size;return(0,a.useEffect)(()=>{let r=()=>e(e=>e+1);return U.add(r),t!==k.size&&r(),()=>{U.delete(r)}},[t,e]),[...k].map((e,t)=>(0,o.jsx)("link",{rel:"stylesheet",href:""+e,precedence:"next"},t))}globalThis._N_E_STYLE_LOAD=function(e){let t=k.size;return k.add(e),k.size!==t&&U.forEach(e=>e()),Promise.resolve()},("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3436:(e,t)=>{"use strict";function r(e,t){return void 0===t&&(t=!0),e.pathname+e.search+(t?e.hash:"")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createHrefFromUrl",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3523:(e,t,r)=>{"use strict";r.r(t),r.d(t,{_:()=>o});var n=0;function o(e){return"__private_"+n+++"_"+e}},3633:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldRenderRootLevelErrorOverlay",{enumerable:!0,get:function(){return r}});let r=()=>{var e;return!!(null==(e=window.__next_root_layout_missing_tags)?void 0:e.length)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3649:(e,t)=>{"use strict";function r(e){return"object"==typeof e&&null!==e&&"digest"in e&&e.digest===n}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{isHangingPromiseRejectionError:function(){return r},makeHangingPromise:function(){return a}});let n="HANGING_PROMISE_REJECTION";class o extends Error{constructor(e){super(`During prerendering, ${e} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${e} to a different context by using \`setTimeout\`, \`after\`, or similar functions you may observe this error and you should handle it in that context.`),this.expression=e,this.digest=n}}function a(e,t){let r=new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new o(t))},{once:!0})});return r.catch(u),r}function u(){}},3664:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{bindSnapshot:function(){return u},createAsyncLocalStorage:function(){return a},createSnapshot:function(){return l}});let r=Object.defineProperty(Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"),"__NEXT_ERROR_CODE",{value:"E504",enumerable:!1,configurable:!0});class n{disable(){throw r}getStore(){}run(){throw r}exit(){throw r}enterWith(){throw r}static bind(e){return e}}let o="undefined"!=typeof globalThis&&globalThis.AsyncLocalStorage;function a(){return o?new o:new n}function u(e){return o?o.bind(e):n.bind(e)}function l(){return o?o.snapshot():function(e,...t){return e(...t)}}},3719:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{BailoutToCSRError:function(){return n},isBailoutToCSRError:function(){return o}});let r="BAILOUT_TO_CLIENT_SIDE_RENDERING";class n extends Error{constructor(e){super("Bail out to client-side rendering: "+e),this.reason=e,this.digest=r}}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&e.digest===r}},3866:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return l}});let n=r(9955),o=r(5155),a=n._(r(2115)),u=r(1394);function l(){let e=(0,a.useContext)(u.TemplateContext);return(0,o.jsx)(o.Fragment,{children:e})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4046:(e,t)=>{"use strict";function r(e){let t=e.indexOf("#"),r=e.indexOf("?"),n=r>-1&&(t<0||r-1?{pathname:e.substring(0,n?r:t),query:n?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return r}})},4054:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{bindSnapshot:function(){return u},createAsyncLocalStorage:function(){return a},createSnapshot:function(){return l}});let r=Object.defineProperty(Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"),"__NEXT_ERROR_CODE",{value:"E504",enumerable:!1,configurable:!0});class n{disable(){throw r}getStore(){}run(){throw r}exit(){throw r}enterWith(){throw r}static bind(e){return e}}let o="undefined"!=typeof globalThis&&globalThis.AsyncLocalStorage;function a(){return o?new o:new n}function u(e){return o?o.bind(e):n.bind(e)}function l(){return o?o.snapshot():function(e,...t){return e(...t)}}},4091:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{createFetch:function(){return y},createFromNextReadableStream:function(){return g},fetchServerResponse:function(){return h},urlToUrlWithoutFlightMarker:function(){return f}});let n=r(2836),o=r(9603),a=r(3355),u=r(4445),l=r(1648),i=r(8127),c=r(6802),{createFromReadableStream:s}=r(4979);function f(e){let t=new URL(e,location.origin);if(t.searchParams.delete(n.NEXT_RSC_UNION_QUERY),t.pathname.endsWith(".txt")){let{pathname:e}=t,r=e.endsWith("/index.txt")?10:4;t.pathname=e.slice(0,-r)}return t}function d(e){return{flightData:f(e).toString(),canonicalUrl:void 0,couldBeIntercepted:!1,prerendered:!1,postponed:!1,staleTime:-1}}let p=new AbortController;async function h(e,t){let{flightRouterState:r,nextUrl:o,prefetchKind:a}=t,c={[n.RSC_HEADER]:"1",[n.NEXT_ROUTER_STATE_TREE_HEADER]:encodeURIComponent(JSON.stringify(r))};a===u.PrefetchKind.AUTO&&(c[n.NEXT_ROUTER_PREFETCH_HEADER]="1"),o&&(c[n.NEXT_URL]=o);try{var s;let t=a?a===u.PrefetchKind.TEMPORARY?"high":"low":"auto",r=await y(e,c,t,p.signal),o=f(r.url),h=r.redirected?o:void 0,_=r.headers.get("content-type")||"",b=!!(null==(s=r.headers.get("vary"))?void 0:s.includes(n.NEXT_URL)),m=!!r.headers.get(n.NEXT_DID_POSTPONE_HEADER),v=r.headers.get(n.NEXT_ROUTER_STALE_TIME_HEADER),E=null!==v?parseInt(v,10):-1,R=_.startsWith(n.RSC_CONTENT_TYPE_HEADER);if(R||(R=_.startsWith("text/plain")),!R||!r.ok||!r.body)return e.hash&&(o.hash=e.hash),d(o.toString());let O=m?function(e){let t=e.getReader();return new ReadableStream({async pull(e){for(;;){let{done:r,value:n}=await t.read();if(!r){e.enqueue(n);continue}return}}})}(r.body):r.body,P=await g(O);if((0,i.getAppBuildId)()!==P.b)return d(r.url);return{flightData:(0,l.normalizeFlightData)(P.f),canonicalUrl:h,couldBeIntercepted:b,prerendered:P.S,postponed:m,staleTime:E}}catch(t){return p.signal.aborted||console.error("Failed to fetch RSC payload for "+e+". Falling back to browser navigation.",t),{flightData:e.toString(),canonicalUrl:void 0,couldBeIntercepted:!1,prerendered:!1,postponed:!1,staleTime:-1}}}function y(e,t,r,n){let o=new URL(e);return o.pathname.endsWith("/")?o.pathname+="index.txt":o.pathname+=".txt",(0,c.setCacheBustingSearchParam)(o,t),fetch(o,{credentials:"same-origin",headers:t,priority:r||void 0,signal:n})}function g(e){return s(e,{callServer:o.callServer,findSourceMapURL:a.findSourceMapURL})}"undefined"!=typeof window&&(window.addEventListener("pagehide",()=>{p.abort()}),window.addEventListener("pageshow",()=>{p=new AbortController})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4117:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"afterTaskAsyncStorageInstance",{enumerable:!0,get:function(){return n}});let n=(0,r(3664).createAsyncLocalStorage)()},4124:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRenderSearchParamsFromClient",{enumerable:!0,get:function(){return o}}),r(1042);let n=r(1142);function o(e){return function(e){let t=a.get(e);if(t)return t;let r=Promise.resolve(e);return a.set(e,r),Object.keys(e).forEach(t=>{n.wellKnownProperties.has(t)||(r[t]=e[t])}),r}(e)}let a=new WeakMap},4125:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ServerInsertedHTMLContext:function(){return o},useServerInsertedHTML:function(){return a}});let n=r(9955)._(r(2115)),o=n.default.createContext(null);function a(e){let t=(0,n.useContext)(o);t&&t(e)}},4156:(e,t)=>{"use strict";function r(e){let t={};for(let[r,n]of e.entries()){let e=t[r];void 0===e?t[r]=n:Array.isArray(e)?e.push(n):t[r]=[e,n]}return t}function n(e){return"string"==typeof e?e:("number"!=typeof e||isNaN(e))&&"boolean"!=typeof e?"":String(e)}function o(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(Array.isArray(o))for(let e of o)t.append(r,n(e));else t.set(r,n(o));return t}function a(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n{"use strict";function r(e){return Array.isArray(e)?e[1]:e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentValue",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4283:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{HTML_LIMITED_BOT_UA_RE:function(){return n.HTML_LIMITED_BOT_UA_RE},HTML_LIMITED_BOT_UA_RE_STRING:function(){return a},getBotType:function(){return i},isBot:function(){return l}});let n=r(243),o=/Googlebot|Google-PageRenderer|AdsBot-Google|googleweblight|Storebot-Google/i,a=n.HTML_LIMITED_BOT_UA_RE.source;function u(e){return n.HTML_LIMITED_BOT_UA_RE.test(e)}function l(e){return o.test(e)||u(e)}function i(e){return o.test(e)?"dom":u(e)?"html":void 0}},4300:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{formatConsoleArgs:function(){return a},parseConsoleArgs:function(){return u}});let n=r(306)._(r(9762));function o(e,t){switch(typeof e){case"object":if(null===e)return"null";if(Array.isArray(e)){let r="[";if(t<1)for(let n=0;n0?"...":"";return r+"]"}{if(e instanceof Error)return e+"";let r=Object.keys(e),n="{";if(t<1)for(let a=0;a0?"...":"";return n+"}"}case"string":return JSON.stringify(e);default:return String(e)}}function a(e){let t,r;"string"==typeof e[0]?(t=e[0],r=1):(t="",r=0);let n="",a=!1;for(let u=0;u=e.length){n+=l;continue}let i=t[++u];switch(i){case"c":n=a?""+n+"]":"["+n,a=!a,r++;break;case"O":case"o":n+=o(e[r++],0);break;case"d":case"i":n+=parseInt(e[r++],10);break;case"f":n+=parseFloat(e[r++]);break;case"s":n+=String(e[r++]);break;default:n+="%"+i}}for(;r0?" ":"")+o(e[r],0);return n}function u(e){if(e.length>3&&"string"==typeof e[0]&&e[0].startsWith("%c%s%c ")&&"string"==typeof e[1]&&"string"==typeof e[2]&&"string"==typeof e[3]){let t=e[2],r=e[4];return{environmentName:t.trim(),error:(0,n.default)(r)?r:null}}return{environmentName:null,error:null}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4336:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"notFound",{enumerable:!0,get:function(){return o}});let n=""+r(2469).HTTP_ERROR_FALLBACK_ERROR_CODE+";404";function o(){let e=Object.defineProperty(Error(n),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});throw e.digest=n,e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4383:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{createParamsFromClient:function(){return c},createPrerenderParamsForClientSegment:function(){return p},createServerParamsForMetadata:function(){return s},createServerParamsForRoute:function(){return f},createServerParamsForServerSegment:function(){return d}}),r(1042);let n=r(6378),o=r(5938),a=r(4940),u=r(1142),l=r(3649),i=r(6431);function c(e,t){var r;let n=o.workUnitAsyncStorage.getStore();if(n)switch(n.type){case"prerender":case"prerender-ppr":case"prerender-legacy":return h(e,t,n)}return r=0,g(e)}r(2301);let s=d;function f(e,t){var r;let n=o.workUnitAsyncStorage.getStore();if(n)switch(n.type){case"prerender":case"prerender-ppr":case"prerender-legacy":return h(e,t,n)}return r=0,g(e)}function d(e,t){var r;let n=o.workUnitAsyncStorage.getStore();if(n)switch(n.type){case"prerender":case"prerender-ppr":case"prerender-legacy":return h(e,t,n)}return r=0,g(e)}function p(e,t){let r=o.workUnitAsyncStorage.getStore();if(r&&"prerender"===r.type){let n=t.fallbackRouteParams;if(n){for(let t in e)if(n.has(t))return(0,l.makeHangingPromise)(r.renderSignal,"`params`")}}return Promise.resolve(e)}function h(e,t,r){let o=t.fallbackRouteParams;if(o){let a=!1;for(let t in e)if(o.has(t)){a=!0;break}if(a)return"prerender"===r.type?function(e,t,r){let o=y.get(e);if(o)return o;let a=(0,l.makeHangingPromise)(r.renderSignal,"`params`");return y.set(e,a),Object.keys(e).forEach(e=>{u.wellKnownProperties.has(e)||Object.defineProperty(a,e,{get(){let o=(0,u.describeStringPropertyAccess)("params",e),a=m(t,o);(0,n.abortAndThrowOnSynchronousRequestDataAccess)(t,o,a,r)},set(t){Object.defineProperty(a,e,{value:t,writable:!0,enumerable:!0})},enumerable:!0,configurable:!0})}),a}(e,t.route,r):function(e,t,r,o){let a=y.get(e);if(a)return a;let l={...e},i=Promise.resolve(l);return y.set(e,i),Object.keys(e).forEach(a=>{u.wellKnownProperties.has(a)||(t.has(a)?(Object.defineProperty(l,a,{get(){let e=(0,u.describeStringPropertyAccess)("params",a);"prerender-ppr"===o.type?(0,n.postponeWithTracking)(r.route,e,o.dynamicTracking):(0,n.throwToInterruptStaticGeneration)(e,r,o)},enumerable:!0}),Object.defineProperty(i,a,{get(){let e=(0,u.describeStringPropertyAccess)("params",a);"prerender-ppr"===o.type?(0,n.postponeWithTracking)(r.route,e,o.dynamicTracking):(0,n.throwToInterruptStaticGeneration)(e,r,o)},set(e){Object.defineProperty(i,a,{value:e,writable:!0,enumerable:!0})},enumerable:!0,configurable:!0})):i[a]=e[a])}),i}(e,o,t,r)}return g(e)}let y=new WeakMap;function g(e){let t=y.get(e);if(t)return t;let r=Promise.resolve(e);return y.set(e,r),Object.keys(e).forEach(t=>{u.wellKnownProperties.has(t)||(r[t]=e[t])}),r}let _=(0,i.createDedupedByCallsiteServerErrorLoggerDev)(m),b=(0,i.createDedupedByCallsiteServerErrorLoggerDev)(function(e,t,r){let n=e?`Route "${e}" `:"This route ";return Object.defineProperty(Error(`${n}used ${t}. \`params\` should be awaited before using its properties. The following properties were not available through enumeration because they conflict with builtin property names: ${function(e){switch(e.length){case 0:throw Object.defineProperty(new a.InvariantError("Expected describeListOfPropertyNames to be called with a non-empty list of strings."),"__NEXT_ERROR_CODE",{value:"E531",enumerable:!1,configurable:!0});case 1:return`\`${e[0]}\``;case 2:return`\`${e[0]}\` and \`${e[1]}\``;default:{let t="";for(let r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ACTION_HMR_REFRESH:function(){return l},ACTION_NAVIGATE:function(){return n},ACTION_PREFETCH:function(){return u},ACTION_REFRESH:function(){return r},ACTION_RESTORE:function(){return o},ACTION_SERVER_ACTION:function(){return i},ACTION_SERVER_PATCH:function(){return a},PrefetchCacheEntryStatus:function(){return s},PrefetchKind:function(){return c}});let r="refresh",n="navigate",o="restore",a="server-patch",u="prefetch",l="hmr-refresh",i="server-action";var c=function(e){return e.AUTO="auto",e.FULL="full",e.TEMPORARY="temporary",e}({}),s=function(e){return e.fresh="fresh",e.reusable="reusable",e.expired="expired",e.stale="stale",e}({});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4547:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ClientSegmentRoot",{enumerable:!0,get:function(){return a}});let n=r(5155),o=r(4940);function a(e){let{Component:t,slots:a,params:u,promise:l}=e;if("undefined"==typeof window){let e;let{workAsyncStorage:l}=r(5861),i=l.getStore();if(!i)throw Object.defineProperty(new o.InvariantError("Expected workStore to exist when handling params in a client segment such as a Layout or Template."),"__NEXT_ERROR_CODE",{value:"E600",enumerable:!1,configurable:!0});let{createParamsFromClient:c}=r(4383);return e=c(u,i),(0,n.jsx)(t,{...a,params:e})}{let{createRenderParamsFromClient:e}=r(5737),o=e(u);return(0,n.jsx)(t,{...a,params:o})}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4557:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ReadonlyURLSearchParams:function(){return s},RedirectType:function(){return o.RedirectType},forbidden:function(){return u.forbidden},notFound:function(){return a.notFound},permanentRedirect:function(){return n.permanentRedirect},redirect:function(){return n.redirect},unauthorized:function(){return l.unauthorized},unstable_rethrow:function(){return i.unstable_rethrow}});let n=r(9100),o=r(7563),a=r(4336),u=r(8901),l=r(882),i=r(7554);class c extends Error{constructor(){super("Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams")}}class s extends URLSearchParams{append(){throw new c}delete(){throw new c}set(){throw new c}sort(){throw new c}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4565:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ServerInsertedMetadataContext",{enumerable:!0,get:function(){return n}});let n=(0,r(2115).createContext)(null)},4682:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{canSegmentBeOverridden:function(){return a},matchSegment:function(){return o}});let n=r(6654),o=(e,t)=>"string"==typeof e?"string"==typeof t&&e===t:"string"!=typeof t&&e[0]===t[0]&&e[1]===t[1],a=(e,t)=>{var r;return!Array.isArray(e)&&!!Array.isArray(t)&&(null==(r=(0,n.getSegmentParam)(e))?void 0:r.param)===t[0]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4819:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isPostpone",{enumerable:!0,get:function(){return n}});let r=Symbol.for("react.postpone");function n(e){return"object"==typeof e&&null!==e&&e.$$typeof===r}},4835:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ErrorBoundary:function(){return h},ErrorBoundaryHandler:function(){return f},GlobalError:function(){return d},default:function(){return p}});let n=r(306),o=r(5155),a=n._(r(2115)),u=r(2380),l=r(179);r(9935);let i=r(5861),c={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function s(e){let{error:t}=e,r=i.workAsyncStorage.getStore();if((null==r?void 0:r.isRevalidate)||(null==r?void 0:r.isStaticGeneration))throw console.error(t),t;return null}class f extends a.default.Component{static getDerivedStateFromError(e){if((0,l.isNextRouterError)(e))throw e;return{error:e}}static getDerivedStateFromProps(e,t){let{error:r}=t;return e.pathname!==t.previousPathname&&t.error?{error:null,previousPathname:e.pathname}:{error:t.error,previousPathname:e.pathname}}render(){return this.state.error?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(s,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,(0,o.jsx)(this.props.errorComponent,{error:this.state.error,reset:this.reset})]}):this.props.children}constructor(e){super(e),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}}function d(e){let{error:t}=e,r=null==t?void 0:t.digest;return(0,o.jsxs)("html",{id:"__next_error__",children:[(0,o.jsx)("head",{}),(0,o.jsxs)("body",{children:[(0,o.jsx)(s,{error:t}),(0,o.jsx)("div",{style:c.error,children:(0,o.jsxs)("div",{children:[(0,o.jsxs)("h2",{style:c.text,children:["Application error: a ",r?"server":"client","-side exception has occurred while loading ",window.location.hostname," (see the"," ",r?"server logs":"browser console"," for more information)."]}),r?(0,o.jsx)("p",{style:c.text,children:"Digest: "+r}):null]})})]})]})}let p=d;function h(e){let{errorComponent:t,errorStyles:r,errorScripts:n,children:a}=e,l=(0,u.useUntrackedPathname)();return t?(0,o.jsx)(f,{pathname:l,errorComponent:t,errorStyles:r,errorScripts:n,children:a}):(0,o.jsx)(o.Fragment,{children:a})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4931:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"workUnitAsyncStorageInstance",{enumerable:!0,get:function(){return n}});let n=(0,r(4054).createAsyncLocalStorage)()},4940:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"InvariantError",{enumerable:!0,get:function(){return r}});class r extends Error{constructor(e,t){super("Invariant: "+(e.endsWith(".")?e:e+".")+" This is a bug in Next.js.",t),this.name="InvariantError"}}},4979:(e,t,r)=>{"use strict";e.exports=r(7197)},5025:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"refreshReducer",{enumerable:!0,get:function(){return h}});let n=r(4091),o=r(3436),a=r(1053),u=r(6449),l=r(2603),i=r(7344),c=r(223),s=r(3423),f=r(9786),d=r(941),p=r(1387);function h(e,t){let{origin:r}=t,h={},y=e.canonicalUrl,g=e.tree;h.preserveCustomHistoryState=!1;let _=(0,s.createEmptyCacheNode)(),b=(0,d.hasInterceptionRouteInCurrentTree)(e.tree);return _.lazyData=(0,n.fetchServerResponse)(new URL(y,r),{flightRouterState:[g[0],g[1],g[2],"refetch"],nextUrl:b?e.nextUrl:null}),_.lazyData.then(async r=>{let{flightData:n,canonicalUrl:s}=r;if("string"==typeof n)return(0,l.handleExternalUrl)(e,h,n,e.pushRef.pendingPush);for(let r of(_.lazyData=null,n)){let{tree:n,seedData:i,head:d,isRootRender:m}=r;if(!m)return console.log("REFRESH FAILED"),e;let v=(0,a.applyRouterStatePatchToTree)([""],g,n,e.canonicalUrl);if(null===v)return(0,f.handleSegmentMismatch)(e,t,n);if((0,u.isNavigatingToNewRootLayout)(g,v))return(0,l.handleExternalUrl)(e,h,y,e.pushRef.pendingPush);let E=s?(0,o.createHrefFromUrl)(s):void 0;if(s&&(h.canonicalUrl=E),null!==i){let e=i[1],t=i[3];_.rsc=e,_.prefetchRsc=null,_.loading=t,(0,c.fillLazyItemsTillLeafWithHead)(_,void 0,n,i,d,void 0),h.prefetchCache=new Map}await (0,p.refreshInactiveParallelSegments)({state:e,updatedTree:v,updatedCache:_,includeNextUrl:b,canonicalUrl:h.canonicalUrl||e.canonicalUrl}),h.cache=_,h.patchedTree=v,g=v}return(0,i.handleMutable)(e,h)},()=>e)}r(3099),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5155:(e,t,r)=>{"use strict";e.exports=r(6897)},5194:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{originConsoleError:function(){return o},patchConsoleError:function(){return a}}),r(306),r(9762);let n=r(179);r(5597),r(4300);let o=globalThis.console.error;function a(){"undefined"!=typeof window&&(window.console.error=function(){let e;for(var t=arguments.length,r=Array(t),a=0;a{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"useSyncDevRenderIndicator",{enumerable:!0,get:function(){return n}});let r=e=>e(),n=()=>r;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5244:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return S}});let n=r(306),o=r(9955),a=r(5155),u=o._(r(2115)),l=n._(r(7650)),i=r(1394),c=r(4091),s=r(9321),f=r(4835),d=r(4682),p=r(8344),h=r(6501),y=r(2328),g=r(5404),_=r(941),b=l.default.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,m=["bottom","height","left","right","top","width","x","y"];function v(e,t){let r=e.getBoundingClientRect();return r.top>=0&&r.top<=t}class E extends u.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:t}=this.props;if(e.apply){if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>t.every((t,r)=>(0,d.matchSegment)(t,e[r]))))return;let r=null,n=e.hashFragment;if(n&&(r=function(e){var t;return"top"===e?document.body:null!=(t=document.getElementById(e))?t:document.getElementsByName(e)[0]}(n)),!r)r="undefined"==typeof window?null:(0,b.findDOMNode)(this);if(!(r instanceof Element))return;for(;!(r instanceof HTMLElement)||function(e){if(["sticky","fixed"].includes(getComputedStyle(e).position))return!0;let t=e.getBoundingClientRect();return m.every(e=>0===t[e])}(r);){if(null===r.nextElementSibling)return;r=r.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,p.handleSmoothScroll)(()=>{if(n){r.scrollIntoView();return}let e=document.documentElement,t=e.clientHeight;!v(r,t)&&(e.scrollTop=0,v(r,t)||r.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:e.onlyHashChange}),e.onlyHashChange=!1,r.focus()}}}}function R(e){let{segmentPath:t,children:r}=e,n=(0,u.useContext)(i.GlobalLayoutRouterContext);if(!n)throw Object.defineProperty(Error("invariant global layout router not mounted"),"__NEXT_ERROR_CODE",{value:"E473",enumerable:!1,configurable:!0});return(0,a.jsx)(E,{segmentPath:t,focusAndScrollRef:n.focusAndScrollRef,children:r})}function O(e){let{tree:t,segmentPath:r,cacheNode:n,url:o}=e,l=(0,u.useContext)(i.GlobalLayoutRouterContext);if(!l)throw Object.defineProperty(Error("invariant global layout router not mounted"),"__NEXT_ERROR_CODE",{value:"E473",enumerable:!1,configurable:!0});let{changeByServerResponse:f,tree:p}=l,h=null!==n.prefetchRsc?n.prefetchRsc:n.rsc,y=(0,u.useDeferredValue)(n.rsc,h),g="object"==typeof y&&null!==y&&"function"==typeof y.then?(0,u.use)(y):y;if(!g){let e=n.lazyData;if(null===e){let t=function e(t,r){if(t){let[n,o]=t,a=2===t.length;if((0,d.matchSegment)(r[0],n)&&r[1].hasOwnProperty(o)){if(a){let t=e(void 0,r[1][o]);return[r[0],{...r[1],[o]:[t[0],t[1],t[2],"refetch"]}]}return[r[0],{...r[1],[o]:e(t.slice(2),r[1][o])}]}}return r}(["",...r],p),a=(0,_.hasInterceptionRouteInCurrentTree)(p);n.lazyData=e=(0,c.fetchServerResponse)(new URL(o,location.origin),{flightRouterState:t,nextUrl:a?l.nextUrl:null}).then(e=>((0,u.startTransition)(()=>{f({previousTree:p,serverResponse:e})}),e)),(0,u.use)(e)}(0,u.use)(s.unresolvedThenable)}return(0,a.jsx)(i.LayoutRouterContext.Provider,{value:{parentTree:t,parentCacheNode:n,parentSegmentPath:r,url:o},children:g})}function P(e){let t,{loading:r,children:n}=e;if(t="object"==typeof r&&null!==r&&"function"==typeof r.then?(0,u.use)(r):r){let e=t[0],r=t[1],o=t[2];return(0,a.jsx)(u.Suspense,{fallback:(0,a.jsxs)(a.Fragment,{children:[r,o,e]}),children:n})}return(0,a.jsx)(a.Fragment,{children:n})}function S(e){let{parallelRouterKey:t,error:r,errorStyles:n,errorScripts:o,templateStyles:l,templateScripts:c,template:s,notFound:d,forbidden:p,unauthorized:_}=e,b=(0,u.useContext)(i.LayoutRouterContext);if(!b)throw Object.defineProperty(Error("invariant expected layout router to be mounted"),"__NEXT_ERROR_CODE",{value:"E56",enumerable:!1,configurable:!0});let{parentTree:m,parentCacheNode:v,parentSegmentPath:E,url:S}=b,j=v.parallelRoutes,T=j.get(t);T||(T=new Map,j.set(t,T));let w=m[0],M=m[1][t],x=M[0],C=null===E?[t]:E.concat([w,t]),A=(0,g.createRouterCacheKey)(x),D=(0,g.createRouterCacheKey)(x,!0),N=T.get(A);if(void 0===N){let e={lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:null};N=e,T.set(A,e)}let k=v.loading;return(0,a.jsxs)(i.TemplateContext.Provider,{value:(0,a.jsx)(R,{segmentPath:C,children:(0,a.jsx)(f.ErrorBoundary,{errorComponent:r,errorStyles:n,errorScripts:o,children:(0,a.jsx)(P,{loading:k,children:(0,a.jsx)(y.HTTPAccessFallbackBoundary,{notFound:d,forbidden:p,unauthorized:_,children:(0,a.jsx)(h.RedirectBoundary,{children:(0,a.jsx)(O,{url:S,tree:M,cacheNode:N,segmentPath:C})})})})})}),children:[l,c,s]},D)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5245:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NavigationResultTag:function(){return i},navigate:function(){return s}});let n=r(4091),o=r(3223),a=r(3436),u=r(3099),l=r(2633);var i=function(e){return e[e.MPA=0]="MPA",e[e.Success=1]="Success",e[e.NoOp=2]="NoOp",e[e.Async=3]="Async",e}({});let c={tag:2,data:null};function s(e,t,r,a,i){let s=Date.now(),p=(0,l.createCacheKey)(e.href,a),h=(0,u.readRouteCacheEntry)(s,p);if(null!==h&&h.status===u.EntryStatus.Fulfilled){let l=function e(t,r){let n={},o={},a=r.slots;if(null!==a)for(let r in a){let u=e(t,a[r]);n[r]=u.flightRouterState,o[r]=u.seedData}let l=null,i=null,c=!0,s=(0,u.readSegmentCacheEntry)(t,r.key);if(null!==s)switch(s.status){case u.EntryStatus.Fulfilled:l=s.rsc,i=s.loading,c=s.isPartial;break;case u.EntryStatus.Pending:{let e=(0,u.waitForSegmentCacheEntry)(s);l=e.then(e=>null!==e?e.rsc:null),i=e.then(e=>null!==e?e.loading:null),c=!0}case u.EntryStatus.Empty:case u.EntryStatus.Rejected:}return{flightRouterState:[r.segment,n,null,null,r.isRootLayout],seedData:[r.segment,l,o,i,c]}}(s,h.tree),d=l.flightRouterState,p=l.seedData,y=h.head;return function(e,t,r,a,u,l,i,s,d,p){let h=[],y=(0,o.startPPRNavigation)(r,a,u,l,i,s,h);if(null!==y){let a=y.dynamicRequestTree;if(null!==a){let r=(0,n.fetchServerResponse)(e,{flightRouterState:a,nextUrl:t});(0,o.listenForDynamicRequest)(y,r)}return f(y,r,d,h,p)}return c}(e,a,t,r,d,p,y,h.isHeadPartial,h.canonicalUrl,i)}return{tag:3,data:d(e,a,t,r,i)}}function f(e,t,r,n,o){let a=e.route;if(null===a)return{tag:0,data:r};let u=e.node;return{tag:1,data:{flightRouterState:a,cacheNode:null!==u?u:t,canonicalUrl:r,scrollableSegments:n,shouldScroll:o}}}async function d(e,t,r,u,l){let i=(0,n.fetchServerResponse)(e,{flightRouterState:u,nextUrl:t}),{flightData:s,canonicalUrl:d}=await i;if("string"==typeof s)return{tag:0,data:s};let p=function(e,t){let r=e;for(let{segmentPath:n,tree:o}of t){let t=r!==e;r=function e(t,r,n,o,a){if(a===n.length)return r;let u=n[a],l=t[1],i={};for(let t in l)if(t===u){let u=l[t];i[t]=e(u,r,n,o,a+2)}else i[t]=l[t];if(o)return t[1]=i,t;let c=[t[0],i];return 2 in t&&(c[2]=t[2]),3 in t&&(c[3]=t[3]),4 in t&&(c[4]=t[4]),c}(r,o,n,t,0)}return r}(u,s),h=(0,a.createHrefFromUrl)(d||e),y=[],g=(0,o.startPPRNavigation)(r,u,p,null,null,!0,y);return null!==g?(null!==g.dynamicRequestTree&&(0,o.listenForDynamicRequest)(g,i),f(g,r,h,y,l)):c}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5353:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"useMergedRef",{enumerable:!0,get:function(){return o}});let n=r(2115);function o(e,t){let r=(0,n.useRef)(null),o=(0,n.useRef)(null);return(0,n.useCallback)(n=>{if(null===n){let e=r.current;e&&(r.current=null,e());let t=o.current;t&&(o.current=null,t())}else e&&(r.current=a(e,n)),t&&(o.current=a(t,n))},[e,t])}function a(e,t){if("function"!=typeof e)return e.current=t,()=>{e.current=null};{let r=e(t);return"function"==typeof r?r:()=>e(null)}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5384:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXTJS_HYDRATION_ERROR_LINK:function(){return i},REACT_HYDRATION_ERROR_LINK:function(){return l},getDefaultHydrationErrorMessage:function(){return c},getHydrationErrorStackInfo:function(){return h},isHydrationError:function(){return s},isReactHydrationErrorMessage:function(){return f},testReactHydrationWarning:function(){return p}});let n=r(306)._(r(9762)),o=/hydration failed|while hydrating|content does not match|did not match|HTML didn't match/i,a="Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:",u=[a,"A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:"],l="https://react.dev/link/hydration-mismatch",i="https://nextjs.org/docs/messages/react-hydration-error",c=()=>a;function s(e){return(0,n.default)(e)&&o.test(e.message)}function f(e){return u.some(t=>e.startsWith(t))}let d=[/^In HTML, (.+?) cannot be a child of <(.+?)>\.(.*)\nThis will cause a hydration error\.(.*)/,/^In HTML, (.+?) cannot be a descendant of <(.+?)>\.\nThis will cause a hydration error\.(.*)/,/^In HTML, text nodes cannot be a child of <(.+?)>\.\nThis will cause a hydration error\./,/^In HTML, whitespace text nodes cannot be a child of <(.+?)>\. Make sure you don't have any extra whitespace between tags on each line of your source code\.\nThis will cause a hydration error\./,/^Expected server HTML to contain a matching <(.+?)> in <(.+?)>\.(.*)/,/^Did not expect server HTML to contain a <(.+?)> in <(.+?)>\.(.*)/,/^Expected server HTML to contain a matching text node for "(.+?)" in <(.+?)>\.(.*)/,/^Did not expect server HTML to contain the text node "(.+?)" in <(.+?)>\.(.*)/,/^Text content did not match\. Server: "(.+?)" Client: "(.+?)"(.*)/];function p(e){return"string"==typeof e&&!!e&&(e.startsWith("Warning: ")&&(e=e.slice(9)),d.some(t=>t.test(e)))}function h(e){let t=p(e=(e=e.replace(/^Error: /,"")).replace("Warning: ",""));if(!f(e)&&!t)return{message:null,stack:e,diff:""};if(t){let[t,r]=e.split("\n\n");return{message:t.trim(),stack:"",diff:(r||"").trim()}}let r=e.indexOf("\n"),[n,o]=(e=e.slice(r+1).trim()).split(""+l),a=n.trim();if(!o||!(o.length>1))return{message:a,stack:o};{let e=[],t=[];return o.split("\n").forEach(r=>{""!==r.trim()&&(r.trim().startsWith("at ")?e.push(r):t.push(r))}),{message:a,diff:t.join("\n"),stack:e.join("\n")}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5404:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRouterCacheKey",{enumerable:!0,get:function(){return o}});let n=r(6090);function o(e,t){return(void 0===t&&(t=!1),Array.isArray(e))?e[0]+"|"+e[1]+"|"+e[2]:t&&e.startsWith(n.PAGE_SEGMENT_KEY)?n.PAGE_SEGMENT_KEY:e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5411:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheBelowFlightSegmentPath",{enumerable:!0,get:function(){return function e(t,r,a){let u=a.length<=2,[l,i]=a,c=(0,n.createRouterCacheKey)(i),s=r.parallelRoutes.get(l);if(!s)return;let f=t.parallelRoutes.get(l);if(f&&f!==s||(f=new Map(s),t.parallelRoutes.set(l,f)),u){f.delete(c);return}let d=s.get(c),p=f.get(c);p&&d&&(p===d&&(p={lazyData:p.lazyData,rsc:p.rsc,prefetchRsc:p.prefetchRsc,head:p.head,prefetchHead:p.prefetchHead,parallelRoutes:new Map(p.parallelRoutes)},f.set(c,p)),e(p,d,(0,o.getNextFlightSegmentPath)(a)))}}});let n=r(5404),o=r(1648);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5597:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleClientError:function(){return b},handleGlobalErrors:function(){return R},useErrorHandler:function(){return m}});let n=r(306),o=r(2115),a=r(33),u=r(179),l=r(7088),i=r(4300),c=n._(r(9762)),s=r(410),f=r(5881),d=r(8227),p=globalThis.queueMicrotask||(e=>Promise.resolve().then(e)),h=[],y=[],g=[],_=[];function b(e,t,r){let n;if(void 0===r&&(r=!1),e&&(0,c.default)(e))n=r?(0,s.createUnhandledError)(e):e;else{let e=(0,i.formatConsoleArgs)(t),{environmentName:r}=(0,i.parseConsoleArgs)(t);n=(0,s.createUnhandledError)(e,r)}for(let e of(n=(0,d.getReactStitchedError)(n),(0,l.storeHydrationErrorStateFromConsoleArgs)(...t),(0,a.attachHydrationErrorState)(n),(0,f.enqueueConsecutiveDedupedError)(h,n),y))p(()=>{e(n)})}function m(e,t){(0,o.useEffect)(()=>(h.forEach(e),g.forEach(t),y.push(e),_.push(t),()=>{y.splice(y.indexOf(e),1),_.splice(_.indexOf(t),1),h.splice(0,h.length),g.splice(0,g.length)}),[e,t])}function v(e){if((0,u.isNextRouterError)(e.error))return e.preventDefault(),!1;e.error&&b(e.error,[])}function E(e){let t=null==e?void 0:e.reason;if((0,u.isNextRouterError)(t)){e.preventDefault();return}let r=t;for(let e of(r&&!(0,c.default)(r)&&(r=(0,s.createUnhandledError)(r+"")),g.push(r),_))e(r)}function R(){if("undefined"!=typeof window){try{Error.stackTraceLimit=50}catch(e){}window.addEventListener("error",v),window.addEventListener("unhandledrejection",E)}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5737:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRenderParamsFromClient",{enumerable:!0,get:function(){return o}}),r(1042),r(4940);let n=r(1142);function o(e){return function(e){let t=a.get(e);if(t)return t;let r=Promise.resolve(e);return a.set(e,r),Object.keys(e).forEach(t=>{n.wellKnownProperties.has(t)||(r[t]=e[t])}),r}(e)}let a=new WeakMap},5851:(e,t)=>{"use strict";function r(){return""}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getDeploymentIdQueryOrEmptyString",{enumerable:!0,get:function(){return r}})},5861:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"workAsyncStorage",{enumerable:!0,get:function(){return n.workAsyncStorageInstance}});let n=r(7828)},5881:(e,t)=>{"use strict";function r(e,t){let r=e[e.length-1];(!r||r.stack!==t.stack)&&e.push(t)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"enqueueConsecutiveDedupedError",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5938:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getExpectedRequestStore:function(){return o},getHmrRefreshHash:function(){return l},getPrerenderResumeDataCache:function(){return a},getRenderResumeDataCache:function(){return u},workUnitAsyncStorage:function(){return n.workUnitAsyncStorageInstance}});let n=r(4931);function o(e){let t=n.workUnitAsyncStorageInstance.getStore();if(t){if("request"===t.type)return t;if("prerender"===t.type||"prerender-ppr"===t.type||"prerender-legacy"===t.type)throw Object.defineProperty(Error(`\`${e}\` cannot be called inside a prerender. This is a bug in Next.js.`),"__NEXT_ERROR_CODE",{value:"E401",enumerable:!1,configurable:!0});if("cache"===t.type)throw Object.defineProperty(Error(`\`${e}\` cannot be called inside "use cache". Call it outside and pass an argument instead. Read more: https://nextjs.org/docs/messages/next-request-in-use-cache`),"__NEXT_ERROR_CODE",{value:"E37",enumerable:!1,configurable:!0});if("unstable-cache"===t.type)throw Object.defineProperty(Error(`\`${e}\` cannot be called inside unstable_cache. Call it outside and pass an argument instead. Read more: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`),"__NEXT_ERROR_CODE",{value:"E69",enumerable:!1,configurable:!0})}throw Object.defineProperty(Error(`\`${e}\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`),"__NEXT_ERROR_CODE",{value:"E251",enumerable:!1,configurable:!0})}function a(e){return"prerender"===e.type||"prerender-ppr"===e.type?e.prerenderResumeDataCache:null}function u(e){return"prerender-legacy"!==e.type&&"cache"!==e.type&&"unstable-cache"!==e.type?"request"===e.type?e.renderResumeDataCache:e.prerenderResumeDataCache:null}function l(e){var t;return"cache"===e.type?e.hmrRefreshHash:"request"===e.type?null==(t=e.cookies.get("__next_hmr_refresh_hash__"))?void 0:t.value:void 0}},6003:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return o}});let n=r(8912);function o(e){return(0,n.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6090:(e,t)=>{"use strict";function r(e){return"("===e[0]&&e.endsWith(")")}function n(e){return e.startsWith("@")&&"@children"!==e}function o(e,t){if(e.includes(a)){let e=JSON.stringify(t);return"{}"!==e?a+"?"+e:a}return e}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DEFAULT_SEGMENT_KEY:function(){return u},PAGE_SEGMENT_KEY:function(){return a},addSearchParamsIfPageSegment:function(){return o},isGroupSegment:function(){return r},isParallelRouteSegment:function(){return n}});let a="__PAGE__",u="__DEFAULT__"},6127:(e,t)=>{"use strict";function r(e){if("string"==typeof e)return"/_not-found"===e?"_not-found":u(e);let t=e[0],r=e[1],n=e[2],o=u(t);return"$"+n+"$"+o+"$"+u(r)}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ROOT_SEGMENT_KEY:function(){return n},encodeChildSegmentKey:function(){return o},encodeSegment:function(){return r}});let n="";function o(e,t,r){return e+"/"+("children"===t?r:`@${u(t)}/${r}`)}let a=/^[a-zA-Z0-9\-_@]+$/;function u(e){return a.test(e)?e:"!"+btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},6213:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{MetadataBoundary:function(){return a},OutletBoundary:function(){return l},ViewportBoundary:function(){return u}});let n=r(740),o={[n.METADATA_BOUNDARY_NAME]:function(e){let{children:t}=e;return t},[n.VIEWPORT_BOUNDARY_NAME]:function(e){let{children:t}=e;return t},[n.OUTLET_BOUNDARY_NAME]:function(e){let{children:t}=e;return t}},a=o[n.METADATA_BOUNDARY_NAME.slice(0)],u=o[n.VIEWPORT_BOUNDARY_NAME.slice(0)],l=o[n.OUTLET_BOUNDARY_NAME.slice(0)]},6378:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{Postpone:function(){return P},abortAndThrowOnSynchronousRequestDataAccess:function(){return R},abortOnSynchronousPlatformIOAccess:function(){return v},accessedDynamicData:function(){return A},annotateDynamicAccess:function(){return L},consumeDynamicAccess:function(){return D},createDynamicTrackingState:function(){return d},createDynamicValidationState:function(){return p},createHangingInputAbortSignal:function(){return I},createPostponedAbortSignal:function(){return U},formatDynamicAPIAccesses:function(){return N},getFirstDynamicReason:function(){return h},isDynamicPostpone:function(){return T},isPrerenderInterruptedError:function(){return C},markCurrentScopeAsDynamic:function(){return y},postponeWithTracking:function(){return S},throwIfDisallowedDynamic:function(){return K},throwToInterruptStaticGeneration:function(){return _},trackAllowedDynamicAccess:function(){return X},trackDynamicDataInDynamicRender:function(){return b},trackFallbackParamAccessed:function(){return g},trackSynchronousPlatformIOAccessInDev:function(){return E},trackSynchronousRequestDataAccessInDev:function(){return O},useDynamicRouteParams:function(){return F}});let n=function(e){return e&&e.__esModule?e:{default:e}}(r(2115)),o=r(406),a=r(6830),u=r(5938),l=r(5861),i=r(3649),c=r(740),s=r(2301),f="function"==typeof n.default.unstable_postpone;function d(e){return{isDebugDynamicAccesses:e,dynamicAccesses:[],syncDynamicExpression:void 0,syncDynamicErrorWithStack:null}}function p(){return{hasSuspendedDynamic:!1,hasDynamicMetadata:!1,hasDynamicViewport:!1,hasSyncDynamicErrors:!1,dynamicErrors:[]}}function h(e){var t;return null==(t=e.dynamicAccesses[0])?void 0:t.expression}function y(e,t,r){if((!t||"cache"!==t.type&&"unstable-cache"!==t.type)&&!e.forceDynamic&&!e.forceStatic){if(e.dynamicShouldError)throw Object.defineProperty(new a.StaticGenBailoutError(`Route ${e.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${r}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E553",enumerable:!1,configurable:!0});if(t){if("prerender-ppr"===t.type)S(e.route,r,t.dynamicTracking);else if("prerender-legacy"===t.type){t.revalidate=0;let n=Object.defineProperty(new o.DynamicServerError(`Route ${e.route} couldn't be rendered statically because it used ${r}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`),"__NEXT_ERROR_CODE",{value:"E550",enumerable:!1,configurable:!0});throw e.dynamicUsageDescription=r,e.dynamicUsageStack=n.stack,n}}}}function g(e,t){let r=u.workUnitAsyncStorage.getStore();r&&"prerender-ppr"===r.type&&S(e.route,t,r.dynamicTracking)}function _(e,t,r){let n=Object.defineProperty(new o.DynamicServerError(`Route ${t.route} couldn't be rendered statically because it used \`${e}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`),"__NEXT_ERROR_CODE",{value:"E558",enumerable:!1,configurable:!0});throw r.revalidate=0,t.dynamicUsageDescription=e,t.dynamicUsageStack=n.stack,n}function b(e,t){t&&"cache"!==t.type&&"unstable-cache"!==t.type&&("prerender"===t.type||"prerender-legacy"===t.type)&&(t.revalidate=0)}function m(e,t,r){let n=x(`Route ${e} needs to bail out of prerendering at this point because it used ${t}.`);r.controller.abort(n);let o=r.dynamicTracking;o&&o.dynamicAccesses.push({stack:o.isDebugDynamicAccesses?Error().stack:void 0,expression:t})}function v(e,t,r,n){let o=n.dynamicTracking;return o&&null===o.syncDynamicErrorWithStack&&(o.syncDynamicExpression=t,o.syncDynamicErrorWithStack=r),m(e,t,n)}function E(e){e.prerenderPhase=!1}function R(e,t,r,n){let o=n.dynamicTracking;throw o&&null===o.syncDynamicErrorWithStack&&(o.syncDynamicExpression=t,o.syncDynamicErrorWithStack=r,!0===n.validating&&(o.syncDynamicLogged=!0)),m(e,t,n),x(`Route ${e} needs to bail out of prerendering at this point because it used ${t}.`)}let O=E;function P({reason:e,route:t}){let r=u.workUnitAsyncStorage.getStore();S(t,e,r&&"prerender-ppr"===r.type?r.dynamicTracking:null)}function S(e,t,r){k(),r&&r.dynamicAccesses.push({stack:r.isDebugDynamicAccesses?Error().stack:void 0,expression:t}),n.default.unstable_postpone(j(e,t))}function j(e,t){return`Route ${e} needs to bail out of prerendering at this point because it used ${t}. React throws this special object to indicate where. It should not be caught by your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`}function T(e){return"object"==typeof e&&null!==e&&"string"==typeof e.message&&w(e.message)}function w(e){return e.includes("needs to bail out of prerendering at this point because it used")&&e.includes("Learn more: https://nextjs.org/docs/messages/ppr-caught-error")}if(!1===w(j("%%%","^^^")))throw Object.defineProperty(Error("Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js"),"__NEXT_ERROR_CODE",{value:"E296",enumerable:!1,configurable:!0});let M="NEXT_PRERENDER_INTERRUPTED";function x(e){let t=Object.defineProperty(Error(e),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return t.digest=M,t}function C(e){return"object"==typeof e&&null!==e&&e.digest===M&&"name"in e&&"message"in e&&e instanceof Error}function A(e){return e.length>0}function D(e,t){return e.dynamicAccesses.push(...t.dynamicAccesses),e.dynamicAccesses}function N(e){return e.filter(e=>"string"==typeof e.stack&&e.stack.length>0).map(({expression:e,stack:t})=>(t=t.split("\n").slice(4).filter(e=>!(e.includes("node_modules/next/")||e.includes(" ()")||e.includes(" (node:"))).join("\n"),`Dynamic API Usage Debug - ${e}: +${t}`))}function k(){if(!f)throw Object.defineProperty(Error("Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js"),"__NEXT_ERROR_CODE",{value:"E224",enumerable:!1,configurable:!0})}function U(e){k();let t=new AbortController;try{n.default.unstable_postpone(e)}catch(e){t.abort(e)}return t.signal}function I(e){let t=new AbortController;return e.cacheSignal?e.cacheSignal.inputReady().then(()=>{t.abort()}):(0,s.scheduleOnNextTick)(()=>t.abort()),t.signal}function L(e,t){let r=t.dynamicTracking;r&&r.dynamicAccesses.push({stack:r.isDebugDynamicAccesses?Error().stack:void 0,expression:e})}function F(e){if("undefined"==typeof window){let t=l.workAsyncStorage.getStore();if(t&&t.isStaticGeneration&&t.fallbackRouteParams&&t.fallbackRouteParams.size>0){let r=u.workUnitAsyncStorage.getStore();r&&("prerender"===r.type?n.default.use((0,i.makeHangingPromise)(r.renderSignal,e)):"prerender-ppr"===r.type?S(t.route,e,r.dynamicTracking):"prerender-legacy"===r.type&&_(e,t,r))}}}let H=/\n\s+at Suspense \(\)/,B=RegExp(`\\n\\s+at ${c.METADATA_BOUNDARY_NAME}[\\n\\s]`),$=RegExp(`\\n\\s+at ${c.VIEWPORT_BOUNDARY_NAME}[\\n\\s]`),W=RegExp(`\\n\\s+at ${c.OUTLET_BOUNDARY_NAME}[\\n\\s]`);function X(e,t,r,n,o){if(!W.test(t)){if(B.test(t)){r.hasDynamicMetadata=!0;return}if($.test(t)){r.hasDynamicViewport=!0;return}if(H.test(t)){r.hasSuspendedDynamic=!0;return}else if(n.syncDynamicErrorWithStack||o.syncDynamicErrorWithStack){r.hasSyncDynamicErrors=!0;return}else{let n=function(e,t){let r=Object.defineProperty(Error(e),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return r.stack="Error: "+e+t,r}(`Route "${e}": A component accessed data, headers, params, searchParams, or a short-lived cache without a Suspense boundary nor a "use cache" above it. We don't have the exact line number added to error messages yet but you can see which component in the stack below. See more info: https://nextjs.org/docs/messages/next-prerender-missing-suspense`,t);r.dynamicErrors.push(n);return}}}function K(e,t,r,n){let o,u,l;if(r.syncDynamicErrorWithStack?(o=r.syncDynamicErrorWithStack,u=r.syncDynamicExpression,l=!0===r.syncDynamicLogged):n.syncDynamicErrorWithStack?(o=n.syncDynamicErrorWithStack,u=n.syncDynamicExpression,l=!0===n.syncDynamicLogged):(o=null,u=void 0,l=!1),t.hasSyncDynamicErrors&&o)throw l||console.error(o),new a.StaticGenBailoutError;let i=t.dynamicErrors;if(i.length){for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createDedupedByCallsiteServerErrorLoggerDev",{enumerable:!0,get:function(){return i}});let n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=o(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&Object.prototype.hasOwnProperty.call(e,u)){var l=a?Object.getOwnPropertyDescriptor(e,u):null;l&&(l.get||l.set)?Object.defineProperty(n,u,l):n[u]=e[u]}return n.default=e,r&&r.set(e,n),n}(r(2115));function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(o=function(e){return e?r:t})(e)}let a={current:null},u="function"==typeof n.cache?n.cache:e=>e,l=console.warn;function i(e){return function(...t){l(e(...t))}}u(e=>{try{l(a.current)}finally{a.current=null}})},6449:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNavigatingToNewRootLayout",{enumerable:!0,get:function(){return function e(t,r){let n=t[0],o=r[0];if(Array.isArray(n)&&Array.isArray(o)){if(n[0]!==o[0]||n[2]!==o[2])return!0}else if(n!==o)return!0;if(t[4])return!r[4];if(r[4])return!0;let a=Object.values(t[1])[0],u=Object.values(r[1])[0];return!a||!u||e(a,u)}}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6494:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{useReducer:function(){return l},useUnwrapState:function(){return u}});let n=r(9955)._(r(2115)),o=r(2707),a=r(5235);function u(e){return(0,o.isThenable)(e)?(0,n.use)(e):e}function l(e){let[t,r]=n.default.useState(e.state),o=(0,a.useSyncDevRenderIndicator)();return[t,(0,n.useCallback)(t=>{o(()=>{e.dispatch(t,r)})},[e,o])]}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6501:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectBoundary:function(){return f},RedirectErrorBoundary:function(){return s}});let n=r(9955),o=r(5155),a=n._(r(2115)),u=r(6658),l=r(9100),i=r(7563);function c(e){let{redirect:t,reset:r,redirectType:n}=e,o=(0,u.useRouter)();return(0,a.useEffect)(()=>{a.default.startTransition(()=>{n===i.RedirectType.push?o.push(t,{}):o.replace(t,{}),r()})},[t,n,r,o]),null}class s extends a.default.Component{static getDerivedStateFromError(e){if((0,i.isRedirectError)(e))return{redirect:(0,l.getURLFromRedirectError)(e),redirectType:(0,l.getRedirectTypeFromError)(e)};throw e}render(){let{redirect:e,redirectType:t}=this.state;return null!==e&&null!==t?(0,o.jsx)(c,{redirect:e,redirectType:t,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(e){super(e),this.state={redirect:null,redirectType:null}}}function f(e){let{children:t}=e,r=(0,u.useRouter)();return(0,o.jsx)(s,{router:r,children:t})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6573:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return a}});let n=r(1246),o=r(4046),a=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:r,hash:a}=(0,o.parsePath)(e);return""+(0,n.removeTrailingSlash)(t)+r+a};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6654:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentParam",{enumerable:!0,get:function(){return o}});let n=r(8456);function o(e){let t=n.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t));return(t&&(e=e.slice(t.length)),e.startsWith("[[...")&&e.endsWith("]]"))?{type:"optional-catchall",param:e.slice(5,-2)}:e.startsWith("[...")&&e.endsWith("]")?{type:t?"catchall-intercepted":"catchall",param:e.slice(4,-1)}:e.startsWith("[")&&e.endsWith("]")?{type:t?"dynamic-intercepted":"dynamic",param:e.slice(1,-1)}:null}},6658:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ReadonlyURLSearchParams:function(){return i.ReadonlyURLSearchParams},RedirectType:function(){return i.RedirectType},ServerInsertedHTMLContext:function(){return s.ServerInsertedHTMLContext},forbidden:function(){return i.forbidden},notFound:function(){return i.notFound},permanentRedirect:function(){return i.permanentRedirect},redirect:function(){return i.redirect},unauthorized:function(){return i.unauthorized},unstable_rethrow:function(){return i.unstable_rethrow},useParams:function(){return h},usePathname:function(){return d},useRouter:function(){return p},useSearchParams:function(){return f},useSelectedLayoutSegment:function(){return g},useSelectedLayoutSegments:function(){return y},useServerInsertedHTML:function(){return s.useServerInsertedHTML}});let n=r(2115),o=r(1394),a=r(8703),u=r(4183),l=r(6090),i=r(4557),c=r(6378),s=r(4125);function f(){let e=(0,n.useContext)(a.SearchParamsContext),t=(0,n.useMemo)(()=>e?new i.ReadonlyURLSearchParams(e):null,[e]);if("undefined"==typeof window){let{bailoutToClientRendering:e}=r(8967);e("useSearchParams()")}return t}function d(){return(0,c.useDynamicRouteParams)("usePathname()"),(0,n.useContext)(a.PathnameContext)}function p(){let e=(0,n.useContext)(o.AppRouterContext);if(null===e)throw Object.defineProperty(Error("invariant expected app router to be mounted"),"__NEXT_ERROR_CODE",{value:"E238",enumerable:!1,configurable:!0});return e}function h(){return(0,c.useDynamicRouteParams)("useParams()"),(0,n.useContext)(a.PathParamsContext)}function y(e){void 0===e&&(e="children"),(0,c.useDynamicRouteParams)("useSelectedLayoutSegments()");let t=(0,n.useContext)(o.LayoutRouterContext);return t?function e(t,r,n,o){let a;if(void 0===n&&(n=!0),void 0===o&&(o=[]),n)a=t[1][r];else{var i;let e=t[1];a=null!=(i=e.children)?i:Object.values(e)[0]}if(!a)return o;let c=a[0],s=(0,u.getSegmentValue)(c);return!s||s.startsWith(l.PAGE_SEGMENT_KEY)?o:(o.push(s),e(a,r,!1,o))}(t.parentTree,e):null}function g(e){void 0===e&&(e="children"),(0,c.useDynamicRouteParams)("useSelectedLayoutSegment()");let t=y(e);if(!t||0===t.length)return null;let r="children"===e?t[0]:t[t.length-1];return r===l.DEFAULT_SEGMENT_KEY?null:r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6674:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"findHeadInCache",{enumerable:!0,get:function(){return o}});let n=r(5404);function o(e,t){return function e(t,r,o){if(0===Object.keys(r).length)return[t,o];for(let a in r){let[u,l]=r[a],i=t.parallelRoutes.get(a);if(!i)continue;let c=(0,n.createRouterCacheKey)(u),s=i.get(c);if(!s)continue;let f=e(s,l,o+"/"+c);if(f)return f}return null}(e,t,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6802:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"setCacheBustingSearchParam",{enumerable:!0,get:function(){return a}});let n=r(1233),o=r(2836),a=(e,t)=>{let r=(0,n.hexHash)([t[o.NEXT_ROUTER_PREFETCH_HEADER]||"0",t[o.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]||"0",t[o.NEXT_ROUTER_STATE_TREE_HEADER],t[o.NEXT_URL]].join(",")),a=e.search,u=(a.startsWith("?")?a.slice(1):a).split("&").filter(Boolean);u.push(o.NEXT_RSC_UNION_QUERY+"="+r),e.search=u.length?"?"+u.join("&"):""};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6830:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{StaticGenBailoutError:function(){return n},isStaticGenBailoutError:function(){return o}});let r="NEXT_STATIC_GEN_BAILOUT";class n extends Error{constructor(...e){super(...e),this.code=r}}function o(e){return"object"==typeof e&&null!==e&&"code"in e&&e.code===r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6833:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{createMutableActionQueue:function(){return s},getCurrentAppRouterState:function(){return f}});let n=r(4445),o=r(1677),a=r(2115),u=r(2707);function l(e,t){null!==e.pending&&(e.pending=e.pending.next,null!==e.pending?i({actionQueue:e,action:e.pending,setState:t}):e.needsRefresh&&(e.needsRefresh=!1,e.dispatch({type:n.ACTION_REFRESH,origin:window.location.origin},t)))}async function i(e){let{actionQueue:t,action:r,setState:n}=e,o=t.state;t.pending=r;let a=r.payload,i=t.action(o,a);function c(e){!r.discarded&&(t.state=e,l(t,n),r.resolve(e))}(0,u.isThenable)(i)?i.then(c,e=>{l(t,n),r.reject(e)}):c(i)}let c=null;function s(e){let t={state:e,dispatch:(e,r)=>(function(e,t,r){let o={resolve:r,reject:()=>{}};if(t.type!==n.ACTION_RESTORE){let e=new Promise((e,t)=>{o={resolve:e,reject:t}});(0,a.startTransition)(()=>{r(e)})}let u={payload:t,next:null,resolve:o.resolve,reject:o.reject};null===e.pending?(e.last=u,i({actionQueue:e,action:u,setState:r})):t.type===n.ACTION_NAVIGATE||t.type===n.ACTION_RESTORE?(e.pending.discarded=!0,e.last=u,e.pending.payload.type===n.ACTION_SERVER_ACTION&&(e.needsRefresh=!0),i({actionQueue:e,action:u,setState:r})):(null!==e.last&&(e.last.next=u),e.last=u)})(t,e,r),action:async(e,t)=>(0,o.reducer)(e,t),pending:null,last:null};if("undefined"!=typeof window){if(null!==c)throw Object.defineProperty(Error("Internal Next.js Error: createMutableActionQueue was called more than once"),"__NEXT_ERROR_CODE",{value:"E624",enumerable:!1,configurable:!0});c=t}return t}function f(){return null!==c?c.state:null}},6897:(e,t)=>{"use strict";var r=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function o(e,t,n){var o=null;if(void 0!==n&&(o=""+n),void 0!==t.key&&(o=""+t.key),"key"in t)for(var a in n={},t)"key"!==a&&(n[a]=t[a]);else n=t;return{$$typeof:r,type:e,key:o,ref:void 0!==(t=n.ref)?t:null,props:n}}t.Fragment=n,t.jsx=o,t.jsxs=o},6976:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverPatchReducer",{enumerable:!0,get:function(){return s}});let n=r(3436),o=r(1053),a=r(6449),u=r(2603),l=r(655),i=r(7344),c=r(3423);function s(e,t){let{serverResponse:{flightData:r,canonicalUrl:s}}=t,f={};if(f.preserveCustomHistoryState=!1,"string"==typeof r)return(0,u.handleExternalUrl)(e,f,r,e.pushRef.pendingPush);let d=e.tree,p=e.cache;for(let t of r){let{segmentPath:r,tree:i}=t,h=(0,o.applyRouterStatePatchToTree)(["",...r],d,i,e.canonicalUrl);if(null===h)return e;if((0,a.isNavigatingToNewRootLayout)(d,h))return(0,u.handleExternalUrl)(e,f,e.canonicalUrl,e.pushRef.pendingPush);let y=s?(0,n.createHrefFromUrl)(s):void 0;y&&(f.canonicalUrl=y);let g=(0,c.createEmptyCacheNode)();(0,l.applyFlightData)(p,g,t),f.patchedTree=h,f.cache=g,p=g,d=h}return(0,i.handleMutable)(e,f)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7033:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ClientPageRoot",{enumerable:!0,get:function(){return a}});let n=r(5155),o=r(4940);function a(e){let{Component:t,searchParams:a,params:u,promises:l}=e;if("undefined"==typeof window){let e,l;let{workAsyncStorage:i}=r(5861),c=i.getStore();if(!c)throw Object.defineProperty(new o.InvariantError("Expected workStore to exist when handling searchParams in a client Page."),"__NEXT_ERROR_CODE",{value:"E564",enumerable:!1,configurable:!0});let{createSearchParamsFromClient:s}=r(2130);e=s(a,c);let{createParamsFromClient:f}=r(4383);return l=f(u,c),(0,n.jsx)(t,{params:l,searchParams:e})}{let{createRenderSearchParamsFromClient:e}=r(4124),o=e(a),{createRenderParamsFromClient:l}=r(5737),i=l(u);return(0,n.jsx)(t,{params:i,searchParams:o})}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7088:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getHydrationWarningType:function(){return l},getReactHydrationDiffSegments:function(){return s},hydrationErrorState:function(){return o},storeHydrationErrorStateFromConsoleArgs:function(){return f}});let n=r(5384),o={},a=new Set(["Warning: In HTML, %s cannot be a child of <%s>.%s\nThis will cause a hydration error.%s","Warning: In HTML, %s cannot be a descendant of <%s>.\nThis will cause a hydration error.%s","Warning: In HTML, text nodes cannot be a child of <%s>.\nThis will cause a hydration error.","Warning: In HTML, whitespace text nodes cannot be a child of <%s>. Make sure you don't have any extra whitespace between tags on each line of your source code.\nThis will cause a hydration error.","Warning: Expected server HTML to contain a matching <%s> in <%s>.%s","Warning: Did not expect server HTML to contain a <%s> in <%s>.%s"]),u=new Set(['Warning: Expected server HTML to contain a matching text node for "%s" in <%s>.%s','Warning: Did not expect server HTML to contain the text node "%s" in <%s>.%s']),l=e=>{if("string"!=typeof e)return"text";let t=e.startsWith("Warning: ")?e:"Warning: "+e;return i(t)?"tag":c(t)?"text-in-tag":"text"},i=e=>a.has(e),c=e=>u.has(e),s=e=>{if(e){let{message:t,diff:r}=(0,n.getHydrationErrorStackInfo)(e);if(t)return[t,r]}};function f(){for(var e=arguments.length,t=Array(e),r=0;r{e=e.trim();let[,u,l]=/at (\w+)( \((.*)\))?/.exec(e)||[];return l||(u===t&&-1===o?o=n:u!==r||-1!==a||(a=n)),l?"":u}).filter(Boolean).reverse(),c="";for(let e=0;e "+" ".repeat(Math.max(2*e-2,0)+2)+"<"+t+">\n":c+=" ".repeat(2*e+2)+"<"+t+">\n"}if("text"===u){let e=" ".repeat(2*i.length);c+="+ "+e+'"'+t+'"\n'+("- "+e+'"'+r)+'"\n'}else if("text-in-tag"===u){let e=" ".repeat(2*i.length);c+="> "+e+"<"+r+">\n"+("> "+e+'"'+t)+'"\n'}return c}(a,u,i,n):o.reactOutputComponentDiff=n,o.warning=r,o.serverContent=u,o.clientContent=i}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7173:(e,t)=>{"use strict";function r(e){let t=parseInt(e.slice(0,2),16),r=t>>1&63,n=Array(6);for(let e=0;e<6;e++){let t=r>>5-e&1;n[e]=1===t}return{type:1==(t>>7&1)?"use-cache":"server-action",usedArgs:n,hasRestArgs:1==(1&t)}}function n(e,t){let r=Array(e.length);for(let n=0;n=6&&t.hasRestArgs)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{extractInfoFromServerReferenceId:function(){return r},omitUnusedArgs:function(){return n}})},7197:(e,t,r)=>{"use strict";e.exports=r(9062)},7200:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(8132),(0,r(7297).appBootstrap)(()=>{let{hydrate:e}=r(847);r(3423),r(5244),e()}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7251:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"onRecoverableError",{enumerable:!0,get:function(){return i}});let n=r(306),o=r(3719),a=r(7489),u=r(8227),l=n._(r(9762)),i=(e,t)=>{let r=(0,l.default)(e)&&"cause"in e?e.cause:e,n=(0,u.getReactStitchedError)(r);(0,o.isBailoutToCSRError)(r)||(0,a.reportGlobalError)(n)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7297:(e,t)=>{"use strict";function r(e){var t,r;t=self.__next_s,r=()=>{e()},t&&t.length?t.reduce((e,t)=>{let[r,n]=t;return e.then(()=>new Promise((e,t)=>{let o=document.createElement("script");if(n)for(let e in n)"children"!==e&&o.setAttribute(e,n[e]);r?(o.src=r,o.onload=()=>e(),o.onerror=t):n&&(o.innerHTML=n.children,setTimeout(e)),document.head.appendChild(o)}))},Promise.resolve()).catch(e=>{console.error(e)}).then(()=>{r()}):r()}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"appBootstrap",{enumerable:!0,get:function(){return r}}),window.next={version:"15.2.0",appDir:!0},("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7344:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleMutable",{enumerable:!0,get:function(){return a}});let n=r(845);function o(e){return void 0!==e}function a(e,t){var r,a;let u=null==(r=t.shouldScroll)||r,l=e.nextUrl;if(o(t.patchedTree)){let r=(0,n.computeChangedPath)(e.tree,t.patchedTree);r?l=r:l||(l=e.canonicalUrl)}return{canonicalUrl:o(t.canonicalUrl)?t.canonicalUrl===e.canonicalUrl?e.canonicalUrl:t.canonicalUrl:e.canonicalUrl,pushRef:{pendingPush:o(t.pendingPush)?t.pendingPush:e.pushRef.pendingPush,mpaNavigation:o(t.mpaNavigation)?t.mpaNavigation:e.pushRef.mpaNavigation,preserveCustomHistoryState:o(t.preserveCustomHistoryState)?t.preserveCustomHistoryState:e.pushRef.preserveCustomHistoryState},focusAndScrollRef:{apply:!!u&&(!!o(null==t?void 0:t.scrollableSegments)||e.focusAndScrollRef.apply),onlyHashChange:t.onlyHashChange||!1,hashFragment:u?t.hashFragment&&""!==t.hashFragment?decodeURIComponent(t.hashFragment.slice(1)):e.focusAndScrollRef.hashFragment:null,segmentPaths:u?null!=(a=null==t?void 0:t.scrollableSegments)?a:e.focusAndScrollRef.segmentPaths:[]},cache:t.cache?t.cache:e.cache,prefetchCache:t.prefetchCache?t.prefetchCache:e.prefetchCache,tree:o(t.patchedTree)?t.patchedTree:e.tree,nextUrl:l}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7358:e=>{var t,r,n,o=e.exports={};function a(){throw Error("setTimeout has not been defined")}function u(){throw Error("clearTimeout has not been defined")}function l(e){if(t===setTimeout)return setTimeout(e,0);if((t===a||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:a}catch(e){t=a}try{r="function"==typeof clearTimeout?clearTimeout:u}catch(e){r=u}}();var i=[],c=!1,s=-1;function f(){c&&n&&(c=!1,n.length?i=n.concat(i):s=-1,i.length&&d())}function d(){if(!c){var e=l(f);c=!0;for(var t=i.length;t;){for(n=i,i=[];++s1)for(var r=1;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hmrRefreshReducer",{enumerable:!0,get:function(){return n}}),r(4091),r(3436),r(1053),r(6449),r(2603),r(7344),r(655),r(3423),r(9786),r(941);let n=function(e,t){return e};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7361:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RedirectStatusCode",{enumerable:!0,get:function(){return r}});var r=function(e){return e[e.SeeOther=303]="SeeOther",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e}({});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7489:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reportGlobalError",{enumerable:!0,get:function(){return r}});let r="function"==typeof reportError?reportError:e=>{globalThis.console.error(e)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7515:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isDynamicUsageError",{enumerable:!0,get:function(){return l}});let n=r(406),o=r(3719),a=r(179),u=r(6378),l=e=>(0,n.isDynamicServerError)(e)||(0,o.isBailoutToCSRError)(e)||(0,a.isNextRouterError)(e)||(0,u.isDynamicPostpone)(e)},7539:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{AsyncMetadata:function(){return i},AsyncMetadataOutlet:function(){return s}});let n=r(5155),o=r(2115),a=r(8538);function u(e){let{promise:t}=e,{metadata:r}=(0,o.use)(t);return(0,a.useServerInsertedMetadata)(()=>r),null}function l(e){let{promise:t}=e,{metadata:r,error:n}=(0,o.use)(t);return n?null:r}function i(e){let{promise:t}=e;return(0,n.jsx)(n.Fragment,{children:"undefined"==typeof window?(0,n.jsx)(u,{promise:t}):(0,n.jsx)(l,{promise:t})})}function c(e){let{promise:t}=e,{error:r,digest:n}=(0,o.use)(t);if(r)throw n&&(r.digest=n),r;return null}function s(e){let{promise:t}=e;return(0,n.jsx)(o.Suspense,{fallback:null,children:(0,n.jsx)(c,{promise:t})})}},7554:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"unstable_rethrow",{enumerable:!0,get:function(){return function e(t){if((0,l.isNextRouterError)(t)||(0,u.isBailoutToCSRError)(t)||(0,n.isDynamicUsageError)(t)||(0,a.isPostpone)(t)||(0,o.isHangingPromiseRejectionError)(t))throw t;t instanceof Error&&"cause"in t&&e(t.cause)}}});let n=r(7515),o=r(3649),a=r(4819),u=r(3719),l=r(179);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7563:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{REDIRECT_ERROR_CODE:function(){return o},RedirectType:function(){return a},isRedirectError:function(){return u}});let n=r(7361),o="NEXT_REDIRECT";var a=function(e){return e.push="push",e.replace="replace",e}({});function u(e){if("object"!=typeof e||null===e||!("digest"in e)||"string"!=typeof e.digest)return!1;let t=e.digest.split(";"),[r,a]=t,u=t.slice(2,-2).join(";"),l=Number(t.at(-2));return r===o&&("replace"===a||"push"===a)&&"string"==typeof u&&!isNaN(l)&&l in n.RedirectStatusCode}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7650:(e,t,r)=>{"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=r(8730)},7663:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheByRouterState",{enumerable:!0,get:function(){return o}});let n=r(5404);function o(e,t,r){for(let o in r[1]){let a=r[1][o][0],u=(0,n.createRouterCacheKey)(a),l=t.parallelRoutes.get(o);if(l){let t=new Map(l);t.delete(u),e.parallelRoutes.set(o,t)}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7828:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"workAsyncStorageInstance",{enumerable:!0,get:function(){return n}});let n=(0,r(4054).createAsyncLocalStorage)()},7864:(e,t)=>{"use strict";function r(){let e={parent:null,key:null,hasValue:!1,value:null,map:null},t=null,r=null;function n(n){if(r===n)return t;let o=e;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PromiseQueue",{enumerable:!0,get:function(){return c}});let n=r(2141),o=r(3523);var a=o._("_maxConcurrency"),u=o._("_runningCount"),l=o._("_queue"),i=o._("_processNext");class c{enqueue(e){let t,r;let o=new Promise((e,n)=>{t=e,r=n}),a=async()=>{try{n._(this,u)[u]++;let r=await e();t(r)}catch(e){r(e)}finally{n._(this,u)[u]--,n._(this,i)[i]()}};return n._(this,l)[l].push({promiseFn:o,task:a}),n._(this,i)[i](),o}bump(e){let t=n._(this,l)[l].findIndex(t=>t.promiseFn===e);if(t>-1){let e=n._(this,l)[l].splice(t,1)[0];n._(this,l)[l].unshift(e),n._(this,i)[i](!0)}}constructor(e=5){Object.defineProperty(this,i,{value:s}),Object.defineProperty(this,a,{writable:!0,value:void 0}),Object.defineProperty(this,u,{writable:!0,value:void 0}),Object.defineProperty(this,l,{writable:!0,value:void 0}),n._(this,a)[a]=e,n._(this,u)[u]=0,n._(this,l)[l]=[]}}function s(e){if(void 0===e&&(e=!1),(n._(this,u)[u]0){var t;null==(t=n._(this,l)[l].shift())||t.task()}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8127:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getAppBuildId:function(){return o},setAppBuildId:function(){return n}});let r="";function n(e){r=e}function o(){return r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8132:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(5851);let n=r(8284);{let e=r.u;r.u=function(){for(var t=arguments.length,r=Array(t),o=0;o{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"afterTaskAsyncStorage",{enumerable:!0,get:function(){return n.afterTaskAsyncStorageInstance}});let n=r(4117)},8173:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return P},pingVisibleLinks:function(){return R}});let n=r(306),o=r(5155),a=n._(r(2115)),u=r(180),l=r(1394),i=r(4445),c=r(5353),s=r(2170),f=r(9544);r(2363);let d=r(8592);r(6833);let p=r(2633),h=r(3423),y=r(3099),g="function"==typeof WeakMap?new WeakMap:new Map,_=new Set,b="function"==typeof IntersectionObserver?new IntersectionObserver(function(e){for(let t of e){let e=t.intersectionRatio>0;!function(e,t){let r=g.get(e);void 0!==r&&(r.isVisible=t,t?_.add(r):_.delete(r),E(r))}(t.target,e)}},{rootMargin:"200px"}):null;function m(e){let t=g.get(e);if(void 0!==t){g.delete(e),_.delete(t);let r=t.prefetchTask;null!==r&&(0,d.cancelPrefetchTask)(r)}null!==b&&b.unobserve(e)}function v(e){let t=g.get(e);void 0!==t&&void 0!==t&&(t.wasHoveredOrTouched=!0,E(t))}function E(e){var t;let r=e.prefetchTask;if(!e.isVisible){null!==r&&(0,d.cancelPrefetchTask)(r);return}t=e,"undefined"!=typeof window&&(async()=>t.router.prefetch(t.prefetchHref,{kind:t.kind}))().catch(e=>{})}function R(e,t){let r=(0,y.getCurrentCacheVersion)();for(let n of _){let o=n.prefetchTask;if(null!==o&&n.cacheVersion===r&&o.key.nextUrl===e&&o.treeAtTimeOfPrefetch===t)continue;null!==o&&(0,d.cancelPrefetchTask)(o);let a=(0,p.createCacheKey)(n.prefetchHref,e),u=n.wasHoveredOrTouched?d.PrefetchPriority.Intent:d.PrefetchPriority.Default;n.prefetchTask=(0,d.schedulePrefetchTask)(a,t,n.kind===i.PrefetchKind.FULL,u),n.cacheVersion=(0,y.getCurrentCacheVersion)()}}function O(e){return"string"==typeof e?e:(0,u.formatUrl)(e)}let P=a.default.forwardRef(function(e,t){let r,n;let{href:u,as:d,children:p,prefetch:y=null,passHref:_,replace:E,shallow:R,scroll:P,onClick:S,onMouseEnter:j,onTouchStart:T,legacyBehavior:w=!1,...M}=e;r=p,w&&("string"==typeof r||"number"==typeof r)&&(r=(0,o.jsx)("a",{children:r}));let x=a.default.useContext(l.AppRouterContext),C=!1!==y,A=null===y?i.PrefetchKind.AUTO:i.PrefetchKind.FULL,{href:D,as:N}=a.default.useMemo(()=>{let e=O(u);return{href:e,as:d?O(d):e}},[u,d]);w&&(n=a.default.Children.only(r));let k=w?n&&"object"==typeof n&&n.ref:t,U=a.default.useCallback(e=>(C&&null!==x&&function(e,t,r,n){let o=null;try{if(o=(0,h.createPrefetchURL)(t),null===o)return}catch(e){("function"==typeof reportError?reportError:console.error)("Cannot prefetch '"+t+"' because it cannot be converted to a URL.");return}let a={prefetchHref:o.href,router:r,kind:n,isVisible:!1,wasHoveredOrTouched:!1,prefetchTask:null,cacheVersion:-1};void 0!==g.get(e)&&m(e),g.set(e,a),null!==b&&b.observe(e)}(e,D,x,A),()=>{m(e)}),[C,D,x,A]),I={ref:(0,c.useMergedRef)(U,k),onClick(e){w||"function"!=typeof S||S(e),w&&n.props&&"function"==typeof n.props.onClick&&n.props.onClick(e),x&&!e.defaultPrevented&&!function(e,t,r,n,o,u,l){let{nodeName:i}=e.currentTarget;!("A"===i.toUpperCase()&&function(e){let t=e.currentTarget.getAttribute("target");return t&&"_self"!==t||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.nativeEvent&&2===e.nativeEvent.which}(e))&&(e.preventDefault(),a.default.startTransition(()=>{let e=null==l||l;"beforePopState"in t?t[o?"replace":"push"](r,n,{shallow:u,scroll:e}):t[o?"replace":"push"](n||r,{scroll:e})}))}(e,x,D,N,E,R,P)},onMouseEnter(e){w||"function"!=typeof j||j(e),w&&n.props&&"function"==typeof n.props.onMouseEnter&&n.props.onMouseEnter(e),x&&C&&v(e.currentTarget)},onTouchStart:function(e){w||"function"!=typeof T||T(e),w&&n.props&&"function"==typeof n.props.onTouchStart&&n.props.onTouchStart(e),x&&C&&v(e.currentTarget)}};return(0,s.isAbsoluteUrl)(N)?I.href=N:w&&!_&&("a"!==n.type||"href"in n.props)||(I.href=(0,f.addBasePath)(N)),w?a.default.cloneElement(n,I):(0,o.jsx)("a",{...M,...I,children:r})});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8227:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getReactStitchedError",{enumerable:!0,get:function(){return c}});let n=r(306),o=n._(r(2115)),a=n._(r(9762)),u=r(9423),l="react-stack-bottom-frame",i=RegExp("(at "+l+" )|("+l+"\\@)");function c(e){let t=(0,a.default)(e),r=t&&e.stack||"",n=t?e.message:"",l=r.split("\n"),c=l.findIndex(e=>i.test(e)),s=c>=0?l.slice(0,c).join("\n"):r,f=Object.defineProperty(Error(n),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return Object.assign(f,e),(0,u.copyNextErrorCode)(e,f),f.stack=s,function(e){if(!o.default.captureOwnerStack)return;let t=e.stack||"",r=o.default.captureOwnerStack();r&&!1===t.endsWith(r)&&(t+=r,e.stack=t)}(f),f}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8262:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AppRouterAnnouncer",{enumerable:!0,get:function(){return u}});let n=r(2115),o=r(7650),a="next-route-announcer";function u(e){let{tree:t}=e,[r,u]=(0,n.useState)(null);(0,n.useEffect)(()=>(u(function(){var e;let t=document.getElementsByName(a)[0];if(null==t?void 0:null==(e=t.shadowRoot)?void 0:e.childNodes[0])return t.shadowRoot.childNodes[0];{let e=document.createElement(a);e.style.cssText="position:absolute";let t=document.createElement("div");return t.ariaLive="assertive",t.id="__next-route-announcer__",t.role="alert",t.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal",e.attachShadow({mode:"open"}).appendChild(t),document.body.appendChild(e),t}}()),()=>{let e=document.getElementsByTagName(a)[0];(null==e?void 0:e.isConnected)&&document.body.removeChild(e)}),[]);let[l,i]=(0,n.useState)(""),c=(0,n.useRef)(void 0);return(0,n.useEffect)(()=>{let e="";if(document.title)e=document.title;else{let t=document.querySelector("h1");t&&(e=t.innerText||t.textContent||"")}void 0!==c.current&&c.current!==e&&i(e),c.current=e},[t]),r?(0,o.createPortal)(l,r):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8284:(e,t)=>{"use strict";function r(e){return e.split("/").map(e=>encodeURIComponent(e)).join("/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"encodeURIPath",{enumerable:!0,get:function(){return r}})},8344:(e,t)=>{"use strict";function r(e,t){if(void 0===t&&(t={}),t.onlyHashChange){e();return}let r=document.documentElement,n=r.style.scrollBehavior;r.style.scrollBehavior="auto",t.dontForceLayout||r.getClientRects(),e(),r.style.scrollBehavior=n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return r}})},8397:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),(0,r(5194).patchConsoleError)(),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8455:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{prefetchQueue:function(){return a},prefetchReducer:function(){return u}});let n=r(7891),o=r(1893),a=new n.PromiseQueue(5),u=function(e,t){(0,o.prunePrefetchCache)(e.prefetchCache);let{url:r}=t;return(0,o.getOrCreatePrefetchCacheEntry)({url:r,nextUrl:e.nextUrl,prefetchCache:e.prefetchCache,kind:t.kind,tree:e.tree,allowAliasing:!0}),e};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8456:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return o},extractInterceptionRouteInformation:function(){return u},isInterceptionRouteAppPath:function(){return a}});let n=r(9259),o=["(..)(..)","(.)","(..)","(...)"];function a(e){return void 0!==e.split("/").find(e=>o.find(t=>e.startsWith(t)))}function u(e){let t,r,a;for(let n of e.split("/"))if(r=o.find(e=>n.startsWith(e))){[t,a]=e.split(r,2);break}if(!t||!r||!a)throw Object.defineProperty(Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`),"__NEXT_ERROR_CODE",{value:"E269",enumerable:!1,configurable:!0});switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":a="/"===t?`/${a}`:t+"/"+a;break;case"(..)":if("/"===t)throw Object.defineProperty(Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`),"__NEXT_ERROR_CODE",{value:"E207",enumerable:!1,configurable:!0});a=t.split("/").slice(0,-1).concat(a).join("/");break;case"(...)":a="/"+a;break;case"(..)(..)":let u=t.split("/");if(u.length<=2)throw Object.defineProperty(Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`),"__NEXT_ERROR_CODE",{value:"E486",enumerable:!1,configurable:!0});a=u.slice(0,-2).concat(a).join("/");break;default:throw Object.defineProperty(Error("Invariant: unexpected marker"),"__NEXT_ERROR_CODE",{value:"E112",enumerable:!1,configurable:!0})}return{interceptingRoute:t,interceptedRoute:a}}},8500:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldHardNavigate",{enumerable:!0,get:function(){return function e(t,r){let[a,u]=r,[l,i]=t;return(0,o.matchSegment)(l,a)?!(t.length<=2)&&e((0,n.getNextFlightSegmentPath)(t),u[i]):!!Array.isArray(l)}}});let n=r(1648),o=r(4682);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8514:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverActionReducer",{enumerable:!0,get:function(){return M}});let n=r(9603),o=r(3355),a=r(2836),u=r(4445),l=r(630),i=r(3436),c=r(2603),s=r(1053),f=r(6449),d=r(7344),p=r(223),h=r(3423),y=r(941),g=r(9786),_=r(1387),b=r(1648),m=r(9100),v=r(7563),E=r(1893),R=r(1129),O=r(6003),P=r(7173);r(3099);let{createFromFetch:S,createTemporaryReferenceSet:j,encodeReply:T}=r(4979);async function w(e,t,r){let u,i,{actionId:c,actionArgs:s}=r,f=j(),d=(0,P.extractInfoFromServerReferenceId)(c),p="use-cache"===d.type?(0,P.omitUnusedArgs)(s,d):s,h=await T(p,{temporaryReferences:f}),y=await fetch("",{method:"POST",headers:{Accept:a.RSC_CONTENT_TYPE_HEADER,[a.ACTION_HEADER]:c,[a.NEXT_ROUTER_STATE_TREE_HEADER]:encodeURIComponent(JSON.stringify(e.tree)),...t?{[a.NEXT_URL]:t}:{}},body:h}),g=y.headers.get("x-action-redirect"),[_,m]=(null==g?void 0:g.split(";"))||[];switch(m){case"push":u=v.RedirectType.push;break;case"replace":u=v.RedirectType.replace;break;default:u=void 0}let E=!!y.headers.get(a.NEXT_IS_PRERENDER_HEADER);try{let e=JSON.parse(y.headers.get("x-action-revalidated")||"[[],0,0]");i={paths:e[0]||[],tag:!!e[1],cookie:e[2]}}catch(e){i={paths:[],tag:!1,cookie:!1}}let R=_?(0,l.assignLocation)(_,new URL(e.canonicalUrl,window.location.href)):void 0,O=y.headers.get("content-type");if(null==O?void 0:O.startsWith(a.RSC_CONTENT_TYPE_HEADER)){let e=await S(Promise.resolve(y),{callServer:n.callServer,findSourceMapURL:o.findSourceMapURL,temporaryReferences:f});return _?{actionFlightData:(0,b.normalizeFlightData)(e.f),redirectLocation:R,redirectType:u,revalidatedParts:i,isPrerender:E}:{actionResult:e.a,actionFlightData:(0,b.normalizeFlightData)(e.f),redirectLocation:R,redirectType:u,revalidatedParts:i,isPrerender:E}}if(y.status>=400)throw Object.defineProperty(Error("text/plain"===O?await y.text():"An unexpected response was received from the server."),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return{redirectLocation:R,redirectType:u,revalidatedParts:i,isPrerender:E}}function M(e,t){let{resolve:r,reject:n}=t,o={},a=e.tree;o.preserveCustomHistoryState=!1;let l=e.nextUrl&&(0,y.hasInterceptionRouteInCurrentTree)(e.tree)?e.nextUrl:null;return w(e,l,t).then(async y=>{let b,{actionResult:P,actionFlightData:S,redirectLocation:j,redirectType:T,isPrerender:w,revalidatedParts:M}=y;if(j&&(T===v.RedirectType.replace?(e.pushRef.pendingPush=!1,o.pendingPush=!1):(e.pushRef.pendingPush=!0,o.pendingPush=!0),b=(0,i.createHrefFromUrl)(j,!1),o.canonicalUrl=b),!S)return(r(P),j)?(0,c.handleExternalUrl)(e,o,j.href,e.pushRef.pendingPush):e;if("string"==typeof S)return r(P),(0,c.handleExternalUrl)(e,o,S,e.pushRef.pendingPush);let x=M.paths.length>0||M.tag||M.cookie;for(let n of S){let{tree:u,seedData:i,head:d,isRootRender:y}=n;if(!y)return console.log("SERVER ACTION APPLY FAILED"),r(P),e;let m=(0,s.applyRouterStatePatchToTree)([""],a,u,b||e.canonicalUrl);if(null===m)return r(P),(0,g.handleSegmentMismatch)(e,t,u);if((0,f.isNavigatingToNewRootLayout)(a,m))return r(P),(0,c.handleExternalUrl)(e,o,b||e.canonicalUrl,e.pushRef.pendingPush);if(null!==i){let t=i[1],r=(0,h.createEmptyCacheNode)();r.rsc=t,r.prefetchRsc=null,r.loading=i[3],(0,p.fillLazyItemsTillLeafWithHead)(r,void 0,u,i,d,void 0),o.cache=r,o.prefetchCache=new Map,x&&await (0,_.refreshInactiveParallelSegments)({state:e,updatedTree:m,updatedCache:r,includeNextUrl:!!l,canonicalUrl:o.canonicalUrl||e.canonicalUrl})}o.patchedTree=m,a=m}return j&&b?(x||((0,E.createSeededPrefetchCacheEntry)({url:j,data:{flightData:S,canonicalUrl:void 0,couldBeIntercepted:!1,prerendered:!1,postponed:!1,staleTime:-1},tree:e.tree,prefetchCache:e.prefetchCache,nextUrl:e.nextUrl,kind:w?u.PrefetchKind.FULL:u.PrefetchKind.AUTO}),o.prefetchCache=e.prefetchCache),n((0,m.getRedirectError)((0,O.hasBasePath)(b)?(0,R.removeBasePath)(b):b,T||v.RedirectType.push))):r(P),(0,d.handleMutable)(e,o)},t=>(n(t),e))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8538:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"useServerInsertedMetadata",{enumerable:!0,get:function(){return a}});let n=r(2115),o=r(4565),a=e=>{let t=(0,n.useContext)(o.ServerInsertedMetadataContext);t&&t(e)}},8592:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PrefetchPriority:function(){return u},bumpPrefetchTask:function(){return p},cancelPrefetchTask:function(){return d},pingPrefetchTask:function(){return _},schedulePrefetchTask:function(){return f}});let n=r(4682),o=r(3099),a="function"==typeof queueMicrotask?queueMicrotask:e=>Promise.resolve().then(e).catch(e=>setTimeout(()=>{throw e}));var u=function(e){return e[e.Intent=2]="Intent",e[e.Default=1]="Default",e[e.Background=0]="Background",e}({});let l=[],i=0,c=0,s=!1;function f(e,t,r,n){let o={key:e,treeAtTimeOfPrefetch:t,priority:n,phase:1,hasBackgroundWork:!1,includeDynamicData:r,sortId:c++,isCanceled:!1,_heapIndex:-1};return P(l,o),h(),o}function d(e){e.isCanceled=!0,function(e,t){let r=t._heapIndex;if(-1!==r&&(t._heapIndex=-1,0!==e.length)){let n=e.pop();n!==t&&(e[r]=n,n._heapIndex=r,M(e,n,r))}}(l,e)}function p(e,t){e.isCanceled=!1,e.sortId=c++,e.priority=t,-1!==e._heapIndex?T(l,e):P(l,e),h()}function h(){!s&&i<3&&(s=!0,a(b))}function y(e){return i++,e.then(e=>null===e?(g(),null):(e.closed.then(g),e.value))}function g(){i--,h()}function _(e){!e.isCanceled&&-1===e._heapIndex&&(P(l,e),h())}function b(){s=!1;let e=Date.now(),t=S(l);for(;null!==t&&i<3;){let r=(0,o.readOrCreateRouteCacheEntry)(e,t),a=function(e,t,r){switch(r.status){case o.EntryStatus.Empty:y((0,o.fetchRouteOnCacheMiss)(r,t)),r.staleAt=e+6e4,r.status=o.EntryStatus.Pending;case o.EntryStatus.Pending:{let e=r.blockedTasks;return null===e?r.blockedTasks=new Set([t]):e.add(t),1}case o.EntryStatus.Rejected:break;case o.EntryStatus.Fulfilled:{if(0!==t.phase)return 2;if(!(i<3))return 0;let a=r.tree,u=t.includeDynamicData?o.FetchStrategy.Full:r.isPPREnabled?o.FetchStrategy.PPR:o.FetchStrategy.LoadingBoundary;switch(u){case o.FetchStrategy.PPR:return function e(t,r,n,a){let u=(0,o.readOrCreateSegmentCacheEntry)(t,n,a.key);if(function(e,t,r,n,a,u){switch(n.status){case o.EntryStatus.Empty:y((0,o.fetchSegmentOnCacheMiss)(r,(0,o.upgradeToPendingSegment)(n,o.FetchStrategy.PPR),a,u));break;case o.EntryStatus.Pending:switch(n.fetchStrategy){case o.FetchStrategy.PPR:case o.FetchStrategy.Full:break;case o.FetchStrategy.LoadingBoundary:(0===t.priority||(t.hasBackgroundWork=!0,0))&&m(e,n,r,a,u);break;default:n.fetchStrategy}break;case o.EntryStatus.Rejected:switch(n.fetchStrategy){case o.FetchStrategy.PPR:case o.FetchStrategy.Full:break;case o.FetchStrategy.LoadingBoundary:m(e,n,r,a,u);break;default:n.fetchStrategy}case o.EntryStatus.Fulfilled:}}(t,r,n,u,r.key,a.key),null!==a.slots){if(!(i<3))return 0;for(let o in a.slots)if(0===e(t,r,n,a.slots[o]))return 0}return 2}(e,t,r,a);case o.FetchStrategy.Full:case o.FetchStrategy.LoadingBoundary:{let l=new Map,i=function e(t,r,a,u,l,i){let c=a[1],s=u.slots,f={};if(null!==s)for(let a in s){let u=s[a],d=u.segment,p=c[a],h=null==p?void 0:p[0];if(void 0!==h&&(0,n.matchSegment)(d,h)){let n=e(t,r,p,u,l,i);f[a]=n}else switch(i){case o.FetchStrategy.LoadingBoundary:{let e=function e(t,r,n,a,u){let l=null===a?"inside-shared-layout":null,i=(0,o.readOrCreateSegmentCacheEntry)(t,r,n.key);switch(i.status){case o.EntryStatus.Empty:u.set(n.key,(0,o.upgradeToPendingSegment)(i,o.FetchStrategy.LoadingBoundary)),"refetch"!==a&&(l=a="refetch");break;case o.EntryStatus.Fulfilled:if(null!==i.loading)return(0,o.convertRouteTreeToFlightRouterState)(n);case o.EntryStatus.Pending:case o.EntryStatus.Rejected:}let c={};if(null!==n.slots)for(let o in n.slots){let l=n.slots[o];c[o]=e(t,r,l,a,u)}return[n.segment,c,null,l,n.isRootLayout]}(t,r,u,null,l);f[a]=e;break}case o.FetchStrategy.Full:{let e=function e(t,r,n,a,u){let l=(0,o.readOrCreateSegmentCacheEntry)(t,r,n.key),i=null;switch(l.status){case o.EntryStatus.Empty:i=(0,o.upgradeToPendingSegment)(l,o.FetchStrategy.Full);break;case o.EntryStatus.Fulfilled:l.isPartial&&(i=v(t,l,n.key));break;case o.EntryStatus.Pending:case o.EntryStatus.Rejected:l.fetchStrategy!==o.FetchStrategy.Full&&(i=v(t,l,n.key))}let c={};if(null!==n.slots)for(let o in n.slots){let l=n.slots[o];c[o]=e(t,r,l,a||null!==i,u)}null!==i&&u.set(n.key,i);let s=a||null===i?null:"refetch";return[n.segment,c,null,s,n.isRootLayout]}(t,r,u,!1,l);f[a]=e}}}return[u.segment,f,null,null,u.isRootLayout]}(e,r,t.treeAtTimeOfPrefetch,a,l,u);return l.size>0&&y((0,o.fetchSegmentPrefetchesUsingDynamicRequest)(t,r,u,i,l)),2}}}}return 2}(e,t,r),u=t.hasBackgroundWork;switch(t.hasBackgroundWork=!1,a){case 0:return;case 1:j(l),t=S(l);continue;case 2:1===t.phase?(t.phase=0,T(l,t)):u?(t.priority=0,T(l,t)):j(l),t=S(l);continue}}}function m(e,t,r,n,a){let u=(0,o.readOrCreateRevalidatingSegmentEntry)(e,t);switch(u.status){case o.EntryStatus.Empty:R(a,y((0,o.fetchSegmentOnCacheMiss)(r,(0,o.upgradeToPendingSegment)(u,o.FetchStrategy.PPR),n,a)));case o.EntryStatus.Pending:case o.EntryStatus.Fulfilled:case o.EntryStatus.Rejected:}}function v(e,t,r){let n=(0,o.readOrCreateRevalidatingSegmentEntry)(e,t);if(n.status===o.EntryStatus.Empty){let e=(0,o.upgradeToPendingSegment)(n,o.FetchStrategy.Full);return R(r,(0,o.waitForSegmentCacheEntry)(e)),e}if(n.fetchStrategy!==o.FetchStrategy.Full){let e=(0,o.resetRevalidatingSegmentEntry)(n),t=(0,o.upgradeToPendingSegment)(e,o.FetchStrategy.Full);return R(r,(0,o.waitForSegmentCacheEntry)(t)),t}switch(n.status){case o.EntryStatus.Pending:case o.EntryStatus.Fulfilled:case o.EntryStatus.Rejected:default:return null}}let E=()=>{};function R(e,t){t.then(t=>{null!==t&&(0,o.upsertSegmentEntry)(Date.now(),e,t)},E)}function O(e,t){let r=t.priority-e.priority;if(0!==r)return r;let n=t.phase-e.phase;return 0!==n?n:t.sortId-e.sortId}function P(e,t){let r=e.length;e.push(t),t._heapIndex=r,w(e,t,r)}function S(e){return 0===e.length?null:e[0]}function j(e){if(0===e.length)return null;let t=e[0];t._heapIndex=-1;let r=e.pop();return r!==t&&(e[0]=r,r._heapIndex=0,M(e,r,0)),t}function T(e,t){let r=t._heapIndex;-1!==r&&(0===r?M(e,t,0):O(e[r-1>>>1],t)>0?w(e,t,r):M(e,t,r))}function w(e,t,r){let n=r;for(;n>0;){let r=n-1>>>1,o=e[r];if(!(O(o,t)>0))return;e[r]=t,t._heapIndex=r,e[n]=o,o._heapIndex=n,n=r}}function M(e,t,r){let n=r,o=e.length,a=o>>>1;for(;nO(a,t))uO(l,a)?(e[n]=l,l._heapIndex=n,e[u]=t,t._heapIndex=u,n=u):(e[n]=a,a._heapIndex=n,e[r]=t,t._heapIndex=r,n=r);else{if(!(uO(l,t)))return;e[n]=l,l._heapIndex=n,e[u]=t,t._heapIndex=u,n=u}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8645:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{fillCacheWithNewSubTreeData:function(){return i},fillCacheWithNewSubTreeDataButOnlyLoading:function(){return c}});let n=r(7663),o=r(223),a=r(5404),u=r(6090);function l(e,t,r,l,i){let{segmentPath:c,seedData:s,tree:f,head:d}=r,p=e,h=t;for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PathParamsContext:function(){return u},PathnameContext:function(){return a},SearchParamsContext:function(){return o}});let n=r(2115),o=(0,n.createContext)(null),a=(0,n.createContext)(null),u=(0,n.createContext)(null)},8730:(e,t,r)=>{"use strict";var n=r(2115);function o(e){var t="https://react.dev/errors/"+e;if(1{"use strict";function n(){throw Object.defineProperty(Error("`forbidden()` is experimental and only allowed to be enabled when `experimental.authInterrupts` is enabled."),"__NEXT_ERROR_CODE",{value:"E488",enumerable:!1,configurable:!0})}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"forbidden",{enumerable:!0,get:function(){return n}}),r(2469).HTTP_ERROR_FALLBACK_ERROR_CODE,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8912:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return o}});let n=r(4046);function o(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,n.parsePath)(e);return r===t||r.startsWith(t+"/")}},8967:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"bailoutToClientRendering",{enumerable:!0,get:function(){return a}});let n=r(3719),o=r(5861);function a(e){let t=o.workAsyncStorage.getStore();if((null==t||!t.forceStatic)&&(null==t?void 0:t.isStaticGeneration))throw Object.defineProperty(new n.BailoutToCSRError(e),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9003:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),(0,r(5597).handleGlobalErrors)(),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9062:(e,t,r)=>{"use strict";var n=r(7650),o={stream:!0},a=new Map;function u(e){var t=r(e);return"function"!=typeof t.then||"fulfilled"===t.status?null:(t.then(function(e){t.status="fulfilled",t.value=e},function(e){t.status="rejected",t.reason=e}),t)}function l(){}function i(e){for(var t=e[1],n=[],o=0;oc||35===c||114===c||120===c?(s=c,c=3,l++):(s=0,c=3);continue;case 2:44===(y=u[l++])?c=4:f=f<<4|(96u.length&&(y=-1)}var g=u.byteOffset+l;if(-1{"use strict";function r(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return r}})},9100:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getRedirectError:function(){return u},getRedirectStatusCodeFromError:function(){return f},getRedirectTypeFromError:function(){return s},getURLFromRedirectError:function(){return c},permanentRedirect:function(){return i},redirect:function(){return l}});let n=r(9126),o=r(7361),a=r(7563);function u(e,t,r){void 0===r&&(r=o.RedirectStatusCode.TemporaryRedirect);let n=Object.defineProperty(Error(a.REDIRECT_ERROR_CODE),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return n.digest=a.REDIRECT_ERROR_CODE+";"+t+";"+e+";"+r+";",n}function l(e,t){let r=n.actionAsyncStorage.getStore();throw u(e,t||((null==r?void 0:r.isAction)?a.RedirectType.push:a.RedirectType.replace),o.RedirectStatusCode.TemporaryRedirect)}function i(e,t){throw void 0===t&&(t=a.RedirectType.replace),u(e,t,o.RedirectStatusCode.PermanentRedirect)}function c(e){return(0,a.isRedirectError)(e)?e.digest.split(";").slice(2,-2).join(";"):null}function s(e){if(!(0,a.isRedirectError)(e))throw Object.defineProperty(Error("Not a redirect error"),"__NEXT_ERROR_CODE",{value:"E260",enumerable:!1,configurable:!0});return e.digest.split(";",2)[1]}function f(e){if(!(0,a.isRedirectError)(e))throw Object.defineProperty(Error("Not a redirect error"),"__NEXT_ERROR_CODE",{value:"E260",enumerable:!1,configurable:!0});return Number(e.digest.split(";").at(-2))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9126:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"actionAsyncStorage",{enumerable:!0,get:function(){return n.actionAsyncStorageInstance}});let n=r(2075)},9259:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return a},normalizeRscURL:function(){return u}});let n=r(9066),o=r(6090);function a(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,o.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function u(e){return e.replace(/\.rsc($|\?)/,"$1")}},9321:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"unresolvedThenable",{enumerable:!0,get:function(){return r}});let r={then:()=>{}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9377:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return o}});let n=r(4046);function o(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:a}=(0,n.parsePath)(e);return""+t+r+o+a}},9423:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{copyNextErrorCode:function(){return n},createDigestWithErrorCode:function(){return r},extractNextErrorCode:function(){return o}});let r=(e,t)=>"object"==typeof e&&null!==e&&"__NEXT_ERROR_CODE"in e?`${t}@${e.__NEXT_ERROR_CODE}`:t,n=(e,t)=>{let r=o(e);r&&"object"==typeof t&&null!==t&&Object.defineProperty(t,"__NEXT_ERROR_CODE",{value:r,enumerable:!1,configurable:!0})},o=e=>"object"==typeof e&&null!==e&&"__NEXT_ERROR_CODE"in e&&"string"==typeof e.__NEXT_ERROR_CODE?e.__NEXT_ERROR_CODE:"object"==typeof e&&null!==e&&"digest"in e&&"string"==typeof e.digest?e.digest.split("@").find(e=>e.startsWith("E")):void 0},9544:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return a}});let n=r(9377),o=r(6573);function a(e,t){return(0,o.normalizePathTrailingSlash)((0,n.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9603:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{callServer:function(){return l},useServerActionDispatcher:function(){return u}});let n=r(2115),o=r(4445),a=null;function u(e){a=(0,n.useCallback)(t=>{(0,n.startTransition)(()=>{e({...t,type:o.ACTION_SERVER_ACTION})})},[e])}async function l(e,t){let r=a;if(!r)throw Object.defineProperty(Error("Invariant: missing action dispatcher."),"__NEXT_ERROR_CODE",{value:"E507",enumerable:!1,configurable:!0});return new Promise((n,o)=>{r({actionId:e,actionArgs:t,resolve:n,reject:o})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9762:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return o},getProperError:function(){return a}});let n=r(9844);function o(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function a(e){return o(e)?e:Object.defineProperty(Error((0,n.isPlainObject)(e)?function(e){let t=new WeakSet;return JSON.stringify(e,(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r})}(e):e+""),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}},9786:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSegmentMismatch",{enumerable:!0,get:function(){return o}});let n=r(2603);function o(e,t,r){return(0,n.handleExternalUrl)(e,{},e.canonicalUrl,!0)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9824:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prefetch",{enumerable:!0,get:function(){return u}});let n=r(3423),o=r(2633),a=r(8592);function u(e,t,r,u){let l=(0,n.createPrefetchURL)(e);if(null===l)return;let i=(0,o.createCacheKey)(l.href,t);(0,a.schedulePrefetchTask)(i,r,u,a.PrefetchPriority.Default)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9844:(e,t)=>{"use strict";function r(e){return Object.prototype.toString.call(e)}function n(e){if("[object Object]"!==r(e))return!1;let t=Object.getPrototypeOf(e);return null===t||t.hasOwnProperty("isPrototypeOf")}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getObjectClassLabel:function(){return r},isPlainObject:function(){return n}})},9935:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleHardNavError:function(){return o},useNavFailureHandler:function(){return a}}),r(2115);let n=r(3436);function o(e){return!!e&&"undefined"!=typeof window&&!!window.next.__pendingUrl&&(0,n.createHrefFromUrl)(new URL(window.location.href))!==(0,n.createHrefFromUrl)(window.next.__pendingUrl)&&(console.error("Error occurred during navigation, falling back to hard navigation",e),window.location.href=window.next.__pendingUrl.toString(),!0)}function a(){}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9955:(e,t,r)=>{"use strict";function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function o(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var o={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&Object.prototype.hasOwnProperty.call(e,u)){var l=a?Object.getOwnPropertyDescriptor(e,u):null;l&&(l.get||l.set)?Object.defineProperty(o,u,l):o[u]=e[u]}return o.default=e,r&&r.set(e,o),o}r.r(t),r.d(t,{_:()=>o})}}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/821-f382ea5118c8252b.js b/services/v1/media/feedback/static/_next/static/chunks/821-f382ea5118c8252b.js new file mode 100644 index 0000000000000000000000000000000000000000..935ecd2c50a16ed76fff137ec844469c935a1497 --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/821-f382ea5118c8252b.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[821],{364:(e,t,r)=>{var n=r(8202),i=e.exports={WebVTT:r(7219),VTTCue:r(5666),VTTRegion:r(379)};n.vttjs=i,n.WebVTT=i.WebVTT;var a=i.VTTCue,o=i.VTTRegion,s=n.VTTCue,u=n.VTTRegion;i.shim=function(){n.VTTCue=a,n.VTTRegion=o},i.restore=function(){n.VTTCue=s,n.VTTRegion=u},n.VTTCue||i.shim()},379:e=>{var t={"":!0,up:!0};function r(e){return"number"==typeof e&&e>=0&&e<=100}e.exports=function(){var e=100,n=3,i=0,a=100,o=0,s=100,u="";Object.defineProperties(this,{width:{enumerable:!0,get:function(){return e},set:function(t){if(!r(t))throw Error("Width must be between 0 and 100.");e=t}},lines:{enumerable:!0,get:function(){return n},set:function(e){if("number"!=typeof e)throw TypeError("Lines must be set to a number.");n=e}},regionAnchorY:{enumerable:!0,get:function(){return a},set:function(e){if(!r(e))throw Error("RegionAnchorX must be between 0 and 100.");a=e}},regionAnchorX:{enumerable:!0,get:function(){return i},set:function(e){if(!r(e))throw Error("RegionAnchorY must be between 0 and 100.");i=e}},viewportAnchorY:{enumerable:!0,get:function(){return s},set:function(e){if(!r(e))throw Error("ViewportAnchorY must be between 0 and 100.");s=e}},viewportAnchorX:{enumerable:!0,get:function(){return o},set:function(e){if(!r(e))throw Error("ViewportAnchorX must be between 0 and 100.");o=e}},scroll:{enumerable:!0,get:function(){return u},set:function(e){var r="string"==typeof e&&!!t[e.toLowerCase()]&&e.toLowerCase();!1===r?console.warn("Scroll: an invalid or illegal string was specified."):u=r}}})}},400:e=>{"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(i);!(n=a()).done;){var o=n.value;try{r=o(r)}catch(e){}}return r},e}();e.exports=r},559:(e,t,r)=>{"use strict";r.d(t,{Tt:()=>S,Ze:()=>M,qg:()=>eO,i6:()=>ex});var n=r(9512),i=r(8202),a=r.n(i),o=function(e,t,r){t.forEach(function(t){for(var n in e.mediaGroups[t])for(var i in e.mediaGroups[t][n])r(e.mediaGroups[t][n][i],t,n,i)})},s=r(9410),u=r(6002);let l=e=>!!e&&"object"==typeof e,c=(...e)=>e.reduce((e,t)=>("object"!=typeof t||Object.keys(t).forEach(r=>{Array.isArray(e[r])&&Array.isArray(t[r])?e[r]=e[r].concat(t[r]):l(e[r])&&l(t[r])?e[r]=c(e[r],t[r]):e[r]=t[r]}),e),{}),f=e=>Object.keys(e).map(t=>e[t]),p=(e,t)=>{let r=[];for(let n=e;ne.reduce((e,t)=>e.concat(t),[]),d=e=>{if(!e.length)return[];let t=[];for(let r=0;re.reduce((e,r,n)=>(r[t]&&e.push(n),e),[]),m=(e,t)=>f(e.reduce((e,r)=>(r.forEach(r=>{e[t(r)]=r}),e),{}));var b={INVALID_NUMBER_OF_PERIOD:"INVALID_NUMBER_OF_PERIOD",DASH_EMPTY_MANIFEST:"DASH_EMPTY_MANIFEST",DASH_INVALID_XML:"DASH_INVALID_XML",NO_BASE_URL:"NO_BASE_URL",SEGMENT_TIME_UNSPECIFIED:"SEGMENT_TIME_UNSPECIFIED",UNSUPPORTED_UTC_TIMING_SCHEME:"UNSUPPORTED_UTC_TIMING_SCHEME"};let y=({baseUrl:e="",source:t="",range:r="",indexRange:i=""})=>{let o={uri:t,resolvedUri:(0,n.A)(e||"",t)};if(r||i){let e;let t=(r||i).split("-"),n=a().BigInt?a().BigInt(t[0]):parseInt(t[0],10),s=a().BigInt?a().BigInt(t[1]):parseInt(t[1],10);n{let t;return t="bigint"==typeof e.offset||"bigint"==typeof e.length?a().BigInt(e.offset)+a().BigInt(e.length)-a().BigInt(1):e.offset+e.length-1,`${e.offset}-${t}`},v=e=>(e&&"number"!=typeof e&&(e=parseInt(e,10)),isNaN(e))?null:e,T={static(e){let{duration:t,timescale:r=1,sourceDuration:n,periodDuration:i}=e,a=v(e.endNumber),o=t/r;return"number"==typeof a?{start:0,end:a}:"number"==typeof i?{start:0,end:i/o}:{start:0,end:n/o}},dynamic(e){let{NOW:t,clientOffset:r,availabilityStartTime:n,timescale:i=1,duration:a,periodStart:o=0,minimumUpdatePeriod:s=0,timeShiftBufferDepth:u=1/0}=e,l=v(e.endNumber),c=(t+r)/1e3,f=n+o,p=Math.ceil((c+s-f)*i/a),h=Math.floor((c-f-u)*i/a),d=Math.floor((c-f)*i/a);return{start:Math.max(0,h),end:"number"==typeof l?l:Math.min(p,d)}}},w=e=>t=>{let{duration:r,timescale:n=1,periodStart:i,startNumber:a=1}=e;return{number:a+t,duration:r/n,timeline:i,time:t*r}},D=e=>{let{type:t,duration:r,timescale:n=1,periodDuration:i,sourceDuration:a}=e,{start:o,end:s}=T[t](e),u=p(o,s).map(w(e));if("static"===t){let e=u.length-1;u[e].duration=("number"==typeof i?i:a)-r/n*e}return u},A=e=>{let{baseUrl:t,initialization:r={},sourceDuration:n,indexRange:i="",periodStart:a,presentationTime:o,number:s=0,duration:u}=e;if(!t)throw Error(b.NO_BASE_URL);let l=y({baseUrl:t,source:r.sourceURL,range:r.range}),c=y({baseUrl:t,source:t,indexRange:i});if(c.map=l,u){let t=D(e);t.length&&(c.duration=t[0].duration,c.timeline=t[0].timeline)}else n&&(c.duration=n,c.timeline=a);return c.presentationTime=o||a,c.number=s,[c]},S=(e,t,r)=>{let n;let i=e.sidx.map?e.sidx.map:null,o=e.sidx.duration,s=e.timeline||0,u=e.sidx.byterange,l=u.offset+u.length,c=t.timescale,f=t.references.filter(e=>1!==e.referenceType),p=[],h=e.endList?"static":"dynamic",d=e.sidx.timeline,g=d,m=e.mediaSequence||0;n="bigint"==typeof t.firstOffset?a().BigInt(l)+t.firstOffset:l+t.firstOffset;for(let e=0;em(e,({timeline:e})=>e).sort((e,t)=>e.timeline>t.timeline?1:-1),x=(e,t)=>{for(let r=0;r{let t=[];return o(e,N,(e,r,n,i)=>{t=t.concat(e.playlists||[])}),t},C=({playlist:e,mediaSequence:t})=>{e.mediaSequence=t,e.segments.forEach((t,r)=>{t.number=e.mediaSequence+r})},L=({oldPlaylists:e,newPlaylists:t,timelineStarts:r})=>{t.forEach(t=>{t.discontinuitySequence=r.findIndex(function({timeline:e}){return e===t.timeline});let n=x(e,t.attributes.NAME);if(!n||t.sidx)return;let i=t.segments[0],a=n.segments.findIndex(function(e){return Math.abs(e.presentationTime-i.presentationTime)n.timeline||n.segments.length&&t.timeline>n.segments[n.segments.length-1].timeline)&&t.discontinuitySequence--;return}n.segments[a].discontinuity&&!i.discontinuity&&(i.discontinuity=!0,t.discontinuityStarts.unshift(0),t.discontinuitySequence--),C({playlist:t,mediaSequence:n.segments[a].number})})},U=({oldManifest:e,newManifest:t})=>{let r=e.playlists.concat(I(e)),n=t.playlists.concat(I(t));return t.timelineStarts=O([e.timelineStarts,t.timelineStarts]),L({oldPlaylists:r,newPlaylists:n,timelineStarts:t.timelineStarts}),t},M=e=>e&&e.uri+"-"+E(e.byterange),_=e=>{let t=e.reduce(function(e,t){return e[t.attributes.baseUrl]||(e[t.attributes.baseUrl]=[]),e[t.attributes.baseUrl].push(t),e},{}),r=[];return Object.values(t).forEach(e=>{let t=f(e.reduce((e,t)=>{let r=t.attributes.id+(t.attributes.lang||"");return e[r]?(t.segments&&(t.segments[0]&&(t.segments[0].discontinuity=!0),e[r].segments.push(...t.segments)),t.attributes.contentProtection&&(e[r].attributes.contentProtection=t.attributes.contentProtection)):(e[r]=t,e[r].attributes.timelineStarts=[]),e[r].attributes.timelineStarts.push({start:t.attributes.periodStart,timeline:t.attributes.periodStart}),e},{}));r=r.concat(t)}),r.map(e=>(e.discontinuityStarts=g(e.segments||[],"discontinuity"),e))},P=(e,t)=>{let r=M(e.sidx),n=r&&t[r]&&t[r].sidx;return n&&S(e,n,e.sidx.resolvedUri),e},B=(e,t={})=>{if(!Object.keys(t).length)return e;for(let r in e)e[r]=P(e[r],t);return e},q=({attributes:e,segments:t,sidx:r,mediaSequence:n,discontinuitySequence:i,discontinuityStarts:a},o)=>{let s={attributes:{NAME:e.id,BANDWIDTH:e.bandwidth,CODECS:e.codecs,"PROGRAM-ID":1},uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:e.baseUrl||"",targetDuration:e.duration,discontinuitySequence:i,discontinuityStarts:a,timelineStarts:e.timelineStarts,mediaSequence:n,segments:t};return e.contentProtection&&(s.contentProtection=e.contentProtection),e.serviceLocation&&(s.attributes.serviceLocation=e.serviceLocation),r&&(s.sidx=r),o&&(s.attributes.AUDIO="audio",s.attributes.SUBTITLES="subs"),s},k=({attributes:e,segments:t,mediaSequence:r,discontinuityStarts:n,discontinuitySequence:i})=>{void 0===t&&(t=[{uri:e.baseUrl,timeline:e.periodStart,resolvedUri:e.baseUrl||"",duration:e.sourceDuration,number:0}],e.duration=e.sourceDuration);let a={NAME:e.id,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1};e.codecs&&(a.CODECS=e.codecs);let o={attributes:a,uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:e.baseUrl||"",targetDuration:e.duration,timelineStarts:e.timelineStarts,discontinuityStarts:n,discontinuitySequence:i,mediaSequence:r,segments:t};return e.serviceLocation&&(o.attributes.serviceLocation=e.serviceLocation),o},F=(e,t={},r=!1)=>{let n;let i=e.reduce((e,i)=>{let a=i.attributes.role&&i.attributes.role.value||"",o=i.attributes.lang||"",s=i.attributes.label||"main";if(o&&!i.attributes.label){let e=a?` (${a})`:"";s=`${i.attributes.lang}${e}`}e[s]||(e[s]={language:o,autoselect:!0,default:"main"===a,playlists:[],uri:""});let u=P(q(i,r),t);return e[s].playlists.push(u),void 0===n&&"main"===a&&((n=i).default=!0),e},{});if(!n){let e=Object.keys(i)[0];i[e].default=!0}return i},X=(e,t={})=>e.reduce((e,r)=>{let n=r.attributes.label||r.attributes.lang||"text",i=r.attributes.lang||"und";return e[n]||(e[n]={language:i,default:!1,autoselect:!1,playlists:[],uri:""}),e[n].playlists.push(P(k(r),t)),e},{}),j=e=>e.reduce((e,t)=>(t&&t.forEach(t=>{let{channel:r,language:n}=t;e[n]={autoselect:!1,default:!1,instreamId:r,language:n},t.hasOwnProperty("aspectRatio")&&(e[n].aspectRatio=t.aspectRatio),t.hasOwnProperty("easyReader")&&(e[n].easyReader=t.easyReader),t.hasOwnProperty("3D")&&(e[n]["3D"]=t["3D"])}),e),{}),V=({attributes:e,segments:t,sidx:r,discontinuityStarts:n})=>{let i={attributes:{NAME:e.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:e.width,height:e.height},CODECS:e.codecs,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1},uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:e.baseUrl||"",targetDuration:e.duration,discontinuityStarts:n,timelineStarts:e.timelineStarts,segments:t};return e.frameRate&&(i.attributes["FRAME-RATE"]=e.frameRate),e.contentProtection&&(i.contentProtection=e.contentProtection),e.serviceLocation&&(i.attributes.serviceLocation=e.serviceLocation),r&&(i.sidx=r),i},H=({attributes:e})=>"video/mp4"===e.mimeType||"video/webm"===e.mimeType||"video"===e.contentType,G=({attributes:e})=>"audio/mp4"===e.mimeType||"audio/webm"===e.mimeType||"audio"===e.contentType,z=({attributes:e})=>"text/vtt"===e.mimeType||"text"===e.contentType,$=(e,t)=>{e.forEach(e=>{e.mediaSequence=0,e.discontinuitySequence=t.findIndex(function({timeline:t}){return t===e.timeline}),e.segments&&e.segments.forEach((e,t)=>{e.number=t})})},W=e=>e?Object.keys(e).reduce((t,r)=>{let n=e[r];return t.concat(n.playlists)},[]):[],Y=({dashPlaylists:e,locations:t,contentSteering:r,sidxMapping:n={},previousManifest:i,eventStream:a})=>{if(!e.length)return{};let{sourceDuration:o,type:s,suggestedPresentationDelay:u,minimumUpdatePeriod:l}=e[0].attributes,c=_(e.filter(H)).map(V),f=_(e.filter(G)),p=_(e.filter(z)),h=e.map(e=>e.attributes.captionServices).filter(Boolean),d={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:o,playlists:B(c,n)};l>=0&&(d.minimumUpdatePeriod=1e3*l),t&&(d.locations=t),r&&(d.contentSteering=r),"dynamic"===s&&(d.suggestedPresentationDelay=u),a&&a.length>0&&(d.eventStream=a);let g=0===d.playlists.length,m=f.length?F(f,n,g):null,b=p.length?X(p,n):null,y=c.concat(W(m),W(b)),E=y.map(({timelineStarts:e})=>e);return(d.timelineStarts=O(E),$(y,d.timelineStarts),m&&(d.mediaGroups.AUDIO.audio=m),b&&(d.mediaGroups.SUBTITLES.subs=b),h.length&&(d.mediaGroups["CLOSED-CAPTIONS"].cc=j(h)),i)?U({oldManifest:i,newManifest:d}):d},K=(e,t,r)=>{let{NOW:n,clientOffset:i,availabilityStartTime:a,timescale:o=1,periodStart:s=0,minimumUpdatePeriod:u=0}=e;return Math.ceil((((n+i)/1e3+u-(a+s))*o-t)/r)},J=(e,t)=>{let{type:r,minimumUpdatePeriod:n=0,media:i="",sourceDuration:a,timescale:o=1,startNumber:s=1,periodStart:u}=e,l=[],c=-1;for(let f=0;fc&&(c=m),g<0){let s=f+1;p=s===t.length?"dynamic"===r&&n>0&&i.indexOf("$Number$")>0?K(e,c,d):(a*o-c)/d:(t[s].t-c)/d}else p=g+1;let b=s+l.length+p,y=s+l.length;for(;y(t,r,n,i)=>{if("$$"===t)return"$";if(void 0===e[r])return t;let a=""+e[r];return"RepresentationID"===r?a:(i=n?parseInt(i,10):1,a.length>=i)?a:`${Array(i-a.length+1).join("0")}${a}`},ee=(e,t)=>e.replace(Z,Q(t)),et=(e,t)=>e.duration||t?e.duration?D(e):J(e,t):[{number:e.startNumber||1,duration:e.sourceDuration,time:0,timeline:e.periodStart}],er=(e,t)=>{let r={RepresentationID:e.id,Bandwidth:e.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=e,a=y({baseUrl:e.baseUrl,source:ee(i.sourceURL,r),range:i.range});return et(e,t).map(t=>{r.Number=t.number,r.Time=t.time;let i=ee(e.media||"",r),o=e.timescale||1,s=e.presentationTimeOffset||0,u=e.periodStart+(t.time-s)/o;return{uri:i,timeline:t.timeline,duration:t.duration,resolvedUri:(0,n.A)(e.baseUrl||"",i),map:a,number:t.number,presentationTime:u}})},en=(e,t)=>{let{baseUrl:r,initialization:n={}}=e,i=y({baseUrl:r,source:n.sourceURL,range:n.range}),a=y({baseUrl:r,source:t.media,range:t.mediaRange});return a.map=i,a},ei=(e,t)=>{let r;let{duration:n,segmentUrls:i=[],periodStart:a}=e;if(!n&&!t||n&&t)throw Error(b.SEGMENT_TIME_UNSPECIFIED);let o=i.map(t=>en(e,t));return n&&(r=D(e)),t&&(r=J(e,t)),r.map((t,r)=>{if(o[r]){let n=o[r],i=e.timescale||1,s=e.presentationTimeOffset||0;return n.timeline=t.timeline,n.duration=t.duration,n.number=t.number,n.presentationTime=a+(t.time-s)/i,n}}).filter(e=>e)},ea=({attributes:e,segmentInfo:t})=>{let r,n;t.template?(n=er,r=c(e,t.template)):t.base?(n=A,r=c(e,t.base)):t.list&&(n=ei,r=c(e,t.list));let i={attributes:e};if(!n)return i;let a=n(r,t.segmentTimeline);if(r.duration){let{duration:e,timescale:t=1}=r;r.duration=e/t}else a.length?r.duration=a.reduce((e,t)=>Math.max(e,Math.ceil(t.duration)),0):r.duration=0;return i.attributes=r,i.segments=a,t.base&&r.indexRange&&(i.sidx=a[0],i.segments=[]),i},eo=e=>e.map(ea),es=(e,t)=>d(e.childNodes).filter(({tagName:e})=>e===t),eu=e=>e.textContent.trim(),el=e=>parseFloat(e.split("/").reduce((e,t)=>e/t)),ec=e=>{let t=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(e);if(!t)return 0;let[r,n,i,a,o,s]=t.slice(1);return 31536e3*parseFloat(r||0)+2592e3*parseFloat(n||0)+86400*parseFloat(i||0)+3600*parseFloat(a||0)+60*parseFloat(o||0)+parseFloat(s||0)},ef=e=>(/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(e)&&(e+="Z"),Date.parse(e)),ep={mediaPresentationDuration:e=>ec(e),availabilityStartTime:e=>ef(e)/1e3,minimumUpdatePeriod:e=>ec(e),suggestedPresentationDelay:e=>ec(e),type:e=>e,timeShiftBufferDepth:e=>ec(e),start:e=>ec(e),width:e=>parseInt(e,10),height:e=>parseInt(e,10),bandwidth:e=>parseInt(e,10),frameRate:e=>el(e),startNumber:e=>parseInt(e,10),timescale:e=>parseInt(e,10),presentationTimeOffset:e=>parseInt(e,10),duration(e){let t=parseInt(e,10);return isNaN(t)?ec(e):t},d:e=>parseInt(e,10),t:e=>parseInt(e,10),r:e=>parseInt(e,10),presentationTime:e=>parseInt(e,10),DEFAULT:e=>e},eh=e=>e&&e.attributes?d(e.attributes).reduce((e,t)=>{let r=ep[t.name]||ep.DEFAULT;return e[t.name]=r(t.value),e},{}):{},ed={"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime","urn:mpeg:dash:mp4protection:2011":"mp4protection"},eg=(e,t)=>t.length?h(e.map(function(e){return t.map(function(t){let r=eu(t),i=(0,n.A)(e.baseUrl,r),a=c(eh(t),{baseUrl:i});return i!==r&&!a.serviceLocation&&e.serviceLocation&&(a.serviceLocation=e.serviceLocation),a})})):e,em=e=>{let t=es(e,"SegmentTemplate")[0],r=es(e,"SegmentList")[0],n=r&&es(r,"SegmentURL").map(e=>c({tag:"SegmentURL"},eh(e))),i=es(e,"SegmentBase")[0],a=r||t,o=a&&es(a,"SegmentTimeline")[0],s=r||i||t,u=s&&es(s,"Initialization")[0],l=t&&eh(t);l&&u?l.initialization=u&&eh(u):l&&l.initialization&&(l.initialization={sourceURL:l.initialization});let f={template:l,segmentTimeline:o&&es(o,"S").map(e=>eh(e)),list:r&&c(eh(r),{segmentUrls:n,initialization:eh(u)}),base:i&&c(eh(i),{initialization:eh(u)})};return Object.keys(f).forEach(e=>{f[e]||delete f[e]}),f},eb=(e,t,r)=>n=>{let i=eg(t,es(n,"BaseURL")),a=c(e,eh(n)),o=em(n);return i.map(e=>({segmentInfo:c(r,o),attributes:c(a,e)}))},ey=e=>e.reduce((e,t)=>{let r=eh(t);r.schemeIdUri&&(r.schemeIdUri=r.schemeIdUri.toLowerCase());let n=ed[r.schemeIdUri];if(n){e[n]={attributes:r};let i=es(t,"cenc:pssh")[0];if(i){let t=eu(i);e[n].pssh=t&&(0,s.A)(t)}}return e},{}),eE=e=>"urn:scte:dash:cc:cea-608:2015"===e.schemeIdUri?("string"!=typeof e.value?[]:e.value.split(";")).map(e=>{let t,r;return r=e,/^CC\d=/.test(e)?[t,r]=e.split("="):/^CC\d$/.test(e)&&(t=e),{channel:t,language:r}}):"urn:scte:dash:cc:cea-708:2015"===e.schemeIdUri?("string"!=typeof e.value?[]:e.value.split(";")).map(e=>{let t={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(e)){let[r,n=""]=e.split("=");t.channel=r,t.language=e,n.split(",").forEach(e=>{let[r,n]=e.split(":");"lang"===r?t.language=n:"er"===r?t.easyReader=Number(n):"war"===r?t.aspectRatio=Number(n):"3D"===r&&(t["3D"]=Number(n))})}else t.language=e;return t.channel&&(t.channel="SERVICE"+t.channel),t}):void 0,ev=e=>h(es(e.node,"EventStream").map(t=>{let r=eh(t),n=r.schemeIdUri;return es(t,"Event").map(t=>{let i=eh(t),a=i.presentationTime||0,o=r.timescale||1,s=i.duration||0,u=a/o+e.attributes.start;return{schemeIdUri:n,value:r.value,id:i.id,start:u,end:u+s/o,messageData:eu(t)||i.messageData,contentEncoding:r.contentEncoding,presentationTimeOffset:r.presentationTimeOffset||0}})})),eT=(e,t,r)=>n=>{let i=eh(n),a=eg(t,es(n,"BaseURL")),o=c(e,i,{role:eh(es(n,"Role")[0])}),s=eE(eh(es(n,"Accessibility")[0]));s&&(o=c(o,{captionServices:s}));let u=es(n,"Label")[0];u&&u.childNodes.length&&(o=c(o,{label:u.childNodes[0].nodeValue.trim()}));let l=ey(es(n,"ContentProtection"));Object.keys(l).length&&(o=c(o,{contentProtection:l}));let f=em(n),p=es(n,"Representation"),d=c(r,f);return h(p.map(eb(o,a,d)))},ew=(e,t)=>(r,n)=>{let i=eg(t,es(r.node,"BaseURL")),a=c(e,{periodStart:r.attributes.start});"number"==typeof r.attributes.duration&&(a.periodDuration=r.attributes.duration);let o=es(r.node,"AdaptationSet"),s=em(r.node);return h(o.map(eT(a,i,s)))},eD=(e,t)=>{if(e.length>1&&t({type:"warn",message:"The MPD manifest should contain no more than one ContentSteering tag"}),!e.length)return null;let r=c({serverURL:eu(e[0])},eh(e[0]));return r.queryBeforeStart="true"===r.queryBeforeStart,r},eA=({attributes:e,priorPeriodAttributes:t,mpdType:r})=>"number"==typeof e.start?e.start:t&&"number"==typeof t.start&&"number"==typeof t.duration?t.start+t.duration:t||"static"!==r?null:0,eS=(e,t={})=>{let{manifestUri:r="",NOW:n=Date.now(),clientOffset:i=0,eventHandler:a=function(){}}=t,o=es(e,"Period");if(!o.length)throw Error(b.INVALID_NUMBER_OF_PERIOD);let s=es(e,"Location"),u=eh(e),l=eg([{baseUrl:r}],es(e,"BaseURL")),c=es(e,"ContentSteering");u.type=u.type||"static",u.sourceDuration=u.mediaPresentationDuration||0,u.NOW=n,u.clientOffset=i,s.length&&(u.locations=s.map(eu));let f=[];return o.forEach((e,t)=>{let r=eh(e),n=f[t-1];r.start=eA({attributes:r,priorPeriodAttributes:n?n.attributes:null,mpdType:u.type}),f.push({node:e,attributes:r})}),{locations:u.locations,contentSteeringInfo:eD(c,a),representationInfo:h(f.map(ew(u,l))),eventStream:h(f.map(ev))}},eN=e=>{let t,r;if(""===e)throw Error(b.DASH_EMPTY_MANIFEST);let n=new u.DOMParser;try{r=(t=n.parseFromString(e,"application/xml"))&&"MPD"===t.documentElement.tagName?t.documentElement:null}catch(e){}if(!r||r&&r.getElementsByTagName("parsererror").length>0)throw Error(b.DASH_INVALID_XML);return r},eR=e=>{let t=es(e,"UTCTiming")[0];if(!t)return null;let r=eh(t);switch(r.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":r.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":r.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":r.method="DIRECT",r.value=Date.parse(r.value);break;default:throw Error(b.UNSUPPORTED_UTC_TIMING_SCHEME)}return r},eO=(e,t={})=>{let r=eS(eN(e),t);return Y({dashPlaylists:eo(r.representationInfo),locations:r.locations,contentSteering:r.contentSteeringInfo,sidxMapping:t.sidxMapping,previousManifest:t.previousManifest,eventStream:r.eventStream})},ex=e=>eR(eN(e))},770:(e,t,r)=>{var n=r(7925),i=n.find,a=n.NAMESPACE;function o(e){return""!==e}function s(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function u(e){return e?Object.keys((e?e.split(/[\t\n\f\r ]+/).filter(o):[]).reduce(s,{})):[]}function l(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function c(e,t){var r=e.prototype;if(!(r instanceof t)){function n(){}n.prototype=t.prototype,l(r,n=new n),e.prototype=r=n}r.constructor!=e&&("function"!=typeof e&&console.error("unknown Class:"+e),r.constructor=e)}var f={},p=f.ELEMENT_NODE=1,h=f.ATTRIBUTE_NODE=2,d=f.TEXT_NODE=3,g=f.CDATA_SECTION_NODE=4,m=f.ENTITY_REFERENCE_NODE=5,b=f.ENTITY_NODE=6,y=f.PROCESSING_INSTRUCTION_NODE=7,E=f.COMMENT_NODE=8,v=f.DOCUMENT_NODE=9,T=f.DOCUMENT_TYPE_NODE=10,w=f.DOCUMENT_FRAGMENT_NODE=11,D=f.NOTATION_NODE=12,A={},S={};A.INDEX_SIZE_ERR=(S[1]="Index size error",1),A.DOMSTRING_SIZE_ERR=(S[2]="DOMString size error",2);var N=A.HIERARCHY_REQUEST_ERR=(S[3]="Hierarchy request error",3);A.WRONG_DOCUMENT_ERR=(S[4]="Wrong document",4),A.INVALID_CHARACTER_ERR=(S[5]="Invalid character",5),A.NO_DATA_ALLOWED_ERR=(S[6]="No data allowed",6),A.NO_MODIFICATION_ALLOWED_ERR=(S[7]="No modification allowed",7);var R=A.NOT_FOUND_ERR=(S[8]="Not found",8);A.NOT_SUPPORTED_ERR=(S[9]="Not supported",9);var O=A.INUSE_ATTRIBUTE_ERR=(S[10]="Attribute in use",10);function x(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,S[e]),this.message=S[e],Error.captureStackTrace&&Error.captureStackTrace(this,x);return r.code=e,t&&(this.message=this.message+": "+t),r}function I(){}function C(e,t){this._node=e,this._refresh=t,L(this)}function L(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(eg(e,"length",r.length),!e.$$length||r.length=0){for(var i=t.length-1;n"==e&&">"||"&"==e&&"&"||'"'==e&&"""||"&#"+e.charCodeAt()+";"}function F(e,t){if(t(e))return!0;if(e=e.firstChild)do if(F(e,t))return!0;while(e=e.nextSibling)}function X(){this.ownerDocument=this}function j(e,t,r,n){e&&e._inc++,r.namespaceURI===a.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function V(e,t,r){if(e&&e._inc){e._inc++;var n=t.childNodes;if(r)n[n.length++]=r;else{for(var i=t.firstChild,a=0;i;)n[a++]=i,i=i.nextSibling;n.length=a,delete n[n.length]}}}function H(e,t){var r=t.previousSibling,n=t.nextSibling;return r?r.nextSibling=n:e.firstChild=n,n?n.previousSibling=r:e.lastChild=r,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,V(e.ownerDocument,e),t}function G(e){return e&&e.nodeType===q.DOCUMENT_TYPE_NODE}function z(e){return e&&e.nodeType===q.ELEMENT_NODE}function $(e){return e&&e.nodeType===q.TEXT_NODE}function W(e,t){var r=e.childNodes||[];if(i(r,z)||G(t))return!1;var n=i(r,G);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function Y(e,t){var r=e.childNodes||[];if(i(r,function(e){return z(e)&&e!==t}))return!1;var n=i(r,G);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function K(e,t,r){var n=e.childNodes||[],a=t.childNodes||[];if(t.nodeType===q.DOCUMENT_FRAGMENT_NODE){var o=a.filter(z);if(o.length>1||i(a,$))throw new x(N,"More than one element or text in fragment");if(1===o.length&&!Y(e,r))throw new x(N,"Element in fragment can not be inserted before doctype")}if(z(t)&&!Y(e,r))throw new x(N,"Only one element can be added and only after doctype");if(G(t)){if(i(n,function(e){return G(e)&&e!==r}))throw new x(N,"Only one doctype is allowed");var s=i(n,z);if(r&&n.indexOf(s)1||i(a,$))throw new x(N,"More than one element or text in fragment");if(1===o.length&&!W(e,r))throw new x(N,"Element in fragment can not be inserted before doctype")}if(z(t)&&!W(e,r))throw new x(N,"Only one element can be added and only after doctype");if(G(t)){if(i(n,G))throw new x(N,"Only one doctype is allowed");var s=i(n,z);if(r&&n.indexOf(s)=0;D--){var A=i[D];if(""===A.prefix&&A.namespace===e.namespaceURI){o=A.namespace;break}}if(o!==e.namespaceURI)for(var D=i.length-1;D>=0;D--){var A=i[D];if(A.namespace===e.namespaceURI){A.prefix&&(f=A.prefix+":"+c);break}}}t.push("<",f);for(var S=0;S"),r&&/^script$/i.test(c))for(;l;)l.data?t.push(l.data):ed(l,t,r,n,i.slice()),l=l.nextSibling;else for(;l;)ed(l,t,r,n,i.slice()),l=l.nextSibling;t.push("")}else t.push("/>");return;case v:case w:for(var l=e.firstChild;l;)ed(l,t,r,n,i.slice()),l=l.nextSibling;return;case h:return eh(t,e.name,e.value);case d:return t.push(e.data.replace(/[<&>]/g,k));case g:return t.push("",e.data,"");case E:return t.push("\x3c!--",e.data,"--\x3e");case T:var x=e.publicId,I=e.systemId;if(t.push("");else if(I&&"."!=I)t.push(" SYSTEM ",I,">");else{var C=e.internalSubset;C&&t.push(" [",C,"]"),t.push(">")}return;case y:return t.push("");case m:return t.push("&",e.nodeName,";");default:t.push("??",e.nodeName)}}function eg(e,t,r){e[t]=r}A.INVALID_STATE_ERR=(S[11]="Invalid state",11),A.SYNTAX_ERR=(S[12]="Syntax error",12),A.INVALID_MODIFICATION_ERR=(S[13]="Invalid modification",13),A.NAMESPACE_ERR=(S[14]="Invalid namespace",14),A.INVALID_ACCESS_ERR=(S[15]="Invalid access",15),x.prototype=Error.prototype,l(A,x),I.prototype={length:0,item:function(e){return e>=0&&e0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==h?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var r=t._nsMap;if(r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];t=t.nodeType==h?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){return null==this.lookupPrefix(e)}},l(f,q),l(f,q.prototype),X.prototype={nodeName:"#document",nodeType:v,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==w){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return J(this,e,t),e.ownerDocument=this,null===this.documentElement&&e.nodeType===p&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),H(this,e)},replaceChild:function(e,t){J(this,e,t,K),e.ownerDocument=this,t&&this.removeChild(t),z(e)&&(this.documentElement=e)},importNode:function(e,t){return function e(t,r,n){var i;switch(r.nodeType){case p:(i=r.cloneNode(!1)).ownerDocument=t;case w:break;case h:n=!0}if(i||(i=r.cloneNode(!1)),i.ownerDocument=t,i.parentNode=null,n)for(var a=r.firstChild;a;)i.appendChild(e(t,a,n)),a=a.nextSibling;return i}(this,e,t)},getElementById:function(e){var t=null;return F(this.documentElement,function(r){if(r.nodeType==p&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=u(e);return new C(this,function(r){var n=[];return t.length>0&&F(r.documentElement,function(i){if(i!==r&&i.nodeType===p){var a=i.getAttribute("class");if(a){var o=e===a;if(!o){var s=u(a);o=t.every(function(e){return s&&-1!==s.indexOf(e)})}o&&n.push(i)}}}),n})},createElement:function(e){var t=new Z;return t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new I,(t.attributes=new U)._ownerElement=t,t},createDocumentFragment:function(){var e=new eu;return e.ownerDocument=this,e.childNodes=new I,e},createTextNode:function(e){var t=new et;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new er;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){var t=new en;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new el;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Q;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new es;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Z,n=t.split(":"),i=r.attributes=new U;return r.childNodes=new I,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=e,2==n.length?(r.prefix=n[0],r.localName=n[1]):r.localName=t,i._ownerElement=r,r},createAttributeNS:function(e,t){var r=new Q,n=t.split(":");return r.ownerDocument=this,r.nodeName=t,r.name=t,r.namespaceURI=e,r.specified=!0,2==n.length?(r.prefix=n[0],r.localName=n[1]):r.localName=t,r}},c(X,q),Z.prototype={nodeType:p,hasAttribute:function(e){return null!=this.getAttributeNode(e)},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var r=this.ownerDocument.createAttribute(e);r.value=r.nodeValue=""+t,this.setAttributeNode(r)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===w?this.insertBefore(e,null):(e.parentNode&&e.parentNode.removeChild(e),e.parentNode=this,e.previousSibling=this.lastChild,e.nextSibling=null,e.previousSibling?e.previousSibling.nextSibling=e:this.firstChild=e,this.lastChild=e,V(this.ownerDocument,this,e),e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);r&&this.removeAttributeNode(r)},hasAttributeNS:function(e,t){return null!=this.getAttributeNodeNS(e,t)},getAttributeNS:function(e,t){var r=this.getAttributeNodeNS(e,t);return r&&r.value||""},setAttributeNS:function(e,t,r){var n=this.ownerDocument.createAttributeNS(e,t);n.value=n.nodeValue=""+r,this.setAttributeNode(n)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new C(this,function(t){var r=[];return F(t,function(n){n!==t&&n.nodeType==p&&("*"===e||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new C(this,function(r){var n=[];return F(r,function(i){i!==r&&i.nodeType===p&&("*"===e||i.namespaceURI===e)&&("*"===t||i.localName==t)&&n.push(i)}),n})}},X.prototype.getElementsByTagName=Z.prototype.getElementsByTagName,X.prototype.getElementsByTagNameNS=Z.prototype.getElementsByTagNameNS,c(Z,q),Q.prototype.nodeType=h,c(Q,q),ee.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw Error(S[N])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,r){r=this.data.substring(0,e)+r+this.data.substring(e+t),this.nodeValue=this.data=r,this.length=r.length}},c(ee,q),et.prototype={nodeName:"#text",nodeType:d,splitText:function(e){var t=this.data,r=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var n=this.ownerDocument.createTextNode(r);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}},c(et,ee),er.prototype={nodeName:"#comment",nodeType:E},c(er,ee),en.prototype={nodeName:"#cdata-section",nodeType:g},c(en,ee),ei.prototype.nodeType=T,c(ei,q),ea.prototype.nodeType=D,c(ea,q),eo.prototype.nodeType=b,c(eo,q),es.prototype.nodeType=m,c(es,q),eu.prototype.nodeName="#document-fragment",eu.prototype.nodeType=w,c(eu,q),el.prototype.nodeType=y,c(el,q),ec.prototype.serializeToString=function(e,t,r){return ef.call(e,t,r)},q.prototype.toString=ef;try{Object.defineProperty&&(Object.defineProperty(C.prototype,"length",{get:function(){return L(this),this.$$length}}),Object.defineProperty(q.prototype,"textContent",{get:function(){return function e(t){switch(t.nodeType){case p:case w:var r=[];for(t=t.firstChild;t;)7!==t.nodeType&&8!==t.nodeType&&r.push(e(t)),t=t.nextSibling;return r.join("");default:return t.nodeValue}}(this)},set:function(e){switch(this.nodeType){case p:case w:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),eg=function(e,t,r){e["$$"+t]=r})}catch(e){}t.DocumentType=ei,t.DOMException=x,t.DOMImplementation=B,t.Element=Z,t.Node=q,t.NodeList=I,t.XMLSerializer=ec},1082:e=>{var t,r,n,i,a,o,s;t=function(e){return 9e4*e},r=function(e,t){return e*t},n=function(e){return e/9e4},i=function(e,t){return e/t},a=function(e,r){return t(i(e,r))},o=function(e,t){return r(n(e),t)},s=function(e,t,r){return n(r?e:e-t)},e.exports={ONE_SECOND_IN_TS:9e4,secondsToVideoTs:t,secondsToAudioTs:r,videoTsToSeconds:n,audioTsToSeconds:i,audioTsToVideoTs:a,videoTsToAudioTs:o,metadataTsToSeconds:s}},2037:(e,t,r)=>{"use strict";var n=r(8202);e.exports=function(e,t){return void 0===t&&(t=!1),function(r,i,a){if(r){e(r);return}if(i.statusCode>=400&&i.statusCode<=599){var o=a;if(t){if(n.TextDecoder){var s,u=(void 0===(s=i.headers&&i.headers["content-type"])&&(s=""),s.toLowerCase().split(";").reduce(function(e,t){var r=t.split("="),n=r[0],i=r[1];return"charset"===n.trim()?i.trim():e},"utf-8"));try{o=new TextDecoder(u).decode(a)}catch(e){}}else o=String.fromCharCode.apply(null,new Uint8Array(a))}e({cause:o});return}e(null,a)}}},2638:(e,t,r)=>{"use strict";r.d(t,{Af:()=>h,Ar:()=>p,Bu:()=>d,L7:()=>g,Sk:()=>c,WG:()=>f,W_:()=>s,hc:()=>o});var n=r(8202),i=r.n(n),a=function(e,t){for(var r="";t--;)r+=e;return r},o=function(e){return"function"===ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer},s=function(e){return e instanceof Uint8Array?e:(!Array.isArray(e)&&!o(e)&&!(e instanceof ArrayBuffer)&&(e="number"!=typeof e||"number"==typeof e&&e!=e?0:[e]),new Uint8Array(e&&e.buffer||e,e&&e.byteOffset||0,e&&e.byteLength||0))},u=i().BigInt||Number,l=[u("0x1"),u("0x100"),u("0x10000"),u("0x1000000"),u("0x100000000"),u("0x10000000000"),u("0x1000000000000"),u("0x100000000000000"),u("0x10000000000000000")],c=(function(){var e=new Uint16Array([65484]),t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);255===t[0]?"big":204===t[0]?"little":"unknown"}(),function(e,t){var r=void 0===t?{}:t,n=r.signed,i=r.le,a=void 0!==i&&i;e=s(e);var o=a?"reduce":"reduceRight",c=(e[o]?e[o]:Array.prototype[o]).call(e,function(t,r,n){var i=a?n:Math.abs(n+1-e.length);return t+u(r)*l[i]},u(0));if(void 0!==n&&n){var f=l[e.length]/u(2)-u(1);(c=u(c))>f&&(c-=f,c-=f,c-=u(2))}return Number(c)}),f=function(e,t){var r=(void 0===t?{}:t).le,n=void 0!==r&&r;("bigint"!=typeof e&&"number"!=typeof e||"number"==typeof e&&e!=e)&&(e=0);for(var i=Math.ceil((e=u(e)).toString(2).length/8),a=new Uint8Array(new ArrayBuffer(i)),o=0;o=t.length&&l.call(t,function(t,r){return t===(u[r]?u[r]&e[a+r]:e[a+r])})}},2651:(e,t,r)=>{"use strict";let n;r.d(t,{A:()=>ts});var i,a,o,s={};function u(e,t){return function(){return e.apply(t,arguments)}}r.r(s),r.d(s,{hasBrowserEnv:()=>ec,hasStandardBrowserEnv:()=>ep,hasStandardBrowserWebWorkerEnv:()=>eh,navigator:()=>ef,origin:()=>ed});var l=r(7358);let{toString:c}=Object.prototype,{getPrototypeOf:f}=Object,p=(e=>t=>{let r=c.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),h=e=>(e=e.toLowerCase(),t=>p(t)===e),d=e=>t=>typeof t===e,{isArray:g}=Array,m=d("undefined"),b=h("ArrayBuffer"),y=d("string"),E=d("function"),v=d("number"),T=e=>null!==e&&"object"==typeof e,w=e=>{if("object"!==p(e))return!1;let t=f(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},D=h("Date"),A=h("File"),S=h("Blob"),N=h("FileList"),R=h("URLSearchParams"),[O,x,I,C]=["ReadableStream","Request","Response","Headers"].map(h);function L(e,t,{allOwnKeys:r=!1}={}){let n,i;if(null!=e){if("object"!=typeof e&&(e=[e]),g(e))for(n=0,i=e.length;n0;)if(t===(r=n[i]).toLowerCase())return r;return null}let M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,_=e=>!m(e)&&e!==M,P=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&f(Uint8Array)),B=h("HTMLFormElement"),q=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),k=h("RegExp"),F=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};L(r,(r,i)=>{let a;!1!==(a=t(r,i,e))&&(n[i]=a||r)}),Object.defineProperties(e,n)},X=h("AsyncFunction"),j=(i="function"==typeof setImmediate,a=E(M.postMessage),i?setImmediate:a?((e,t)=>(M.addEventListener("message",({source:r,data:n})=>{r===M&&n===e&&t.length&&t.shift()()},!1),r=>{t.push(r),M.postMessage(e,"*")}))(`axios@${Math.random()}`,[]):e=>setTimeout(e)),V="undefined"!=typeof queueMicrotask?queueMicrotask.bind(M):void 0!==l&&l.nextTick||j,H={isArray:g,isArrayBuffer:b,isBuffer:function(e){return null!==e&&!m(e)&&null!==e.constructor&&!m(e.constructor)&&E(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||E(e.append)&&("formdata"===(t=p(e))||"object"===t&&E(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&b(e.buffer)},isString:y,isNumber:v,isBoolean:e=>!0===e||!1===e,isObject:T,isPlainObject:w,isReadableStream:O,isRequest:x,isResponse:I,isHeaders:C,isUndefined:m,isDate:D,isFile:A,isBlob:S,isRegExp:k,isFunction:E,isStream:e=>T(e)&&E(e.pipe),isURLSearchParams:R,isTypedArray:P,isFileList:N,forEach:L,merge:function e(){let{caseless:t}=_(this)&&this||{},r={},n=(n,i)=>{let a=t&&U(r,i)||i;w(r[a])&&w(n)?r[a]=e(r[a],n):w(n)?r[a]=e({},n):g(n)?r[a]=n.slice():r[a]=n};for(let e=0,t=arguments.length;e(L(t,(t,n)=>{r&&E(t)?e[n]=u(t,r):e[n]=t},{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,a,o;let s={};if(t=t||{},null==e)return t;do{for(a=(i=Object.getOwnPropertyNames(e)).length;a-- >0;)o=i[a],(!n||n(o,e,t))&&!s[o]&&(t[o]=e[o],s[o]=!0);e=!1!==r&&f(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:p,kindOfTest:h,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;let n=e.indexOf(t,r);return -1!==n&&n===r},toArray:e=>{if(!e)return null;if(g(e))return e;let t=e.length;if(!v(t))return null;let r=Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{let r;let n=(e&&e[Symbol.iterator]).call(e);for(;(r=n.next())&&!r.done;){let n=r.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let r;let n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:B,hasOwnProperty:q,hasOwnProp:q,reduceDescriptors:F,freezeMethods:e=>{F(e,(t,r)=>{if(E(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;if(E(e[r])){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},toObjectSet:(e,t)=>{let r={};return(e=>{e.forEach(e=>{r[e]=!0})})(g(e)?e:String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e*=1)?e:t,findKey:U,global:M,isContextDefined:_,isSpecCompliantForm:function(e){return!!(e&&E(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{let t=Array(10),r=(e,n)=>{if(T(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;let i=g(e)?[]:{};return L(e,(e,t)=>{let a=r(e,n+1);m(a)||(i[t]=a)}),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:X,isThenable:e=>e&&(T(e)||E(e))&&E(e.then)&&E(e.catch),setImmediate:j,asap:V};function G(e,t,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}H.inherits(G,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:H.toJSONObject(this.config),code:this.code,status:this.status}}});let z=G.prototype,$={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{$[e]={value:e}}),Object.defineProperties(G,$),Object.defineProperty(z,"isAxiosError",{value:!0}),G.from=(e,t,r,n,i,a)=>{let o=Object.create(z);return H.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),G.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,a&&Object.assign(o,a),o};var W=r(5714).Buffer;function Y(e){return H.isPlainObject(e)||H.isArray(e)}function K(e){return H.endsWith(e,"[]")?e.slice(0,-2):e}function J(e,t,r){return e?e.concat(t).map(function(e,t){return e=K(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}let Z=H.toFlatObject(H,{},null,function(e){return/^is[A-Z]/.test(e)}),Q=function(e,t,r){if(!H.isObject(e))throw TypeError("target must be an object");t=t||new FormData;let n=(r=H.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!H.isUndefined(t[e])})).metaTokens,i=r.visitor||l,a=r.dots,o=r.indexes,s=(r.Blob||"undefined"!=typeof Blob&&Blob)&&H.isSpecCompliantForm(t);if(!H.isFunction(i))throw TypeError("visitor must be a function");function u(e){if(null===e)return"";if(H.isDate(e))return e.toISOString();if(!s&&H.isBlob(e))throw new G("Blob is not supported. Use a Buffer instead.");return H.isArrayBuffer(e)||H.isTypedArray(e)?s&&"function"==typeof Blob?new Blob([e]):W.from(e):e}function l(e,r,i){let s=e;if(e&&!i&&"object"==typeof e){if(H.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else{var l;if(H.isArray(e)&&(l=e,H.isArray(l)&&!l.some(Y))||(H.isFileList(e)||H.endsWith(r,"[]"))&&(s=H.toArray(e)))return r=K(r),s.forEach(function(e,n){H.isUndefined(e)||null===e||t.append(!0===o?J([r],n,a):null===o?r:r+"[]",u(e))}),!1}}return!!Y(e)||(t.append(J(i,r,a),u(e)),!1)}let c=[],f=Object.assign(Z,{defaultVisitor:l,convertValue:u,isVisitable:Y});if(!H.isObject(e))throw TypeError("data must be an object");return!function e(r,n){if(!H.isUndefined(r)){if(-1!==c.indexOf(r))throw Error("Circular reference detected in "+n.join("."));c.push(r),H.forEach(r,function(r,a){!0===(!(H.isUndefined(r)||null===r)&&i.call(t,r,H.isString(a)?a.trim():a,n,f))&&e(r,n?n.concat(a):[a])}),c.pop()}}(e),t};function ee(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function et(e,t){this._pairs=[],e&&Q(e,this,t)}let er=et.prototype;function en(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ei(e,t,r){let n;if(!t)return e;let i=r&&r.encode||en;H.isFunction(r)&&(r={serialize:r});let a=r&&r.serialize;if(n=a?a(t,r):H.isURLSearchParams(t)?t.toString():new et(t,r).toString(i)){let t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e}er.append=function(e,t){this._pairs.push([e,t])},er.toString=function(e){let t=e?function(t){return e.call(this,t,ee)}:ee;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class ea{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){H.forEach(this.handlers,function(t){null!==t&&e(t)})}}let eo={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},es="undefined"!=typeof URLSearchParams?URLSearchParams:et,eu="undefined"!=typeof FormData?FormData:null,el="undefined"!=typeof Blob?Blob:null,ec="undefined"!=typeof window&&"undefined"!=typeof document,ef="object"==typeof navigator&&navigator||void 0,ep=ec&&(!ef||0>["ReactNative","NativeScript","NS"].indexOf(ef.product)),eh="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,ed=ec&&window.location.href||"http://localhost",eg={...s,isBrowser:!0,classes:{URLSearchParams:es,FormData:eu,Blob:el},protocols:["http","https","file","blob","url","data"]},em=function(e){if(H.isFormData(e)&&H.isFunction(e.entries)){let t={};return H.forEachEntry(e,(e,r)=>{!function e(t,r,n,i){let a=t[i++];if("__proto__"===a)return!0;let o=Number.isFinite(+a),s=i>=t.length;return(a=!a&&H.isArray(n)?n.length:a,s)?H.hasOwnProp(n,a)?n[a]=[n[a],r]:n[a]=r:(n[a]&&H.isObject(n[a])||(n[a]=[]),e(t,r,n[a],i)&&H.isArray(n[a])&&(n[a]=function(e){let t,r;let n={},i=Object.keys(e),a=i.length;for(t=0;t"[]"===e[0]?"":e[1]||e[0]),r,t,0)}),t}return null},eb={transitional:eo,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){let r;let n=t.getContentType()||"",i=n.indexOf("application/json")>-1,a=H.isObject(e);if(a&&H.isHTMLForm(e)&&(e=new FormData(e)),H.isFormData(e))return i?JSON.stringify(em(e)):e;if(H.isArrayBuffer(e)||H.isBuffer(e)||H.isStream(e)||H.isFile(e)||H.isBlob(e)||H.isReadableStream(e))return e;if(H.isArrayBufferView(e))return e.buffer;if(H.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(a){if(n.indexOf("application/x-www-form-urlencoded")>-1){var o,s;return(o=e,s=this.formSerializer,Q(o,new eg.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return eg.isNode&&H.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},s))).toString()}if((r=H.isFileList(e))||n.indexOf("multipart/form-data")>-1){let t=this.env&&this.env.FormData;return Q(r?{"files[]":e}:e,t&&new t,this.formSerializer)}}return a||i?(t.setContentType("application/json",!1),function(e,t,r){if(H.isString(e))try{return(0,JSON.parse)(e),H.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){let t=this.transitional||eb.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(H.isResponse(e)||H.isReadableStream(e))return e;if(e&&H.isString(e)&&(r&&!this.responseType||n)){let r=t&&t.silentJSONParsing;try{return JSON.parse(e)}catch(e){if(!r&&n){if("SyntaxError"===e.name)throw G.from(e,G.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:eg.classes.FormData,Blob:eg.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};H.forEach(["delete","get","head","post","put","patch"],e=>{eb.headers[e]={}});let ey=H.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),eE=e=>{let t,r,n;let i={};return e&&e.split("\n").forEach(function(e){n=e.indexOf(":"),t=e.substring(0,n).trim().toLowerCase(),r=e.substring(n+1).trim(),t&&(!i[t]||!ey[t])&&("set-cookie"===t?i[t]?i[t].push(r):i[t]=[r]:i[t]=i[t]?i[t]+", "+r:r)}),i},ev=Symbol("internals");function eT(e){return e&&String(e).trim().toLowerCase()}function ew(e){return!1===e||null==e?e:H.isArray(e)?e.map(ew):String(e)}let eD=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function eA(e,t,r,n,i){if(H.isFunction(n))return n.call(this,t,r);if(i&&(t=r),H.isString(t)){if(H.isString(n))return -1!==t.indexOf(n);if(H.isRegExp(n))return n.test(t)}}class eS{constructor(e){e&&this.set(e)}set(e,t,r){let n=this;function i(e,t,r){let i=eT(t);if(!i)throw Error("header name must be a non-empty string");let a=H.findKey(n,i);a&&void 0!==n[a]&&!0!==r&&(void 0!==r||!1===n[a])||(n[a||t]=ew(e))}let a=(e,t)=>H.forEach(e,(e,r)=>i(e,r,t));if(H.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(H.isString(e)&&(e=e.trim())&&!eD(e))a(eE(e),t);else if(H.isHeaders(e))for(let[t,n]of e.entries())i(n,t,r);else null!=e&&i(t,e,r);return this}get(e,t){if(e=eT(e)){let r=H.findKey(this,e);if(r){let e=this[r];if(!t)return e;if(!0===t)return function(e){let t;let r=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;for(;t=n.exec(e);)r[t[1]]=t[2];return r}(e);if(H.isFunction(t))return t.call(this,e,r);if(H.isRegExp(t))return t.exec(e);throw TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=eT(e)){let r=H.findKey(this,e);return!!(r&&void 0!==this[r]&&(!t||eA(this,this[r],r,t)))}return!1}delete(e,t){let r=this,n=!1;function i(e){if(e=eT(e)){let i=H.findKey(r,e);i&&(!t||eA(r,r[i],i,t))&&(delete r[i],n=!0)}}return H.isArray(e)?e.forEach(i):i(e),n}clear(e){let t=Object.keys(this),r=t.length,n=!1;for(;r--;){let i=t[r];(!e||eA(this,this[i],i,e,!0))&&(delete this[i],n=!0)}return n}normalize(e){let t=this,r={};return H.forEach(this,(n,i)=>{let a=H.findKey(r,i);if(a){t[a]=ew(n),delete t[i];return}let o=e?i.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r):String(i).trim();o!==i&&delete t[i],t[o]=ew(n),r[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let t=Object.create(null);return H.forEach(this,(r,n)=>{null!=r&&!1!==r&&(t[n]=e&&H.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){let r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){let t=(this[ev]=this[ev]={accessors:{}}).accessors,r=this.prototype;function n(e){let n=eT(e);t[n]||(!function(e,t){let r=H.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}(r,e),t[n]=!0)}return H.isArray(e)?e.forEach(n):n(e),this}}function eN(e,t){let r=this||eb,n=t||r,i=eS.from(n.headers),a=n.data;return H.forEach(e,function(e){a=e.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function eR(e){return!!(e&&e.__CANCEL__)}function eO(e,t,r){G.call(this,null==e?"canceled":e,G.ERR_CANCELED,t,r),this.name="CanceledError"}function ex(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new G("Request failed with status code "+r.status,[G.ERR_BAD_REQUEST,G.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}eS.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),H.reduceDescriptors(eS.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),H.freezeMethods(eS),H.inherits(eO,G,{__CANCEL__:!0});let eI=function(e,t){let r;let n=Array(e=e||10),i=Array(e),a=0,o=0;return t=void 0!==t?t:1e3,function(s){let u=Date.now(),l=i[o];r||(r=u),n[a]=s,i[a]=u;let c=o,f=0;for(;c!==a;)f+=n[c++],c%=e;if((a=(a+1)%e)===o&&(o=(o+1)%e),u-r{i=a,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{let t=Date.now(),s=t-i;s>=a?o(e,t):(r=e,n||(n=setTimeout(()=>{n=null,o(r)},a-s)))},()=>r&&o(r)]},eL=(e,t,r=3)=>{let n=0,i=eI(50,250);return eC(r=>{let a=r.loaded,o=r.lengthComputable?r.total:void 0,s=a-n,u=i(s);n=a,e({loaded:a,total:o,progress:o?a/o:void 0,bytes:s,rate:u||void 0,estimated:u&&o&&a<=o?(o-a)/u:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})},r)},eU=(e,t)=>{let r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},eM=e=>(...t)=>H.asap(()=>e(...t)),e_=eg.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,eg.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(eg.origin),eg.navigator&&/(msie|trident)/i.test(eg.navigator.userAgent)):()=>!0,eP=eg.hasStandardBrowserEnv?{write(e,t,r,n,i,a){let o=[e+"="+encodeURIComponent(t)];H.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),H.isString(n)&&o.push("path="+n),H.isString(i)&&o.push("domain="+i),!0===a&&o.push("secure"),document.cookie=o.join("; ")},read(e){let t=document.cookie.match(RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function eB(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&n||!1==r?t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e:t}let eq=e=>e instanceof eS?{...e}:e;function ek(e,t){t=t||{};let r={};function n(e,t,r,n){return H.isPlainObject(e)&&H.isPlainObject(t)?H.merge.call({caseless:n},e,t):H.isPlainObject(t)?H.merge({},t):H.isArray(t)?t.slice():t}function i(e,t,r,i){return H.isUndefined(t)?H.isUndefined(e)?void 0:n(void 0,e,r,i):n(e,t,r,i)}function a(e,t){if(!H.isUndefined(t))return n(void 0,t)}function o(e,t){return H.isUndefined(t)?H.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function s(r,i,a){return a in t?n(r,i):a in e?n(void 0,r):void 0}let u={url:a,method:a,data:a,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:s,headers:(e,t,r)=>i(eq(e),eq(t),r,!0)};return H.forEach(Object.keys(Object.assign({},e,t)),function(n){let a=u[n]||i,o=a(e[n],t[n],n);H.isUndefined(o)&&a!==s||(r[n]=o)}),r}let eF=e=>{let t;let r=ek({},e),{data:n,withXSRFToken:i,xsrfHeaderName:a,xsrfCookieName:o,headers:s,auth:u}=r;if(r.headers=s=eS.from(s),r.url=ei(eB(r.baseURL,r.url),e.params,e.paramsSerializer),u&&s.set("Authorization","Basic "+btoa((u.username||"")+":"+(u.password?unescape(encodeURIComponent(u.password)):""))),H.isFormData(n)){if(eg.hasStandardBrowserEnv||eg.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(!1!==(t=s.getContentType())){let[e,...r]=t?t.split(";").map(e=>e.trim()).filter(Boolean):[];s.setContentType([e||"multipart/form-data",...r].join("; "))}}if(eg.hasStandardBrowserEnv&&(i&&H.isFunction(i)&&(i=i(r)),i||!1!==i&&e_(r.url))){let e=a&&o&&eP.read(o);e&&s.set(a,e)}return r},eX="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){let n,i,a,o,s;let u=eF(e),l=u.data,c=eS.from(u.headers).normalize(),{responseType:f,onUploadProgress:p,onDownloadProgress:h}=u;function d(){o&&o(),s&&s(),u.cancelToken&&u.cancelToken.unsubscribe(n),u.signal&&u.signal.removeEventListener("abort",n)}let g=new XMLHttpRequest;function m(){if(!g)return;let n=eS.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());ex(function(e){t(e),d()},function(e){r(e),d()},{data:f&&"text"!==f&&"json"!==f?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:n,config:e,request:g}),g=null}g.open(u.method.toUpperCase(),u.url,!0),g.timeout=u.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new G("Request aborted",G.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new G("Network Error",G.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=u.timeout?"timeout of "+u.timeout+"ms exceeded":"timeout exceeded",n=u.transitional||eo;u.timeoutErrorMessage&&(t=u.timeoutErrorMessage),r(new G(t,n.clarifyTimeoutError?G.ETIMEDOUT:G.ECONNABORTED,e,g)),g=null},void 0===l&&c.setContentType(null),"setRequestHeader"in g&&H.forEach(c.toJSON(),function(e,t){g.setRequestHeader(t,e)}),H.isUndefined(u.withCredentials)||(g.withCredentials=!!u.withCredentials),f&&"json"!==f&&(g.responseType=u.responseType),h&&([a,s]=eL(h,!0),g.addEventListener("progress",a)),p&&g.upload&&([i,o]=eL(p),g.upload.addEventListener("progress",i),g.upload.addEventListener("loadend",o)),(u.cancelToken||u.signal)&&(n=t=>{g&&(r(!t||t.type?new eO(null,e,g):t),g.abort(),g=null)},u.cancelToken&&u.cancelToken.subscribe(n),u.signal&&(u.signal.aborted?n():u.signal.addEventListener("abort",n)));let b=function(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u.url);if(b&&-1===eg.protocols.indexOf(b)){r(new G("Unsupported protocol "+b+":",G.ERR_BAD_REQUEST,e));return}g.send(l||null)})},ej=(e,t)=>{let{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController,i=function(e){if(!r){r=!0,o();let t=e instanceof Error?e:this.reason;n.abort(t instanceof G?t:new eO(t instanceof Error?t.message:t))}},a=t&&setTimeout(()=>{a=null,i(new G(`timeout ${t} of ms exceeded`,G.ETIMEDOUT))},t),o=()=>{e&&(a&&clearTimeout(a),a=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));let{signal:s}=n;return s.unsubscribe=()=>H.asap(o),s}},eV=function*(e,t){let r,n=e.byteLength;if(!t||n{let i;let a=eH(e,t),o=0,s=e=>{!i&&(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{let{done:t,value:n}=await a.next();if(t){s(),e.close();return}let i=n.byteLength;if(r){let e=o+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw s(e),e}},cancel:e=>(s(e),a.return())},{highWaterMark:2})},e$="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,eW=e$&&"function"==typeof ReadableStream,eY=e$&&("function"==typeof TextEncoder?(n=new TextEncoder,e=>n.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer())),eK=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},eJ=eW&&eK(()=>{let e=!1,t=new Request(eg.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),eZ=eW&&eK(()=>H.isReadableStream(new Response("").body)),eQ={stream:eZ&&(e=>e.body)};e$&&(o=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{eQ[e]||(eQ[e]=H.isFunction(o[e])?t=>t[e]():(t,r)=>{throw new G(`Response type '${e}' is not supported`,G.ERR_NOT_SUPPORT,r)})}));let e0=async e=>{if(null==e)return 0;if(H.isBlob(e))return e.size;if(H.isSpecCompliantForm(e)){let t=new Request(eg.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return H.isArrayBufferView(e)||H.isArrayBuffer(e)?e.byteLength:(H.isURLSearchParams(e)&&(e+=""),H.isString(e))?(await eY(e)).byteLength:void 0},e1=async(e,t)=>{let r=H.toFiniteNumber(e.getContentLength());return null==r?e0(t):r},e2={http:null,xhr:eX,fetch:e$&&(async e=>{let t,r,{url:n,method:i,data:a,signal:o,cancelToken:s,timeout:u,onDownloadProgress:l,onUploadProgress:c,responseType:f,headers:p,withCredentials:h="same-origin",fetchOptions:d}=eF(e);f=f?(f+"").toLowerCase():"text";let g=ej([o,s&&s.toAbortSignal()],u),m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});try{if(c&&eJ&&"get"!==i&&"head"!==i&&0!==(r=await e1(p,a))){let e,t=new Request(n,{method:"POST",body:a,duplex:"half"});if(H.isFormData(a)&&(e=t.headers.get("content-type"))&&p.setContentType(e),t.body){let[e,n]=eU(r,eL(eM(c)));a=ez(t.body,65536,e,n)}}H.isString(h)||(h=h?"include":"omit");let o="credentials"in Request.prototype;t=new Request(n,{...d,signal:g,method:i.toUpperCase(),headers:p.normalize().toJSON(),body:a,duplex:"half",credentials:o?h:void 0});let s=await fetch(t),u=eZ&&("stream"===f||"response"===f);if(eZ&&(l||u&&m)){let e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});let t=H.toFiniteNumber(s.headers.get("content-length")),[r,n]=l&&eU(t,eL(eM(l),!0))||[];s=new Response(ez(s.body,65536,r,()=>{n&&n(),m&&m()}),e)}f=f||"text";let b=await eQ[H.findKey(eQ,f)||"text"](s,e);return!u&&m&&m(),await new Promise((r,n)=>{ex(r,n,{data:b,headers:eS.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:t})})}catch(r){if(m&&m(),r&&"TypeError"===r.name&&/fetch/i.test(r.message))throw Object.assign(new G("Network Error",G.ERR_NETWORK,e,t),{cause:r.cause||r});throw G.from(r,r&&r.code,e,t)}})};H.forEach(e2,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});let e5=e=>`- ${e}`,e3=e=>H.isFunction(e)||null===e||!1===e,e6={getAdapter:e=>{let t,r;let{length:n}=e=H.isArray(e)?e:[e],i={};for(let a=0;a`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new G("There is no suitable adapter to dispatch the request "+(n?e.length>1?"since :\n"+e.map(e5).join("\n"):" "+e5(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r}};function e8(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new eO(null,e)}function e4(e){return e8(e),e.headers=eS.from(e.headers),e.data=eN.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),e6.getAdapter(e.adapter||eb.adapter)(e).then(function(t){return e8(e),t.data=eN.call(e,e.transformResponse,t),t.headers=eS.from(t.headers),t},function(t){return!eR(t)&&(e8(e),t&&t.response&&(t.response.data=eN.call(e,e.transformResponse,t.response),t.response.headers=eS.from(t.response.headers))),Promise.reject(t)})}let e7="1.8.2",e9={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{e9[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});let te={};e9.transitional=function(e,t,r){function n(e,t){return"[Axios v"+e7+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,a)=>{if(!1===e)throw new G(n(i," has been removed"+(t?" in "+t:"")),G.ERR_DEPRECATED);return t&&!te[i]&&(te[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,a)}},e9.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};let tt={assertOptions:function(e,t,r){if("object"!=typeof e)throw new G("options must be an object",G.ERR_BAD_OPTION_VALUE);let n=Object.keys(e),i=n.length;for(;i-- >0;){let a=n[i],o=t[a];if(o){let t=e[a],r=void 0===t||o(t,a,e);if(!0!==r)throw new G("option "+a+" must be "+r,G.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new G("Unknown option "+a,G.ERR_BAD_OPTION)}},validators:e9},tr=tt.validators;class tn{constructor(e){this.defaults=e,this.interceptors={request:new ea,response:new ea}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=Error();let r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){let r,n;"string"==typeof e?(t=t||{}).url=e:t=e||{};let{transitional:i,paramsSerializer:a,headers:o}=t=ek(this.defaults,t);void 0!==i&&tt.assertOptions(i,{silentJSONParsing:tr.transitional(tr.boolean),forcedJSONParsing:tr.transitional(tr.boolean),clarifyTimeoutError:tr.transitional(tr.boolean)},!1),null!=a&&(H.isFunction(a)?t.paramsSerializer={serialize:a}:tt.assertOptions(a,{encode:tr.function,serialize:tr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),tt.assertOptions(t,{baseUrl:tr.spelling("baseURL"),withXsrfToken:tr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=o&&H.merge(o.common,o[t.method]);o&&H.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=eS.concat(s,o);let u=[],l=!0;this.interceptors.request.forEach(function(e){("function"!=typeof e.runWhen||!1!==e.runWhen(t))&&(l=l&&e.synchronous,u.unshift(e.fulfilled,e.rejected))});let c=[];this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let f=0;if(!l){let e=[e4.bind(this),void 0];for(e.unshift.apply(e,u),e.push.apply(e,c),n=e.length,r=Promise.resolve(t);f{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;let n=new Promise(e=>{r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e(function(e,n,i){!r.reason&&(r.reason=new eO(e,n,i),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new ti(function(t){e=t}),cancel:e}}}let ta={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ta).forEach(([e,t])=>{ta[t]=e});let to=function e(t){let r=new tn(t),n=u(tn.prototype.request,r);return H.extend(n,tn.prototype,r,{allOwnKeys:!0}),H.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(ek(t,r))},n}(eb);to.Axios=tn,to.CanceledError=eO,to.CancelToken=ti,to.isCancel=eR,to.VERSION=e7,to.toFormData=Q,to.AxiosError=G,to.Cancel=to.CanceledError,to.all=function(e){return Promise.all(e)},to.spread=function(e){return function(t){return e.apply(null,t)}},to.isAxiosError=function(e){return H.isObject(e)&&!0===e.isAxiosError},to.mergeConfig=ek,to.AxiosHeaders=eS,to.formToJSON=e=>em(H.isHTMLForm(e)?new FormData(e):e),to.getAdapter=e6.getAdapter,to.HttpStatusCode=ta,to.default=to;let ts=to},2667:(e,t,r)=>{var n,i=void 0!==r.g?r.g:"undefined"!=typeof window?window:{},a=r(542);"undefined"!=typeof document?n=document:(n=i["__GLOBAL_DOCUMENT_CACHE@4"])||(n=i["__GLOBAL_DOCUMENT_CACHE@4"]=a),e.exports=n},2678:(e,t,r)=>{"use strict";r.d(t,{ne:()=>R,J2:()=>O});var n,i=r(2638);new Uint8Array([79,112,117,115,72,101,97,100]);var a=function(e){return"string"==typeof e?(0,i.Af)(e):e},o=function(e){e=(0,i.W_)(e);for(var t=[],r=0;e.length>r;){var a=e[r],o=0,s=0,u=e[++s];for(s++;128&u;)o=(127&u)<<7,u=e[s],s++;o+=127&u;for(var l=0;l>>0,c=t.subarray(u+4,u+8);if(0===l)break;var f=u+l;if(f>t.length){if(n)break;f=t.length}var p=t.subarray(u+8,f);(0,i.L7)(c,r[0])&&(1===r.length?s.push(p):s.push.apply(s,e(p,r.slice(1),n))),u=f}return s},u=function(e,t){if(!(t=a(t)).length)return e.subarray(e.length);for(var r=0;r>>0,i=n>1?r+n:e.byteLength;return e.subarray(r+4,i)}r++}return e.subarray(e.length)},l=function(e,t,r){void 0===t&&(t=4),void 0===r&&(r=function(e){return bytesToNumber(e)});var n=[];if(!e||!e.length)return n;for(var i=bytesToNumber(e.subarray(4,8)),a=8;i;a+=t,i--)n.push(r(e.subarray(a,a+t)));return n},c={EBML:(0,i.W_)([26,69,223,163]),DocType:(0,i.W_)([66,130]),Segment:(0,i.W_)([24,83,128,103]),SegmentInfo:(0,i.W_)([21,73,169,102]),Tracks:(0,i.W_)([22,84,174,107]),Track:(0,i.W_)([174]),TrackNumber:(0,i.W_)([215]),DefaultDuration:(0,i.W_)([35,227,131]),TrackEntry:(0,i.W_)([174]),TrackType:(0,i.W_)([131]),FlagDefault:(0,i.W_)([136]),CodecID:(0,i.W_)([134]),CodecPrivate:(0,i.W_)([99,162]),VideoTrack:(0,i.W_)([224]),AudioTrack:(0,i.W_)([225]),Cluster:(0,i.W_)([31,67,182,117]),Timestamp:(0,i.W_)([231]),TimestampScale:(0,i.W_)([42,215,177]),BlockGroup:(0,i.W_)([160]),BlockDuration:(0,i.W_)([155]),Block:(0,i.W_)([161]),SimpleBlock:(0,i.W_)([163])},f=[128,64,32,16,8,4,2,1],p=function(e){for(var t=1,r=0;r=r.length)return r.length;var a=h(r,n,!1);if((0,i.L7)(t.bytes,a.bytes))return n;var o=h(r,n+a.length);return e(t,r,n+o.length+o.value+a.length)},m=function e(t,r){r=Array.isArray(n=r)?n.map(function(e){return d(e)}):[d(n)],t=(0,i.W_)(t);var n,a=[];if(!r.length)return a;for(var o=0;ot.length?t.length:l+u.value,f=t.subarray(l,c);(0,i.L7)(r[0],s.bytes)&&(1===r.length?a.push(f):a=a.concat(e(f,r.slice(1)))),o+=s.length+u.length+f.length}return a},b=function(e){for(var t=0,r={};t>1&63),-1!==r.indexOf(l)&&(a=o+u),o+=u+("h264"===t?1:2)}return e.subarray(0,0)},A={webm:(0,i.W_)([119,101,98,109]),matroska:(0,i.W_)([109,97,116,114,111,115,107,97]),flac:(0,i.W_)([102,76,97,67]),ogg:(0,i.W_)([79,103,103,83]),ac3:(0,i.W_)([11,119]),riff:(0,i.W_)([82,73,70,70]),avi:(0,i.W_)([65,86,73]),wav:(0,i.W_)([87,65,86,69]),"3gp":(0,i.W_)([102,116,121,112,51,103]),mp4:(0,i.W_)([102,116,121,112]),fmp4:(0,i.W_)([115,116,121,112]),mov:(0,i.W_)([102,116,121,112,113,116]),moov:(0,i.W_)([109,111,111,118]),moof:(0,i.W_)([109,111,111,102])},S={aac:function(e){var t=(0,y.A)(e);return(0,i.L7)(e,[255,16],{offset:t,mask:[255,22]})},mp3:function(e){var t=(0,y.A)(e);return(0,i.L7)(e,[255,2],{offset:t,mask:[255,6]})},webm:function(e){var t=m(e,[c.EBML,c.DocType])[0];return(0,i.L7)(t,A.webm)},mkv:function(e){var t=m(e,[c.EBML,c.DocType])[0];return(0,i.L7)(t,A.matroska)},mp4:function(e){return!(S["3gp"](e)||S.mov(e))&&(!!((0,i.L7)(e,A.mp4,{offset:4})||(0,i.L7)(e,A.fmp4,{offset:4})||(0,i.L7)(e,A.moof,{offset:4})||(0,i.L7)(e,A.moov,{offset:4}))||void 0)},mov:function(e){return(0,i.L7)(e,A.mov,{offset:4})},"3gp":function(e){return(0,i.L7)(e,A["3gp"],{offset:4})},ac3:function(e){var t=(0,y.A)(e);return(0,i.L7)(e,A.ac3,{offset:t})},ts:function(e){if(e.length<189&&e.length>=1)return 71===e[0];for(var t=0;t+1880}},3280:(e,t,r)=>{var n=r(3778).getUint64;e.exports=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),r={version:e[0],flags:new Uint8Array(e.subarray(1,4)),references:[],referenceId:t.getUint32(4),timescale:t.getUint32(8)},i=12;0===r.version?(r.earliestPresentationTime=t.getUint32(i),r.firstOffset=t.getUint32(i+4),i+=8):(r.earliestPresentationTime=n(e.subarray(i)),r.firstOffset=n(e.subarray(i+8)),i+=16),i+=2;var a=t.getUint16(i);for(i+=2;a>0;i+=12,a--)r.references.push({referenceType:(128&e[i])>>>7,referencedSize:0x7fffffff&t.getUint32(i),subsegmentDuration:t.getUint32(i+4),startsWithSap:!!(128&e[i+8]),sapType:(112&e[i+8])>>>4,sapDeltaTime:0xfffffff&t.getUint32(i+8)});return r}},3778:e=>{e.exports={getUint64:function(e){var t,r=new DataView(e.buffer,e.byteOffset,e.byteLength);return r.getBigUint64?(t=r.getBigUint64(0)){function t(){return e.exports=t=Object.assign?Object.assign.bind():function(e){for(var t=1;t{"use strict";var n=r(8202),i=r(4229),a=r(7810),o=r(400),s=r(8138);c.httpHandler=r(2037),c.requestInterceptorsStorage=new o,c.responseInterceptorsStorage=new o,c.retryManager=new s;var u=function(e){var t={};return e&&e.trim().split("\n").forEach(function(e){var r=e.indexOf(":"),n=e.slice(0,r).trim().toLowerCase(),i=e.slice(r+1).trim();void 0===t[n]?t[n]=i:Array.isArray(t[n])?t[n].push(i):t[n]=[t[n],i]}),t};function l(e,t,r){var n=e;return a(t)?(r=t,"string"==typeof e&&(n={uri:e})):n=i({},t,{uri:e}),n.callback=r,n}function c(e,t,r){return f(t=l(e,t,r))}function f(e){if(void 0===e.callback)throw Error("callback argument missing");if(e.requestType&&c.requestInterceptorsStorage.getIsEnabled()){var t,r,n,i={uri:e.uri||e.url,headers:e.headers||{},body:e.body,metadata:e.metadata||{},retry:e.retry,timeout:e.timeout},a=c.requestInterceptorsStorage.execute(e.requestType,i);e.uri=a.uri,e.headers=a.headers,e.body=a.body,e.metadata=a.metadata,e.retry=a.retry,e.timeout=a.timeout}var o=!1,s=function(t,r,n){o||(o=!0,e.callback(t,r,n))};function l(t){if(clearTimeout(n),clearTimeout(e.retryTimeout),t instanceof Error||(t=Error(""+(t||"Unknown XMLHttpRequest Error"))),t.statusCode=0,!r&&c.retryManager.getIsEnabled()&&e.retry&&e.retry.shouldRetry()){e.retryTimeout=setTimeout(function(){e.retry.moveToNextAttempt(),e.xhr=h,f(e)},e.retry.getCurrentFuzzedDelay());return}if(e.requestType&&c.responseInterceptorsStorage.getIsEnabled()){var i={headers:v.headers||{},body:v.body,responseUrl:h.responseURL,responseType:h.responseType},a=c.responseInterceptorsStorage.execute(e.requestType,i);v.body=a.body,v.headers=a.headers}return s(t,v)}function p(){if(!r){clearTimeout(n),clearTimeout(e.retryTimeout);var t,i=v,a=null;if(0!==(t=e.useXDR&&void 0===h.status?200:1223===h.status?204:h.status)?(i={body:function(){var e=void 0;if(e=h.response?h.response:h.responseText||function(e){try{if("document"===e.responseType)return e.responseXML;var t=e.responseXML&&"parsererror"===e.responseXML.documentElement.nodeName;if(""===e.responseType&&!t)return e.responseXML}catch(e){}return null}(h),E)try{e=JSON.parse(e)}catch(e){}return e}(),statusCode:t,method:g,headers:{},url:d,rawRequest:h},h.getAllResponseHeaders&&(i.headers=u(h.getAllResponseHeaders()))):a=Error("Internal XMLHttpRequest Error"),e.requestType&&c.responseInterceptorsStorage.getIsEnabled()){var o={headers:i.headers||{},body:i.body,responseUrl:h.responseURL,responseType:h.responseType},l=c.responseInterceptorsStorage.execute(e.requestType,o);i.body=l.body,i.headers=l.headers}return s(a,i,i.body)}}var h=e.xhr||null;h||(h=e.cors||e.useXDR?new c.XDomainRequest:new c.XMLHttpRequest);var d=h.url=e.uri||e.url,g=h.method=e.method||"GET",m=e.body||e.data,b=h.headers=e.headers||{},y=!!e.sync,E=!1,v={body:void 0,headers:{},statusCode:0,method:g,url:d,rawRequest:h};if("json"in e&&!1!==e.json&&(E=!0,b.accept||b.Accept||(b.Accept="application/json"),"GET"!==g&&"HEAD"!==g&&(b["content-type"]||b["Content-Type"]||(b["Content-Type"]="application/json"),m=JSON.stringify(!0===e.json?m:e.json))),h.onreadystatechange=function(){4!==h.readyState||c.responseInterceptorsStorage.getIsEnabled()||setTimeout(p,0)},h.onload=p,h.onerror=l,h.onprogress=function(){},h.onabort=function(){r=!0,clearTimeout(e.retryTimeout)},h.ontimeout=l,h.open(g,d,!y,e.username,e.password),y||(h.withCredentials=!!e.withCredentials),!y&&e.timeout>0&&(n=setTimeout(function(){if(!r){r=!0,h.abort("timeout");var e=Error("XMLHttpRequest timeout");e.code="ETIMEDOUT",l(e)}},e.timeout)),h.setRequestHeader)for(t in b)b.hasOwnProperty(t)&&h.setRequestHeader(t,b[t]);else if(e.headers&&!function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}(e.headers))throw Error("Headers cannot be set on an XDomainRequest object");return"responseType"in e&&(h.responseType=e.responseType),"beforeSend"in e&&"function"==typeof e.beforeSend&&e.beforeSend(h),h.send(m||null),h}e.exports=c,e.exports.default=c,c.XMLHttpRequest=n.XMLHttpRequest||function(){},c.XDomainRequest="withCredentials"in new c.XMLHttpRequest?c.XMLHttpRequest:n.XDomainRequest,function(e,t){for(var r=0;r{"use strict";r.d(t,{BX:()=>c,Et:()=>u,TY:()=>h,UD:()=>p,YZ:()=>d,Yg:()=>g,dv:()=>m,fz:()=>f,tB:()=>l});var n=r(8202),i=r.n(n),a={mp4:/^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,webm:/^(vp0?[89]|av0?1|opus|vorbis)/,ogg:/^(vp0?[89]|theora|flac|opus|vorbis)/,video:/^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,audio:/^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,text:/^(stpp.ttml.im1t)/,muxerVideo:/^(avc0?1)/,muxerAudio:/^(mp4a)/,muxerText:/a^/},o=["video","audio","text"],s=["Video","Audio","Text"],u=function(e){return e?e.replace(/avc1\.(\d+)\.(\d+)/i,function(e,t,r){return"avc1."+("00"+Number(t).toString(16)).slice(-2)+"00"+("00"+Number(r).toString(16)).slice(-2)}):e},l=function(e){void 0===e&&(e="");var t=e.split(","),r=[];return t.forEach(function(e){var t;e=e.trim(),o.forEach(function(n){var i=a[n].exec(e.toLowerCase());if(i&&!(i.length<=1)){t=n;var o=e.substring(0,i[1].length),s=e.replace(o,"");r.push({type:o,details:s,mediaType:n})}}),t||r.push({type:e,details:"",mediaType:"unknown"})}),r},c=function(e,t){if(!e.mediaGroups.AUDIO||!t)return null;var r=e.mediaGroups.AUDIO[t];if(!r)return null;for(var n in r){var i=r[n];if(i.default&&i.playlists)return l(i.playlists[0].attributes.CODECS)}return null},f=function(e){return void 0===e&&(e=""),a.audio.test(e.trim().toLowerCase())},p=function(e){if(e&&"string"==typeof e){var t,r=e.toLowerCase().split(",").map(function(e){return u(e.trim())}),n="video";1===r.length&&f(r[0])?n="audio":1===r.length&&(void 0===(t=r[0])&&(t=""),a.text.test(t.trim().toLowerCase()))&&(n="application");var i="mp4";return r.every(function(e){return a.mp4.test(e)})?i="mp4":r.every(function(e){return a.webm.test(e)})?i="webm":r.every(function(e){return a.ogg.test(e)})&&(i="ogg"),n+"/"+i+';codecs="'+e+'"'}},h=function(e,t){return void 0===e&&(e=""),void 0===t&&(t=!1),i().MediaSource&&i().MediaSource.isTypeSupported&&i().MediaSource.isTypeSupported(p(e))||t&&i().ManagedMediaSource&&i().ManagedMediaSource.isTypeSupported&&i().ManagedMediaSource.isTypeSupported(p(e))||!1},d=function(e){return void 0===e&&(e=""),e.toLowerCase().split(",").every(function(e){e=e.trim();for(var t=0;t{"use strict";function n(){return(n=Object.assign?Object.assign.bind():function(e){for(var t=1;tn})},5473:(e,t,r)=>{"use strict";var n=r(7925).freeze;t.XML_ENTITIES=n({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}),t.HTML_ENTITIES=n({Aacute:"\xc1",aacute:"\xe1",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"\xc2",acirc:"\xe2",acute:"\xb4",Acy:"А",acy:"а",AElig:"\xc6",aelig:"\xe6",af:"⁡",Afr:"\uD835\uDD04",afr:"\uD835\uDD1E",Agrave:"\xc0",agrave:"\xe0",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"\xc5",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"\uD835\uDD38",aopf:"\uD835\uDD52",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"\xc5",aring:"\xe5",Ascr:"\uD835\uDC9C",ascr:"\uD835\uDCB6",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"\xc3",atilde:"\xe3",Auml:"\xc4",auml:"\xe4",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"\uD835\uDD05",bfr:"\uD835\uDD1F",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"\uD835\uDD39",bopf:"\uD835\uDD53",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"\xa6",Bscr:"ℬ",bscr:"\uD835\uDCB7",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"\xc7",ccedil:"\xe7",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"\xb8",Cedilla:"\xb8",cemptyv:"⦲",cent:"\xa2",CenterDot:"\xb7",centerdot:"\xb7",Cfr:"ℭ",cfr:"\uD835\uDD20",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"\xae",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"\uD835\uDD54",coprod:"∐",Coproduct:"∐",COPY:"\xa9",copy:"\xa9",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"\uD835\uDC9E",cscr:"\uD835\uDCB8",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"\xa4",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"\xb0",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"\uD835\uDD07",dfr:"\uD835\uDD21",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"\xb4",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"\xa8",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"\xf7",divide:"\xf7",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"\uD835\uDD3B",dopf:"\uD835\uDD55",Dot:"\xa8",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"\xa8",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"\uD835\uDC9F",dscr:"\uD835\uDCB9",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"\xc9",eacute:"\xe9",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"\xca",ecirc:"\xea",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"\uD835\uDD08",efr:"\uD835\uDD22",eg:"⪚",Egrave:"\xc8",egrave:"\xe8",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"\uD835\uDD3C",eopf:"\uD835\uDD56",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"\xd0",eth:"\xf0",Euml:"\xcb",euml:"\xeb",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"\uD835\uDD09",ffr:"\uD835\uDD23",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"\uD835\uDD3D",fopf:"\uD835\uDD57",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"\xbd",frac13:"⅓",frac14:"\xbc",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"\xbe",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"\uD835\uDCBB",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"\uD835\uDD0A",gfr:"\uD835\uDD24",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"\uD835\uDD3E",gopf:"\uD835\uDD58",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"\uD835\uDCA2",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",Gt:"≫",GT:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"\xbd",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"\uD835\uDD25",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"\uD835\uDD59",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"\uD835\uDCBD",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"\xcd",iacute:"\xed",ic:"⁣",Icirc:"\xce",icirc:"\xee",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"\xa1",iff:"⇔",Ifr:"ℑ",ifr:"\uD835\uDD26",Igrave:"\xcc",igrave:"\xec",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"\uD835\uDD40",iopf:"\uD835\uDD5A",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"\xbf",Iscr:"ℐ",iscr:"\uD835\uDCBE",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"\xcf",iuml:"\xef",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"\uD835\uDD0D",jfr:"\uD835\uDD27",jmath:"ȷ",Jopf:"\uD835\uDD41",jopf:"\uD835\uDD5B",Jscr:"\uD835\uDCA5",jscr:"\uD835\uDCBF",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"\uD835\uDD0E",kfr:"\uD835\uDD28",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"\uD835\uDD42",kopf:"\uD835\uDD5C",Kscr:"\uD835\uDCA6",kscr:"\uD835\uDCC0",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"\xab",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"\uD835\uDD0F",lfr:"\uD835\uDD29",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"\uD835\uDD43",lopf:"\uD835\uDD5D",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"\uD835\uDCC1",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",Lt:"≪",LT:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"\xaf",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"\uD835\uDD10",mfr:"\uD835\uDD2A",mho:"℧",micro:"\xb5",mid:"∣",midast:"*",midcir:"⫰",middot:"\xb7",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"\uD835\uDD44",mopf:"\uD835\uDD5E",mp:"∓",Mscr:"ℳ",mscr:"\uD835\uDCC2",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:"\xa0",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"\uD835\uDD11",nfr:"\uD835\uDD2B",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:"\xa0",Nopf:"ℕ",nopf:"\uD835\uDD5F",Not:"⫬",not:"\xac",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"\uD835\uDCA9",nscr:"\uD835\uDCC3",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"\xd1",ntilde:"\xf1",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"\xd3",oacute:"\xf3",oast:"⊛",ocir:"⊚",Ocirc:"\xd4",ocirc:"\xf4",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"\uD835\uDD12",ofr:"\uD835\uDD2C",ogon:"˛",Ograve:"\xd2",ograve:"\xf2",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"\uD835\uDD46",oopf:"\uD835\uDD60",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"\xaa",ordm:"\xba",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"\uD835\uDCAA",oscr:"ℴ",Oslash:"\xd8",oslash:"\xf8",osol:"⊘",Otilde:"\xd5",otilde:"\xf5",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"\xd6",ouml:"\xf6",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"\xb6",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"\uD835\uDD13",pfr:"\uD835\uDD2D",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"\xb1",plusmn:"\xb1",plussim:"⨦",plustwo:"⨧",pm:"\xb1",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"\uD835\uDD61",pound:"\xa3",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"\uD835\uDCAB",pscr:"\uD835\uDCC5",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"\uD835\uDD14",qfr:"\uD835\uDD2E",qint:"⨌",Qopf:"ℚ",qopf:"\uD835\uDD62",qprime:"⁗",Qscr:"\uD835\uDCAC",qscr:"\uD835\uDCC6",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"\xbb",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"\xae",reg:"\xae",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"\uD835\uDD2F",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"\uD835\uDD63",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"\uD835\uDCC7",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"\xa7",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"\uD835\uDD16",sfr:"\uD835\uDD30",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"\xad",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"\uD835\uDD4A",sopf:"\uD835\uDD64",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"\uD835\uDCAE",sscr:"\uD835\uDCC8",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"\xaf",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"\xb9",sup2:"\xb2",sup3:"\xb3",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"\xdf",Tab:" ",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"\uD835\uDD17",tfr:"\uD835\uDD31",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"\xde",thorn:"\xfe",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"\xd7",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"\uD835\uDD4B",topf:"\uD835\uDD65",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"\uD835\uDCAF",tscr:"\uD835\uDCC9",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"\xda",uacute:"\xfa",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"\xdb",ucirc:"\xfb",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"\uD835\uDD18",ufr:"\uD835\uDD32",Ugrave:"\xd9",ugrave:"\xf9",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"\xa8",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"\uD835\uDD4C",uopf:"\uD835\uDD66",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"\uD835\uDCB0",uscr:"\uD835\uDCCA",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"\xdc",uuml:"\xfc",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"\uD835\uDD19",vfr:"\uD835\uDD33",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"\uD835\uDD4D",vopf:"\uD835\uDD67",vprop:"∝",vrtri:"⊳",Vscr:"\uD835\uDCB1",vscr:"\uD835\uDCCB",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"\uD835\uDD1A",wfr:"\uD835\uDD34",Wopf:"\uD835\uDD4E",wopf:"\uD835\uDD68",wp:"℘",wr:"≀",wreath:"≀",Wscr:"\uD835\uDCB2",wscr:"\uD835\uDCCC",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"\uD835\uDD1B",xfr:"\uD835\uDD35",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"\uD835\uDD4F",xopf:"\uD835\uDD69",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"\uD835\uDCB3",xscr:"\uD835\uDCCD",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"\xdd",yacute:"\xfd",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"\xa5",Yfr:"\uD835\uDD1C",yfr:"\uD835\uDD36",YIcy:"Ї",yicy:"ї",Yopf:"\uD835\uDD50",yopf:"\uD835\uDD6A",Yscr:"\uD835\uDCB4",yscr:"\uD835\uDCCE",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"\xff",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"\uD835\uDD37",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"\uD835\uDD6B",Zscr:"\uD835\uDCB5",zscr:"\uD835\uDCCF",zwj:"‍",zwnj:"‌"}),t.entityMap=t.HTML_ENTITIES},5666:e=>{var t={"":1,lr:1,rl:1},r={start:1,center:1,end:1,left:1,right:1,auto:1,"line-left":1,"line-right":1};function n(e){return"string"==typeof e&&!!r[e.toLowerCase()]&&e.toLowerCase()}function i(e,r,i){this.hasBeenReset=!1;var a="",o=!1,s=e,u=r,l=i,c=null,f="",p=!0,h="auto",d="start",g="auto",m="auto",b=100,y="center";Object.defineProperties(this,{id:{enumerable:!0,get:function(){return a},set:function(e){a=""+e}},pauseOnExit:{enumerable:!0,get:function(){return o},set:function(e){o=!!e}},startTime:{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e)throw TypeError("Start time must be set to a number.");s=e,this.hasBeenReset=!0}},endTime:{enumerable:!0,get:function(){return u},set:function(e){if("number"!=typeof e)throw TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}},text:{enumerable:!0,get:function(){return l},set:function(e){l=""+e,this.hasBeenReset=!0}},region:{enumerable:!0,get:function(){return c},set:function(e){c=e,this.hasBeenReset=!0}},vertical:{enumerable:!0,get:function(){return f},set:function(e){var r="string"==typeof e&&!!t[e.toLowerCase()]&&e.toLowerCase();if(!1===r)throw SyntaxError("Vertical: an invalid or illegal direction string was specified.");f=r,this.hasBeenReset=!0}},snapToLines:{enumerable:!0,get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}},line:{enumerable:!0,get:function(){return h},set:function(e){if("number"!=typeof e&&"auto"!==e)throw SyntaxError("Line: an invalid number or illegal string was specified.");h=e,this.hasBeenReset=!0}},lineAlign:{enumerable:!0,get:function(){return d},set:function(e){var t=n(e);t?(d=t,this.hasBeenReset=!0):console.warn("lineAlign: an invalid or illegal string was specified.")}},position:{enumerable:!0,get:function(){return g},set:function(e){if(e<0||e>100)throw Error("Position must be between 0 and 100.");g=e,this.hasBeenReset=!0}},positionAlign:{enumerable:!0,get:function(){return m},set:function(e){var t=n(e);t?(m=t,this.hasBeenReset=!0):console.warn("positionAlign: an invalid or illegal string was specified.")}},size:{enumerable:!0,get:function(){return b},set:function(e){if(e<0||e>100)throw Error("Size must be between 0 and 100.");b=e,this.hasBeenReset=!0}},align:{enumerable:!0,get:function(){return y},set:function(e){var t=n(e);if(!t)throw SyntaxError("align: an invalid or illegal alignment string was specified.");y=t,this.hasBeenReset=!0}}}),this.displayState=void 0}i.prototype.getCueAsHTML=function(){return WebVTT.convertCueToDOMTree(window,this.text)},e.exports=i},5714:e=>{!function(){var t={675:function(e,t){"use strict";t.byteLength=function(e){var t=u(e),r=t[0],n=t[1];return(r+n)*3/4-n},t.toByteArray=function(e){var t,r,a=u(e),o=a[0],s=a[1],l=new i((o+s)*3/4-s),c=0,f=s>0?o-4:o;for(r=0;r>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===s&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,l[c++]=255&t),1===s&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,a=[],o=0,s=n-i;o>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}(e,o,o+16383>s?s:o+16383));return 1===i?a.push(r[(t=e[n-1])>>2]+r[t<<4&63]+"=="):2===i&&a.push(r[(t=(e[n-2]<<8)+e[n-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),a.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,s=a.length;o0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var n=r===t?0:4-r%4;return[r,n]}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},72:function(e,t,r){"use strict";var n=r(675),i=r(783),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function o(e){if(e>0x7fffffff)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return c(e)}return u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!s.isEncoding(t))throw TypeError("Unknown encoding: "+t);var r=0|h(e,t),n=o(r),i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}(e,t);if(ArrayBuffer.isView(e))return f(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(x(e,ArrayBuffer)||e&&x(e.buffer,ArrayBuffer)||"undefined"!=typeof SharedArrayBuffer&&(x(e,SharedArrayBuffer)||e&&x(e.buffer,SharedArrayBuffer)))return function(e,t,r){var n;if(t<0||e.byteLength=0x7fffffff)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function h(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||x(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return S(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return R(e).length;default:if(i)return n?-1:S(e).length;t=(""+t).toLowerCase(),i=!0}}function d(e,t,r){var i,a,o,s=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var i="",a=t;a0x7fffffff?r=0x7fffffff:r<-0x80000000&&(r=-0x80000000),(a=r*=1)!=a&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return -1;r=e.length-1}else if(r<0){if(!i)return -1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,i);if("number"==typeof t)return(t&=255,"function"==typeof Uint8Array.prototype.indexOf)?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,i);throw TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){var a,o=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return -1;o=2,s/=2,u/=2,r/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var c=-1;for(a=r;as&&(r=s-u),a=r;a>=0;a--){for(var f=!0,p=0;pr&&(e+=" ... "),""},a&&(s.prototype[a]=s.prototype.inspect),s.prototype.compare=function(e,t,r,n,i){if(x(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var a=i-n,o=r-t,u=Math.min(a,o),l=this.slice(n,i),c=e.slice(t,r),f=0;f239?4:l>223?3:l>191?2:1;if(i+f<=r)switch(f){case 1:l<128&&(c=l);break;case 2:(192&(a=e[i+1]))==128&&(u=(31&l)<<6|63&a)>127&&(c=u);break;case 3:a=e[i+1],o=e[i+2],(192&a)==128&&(192&o)==128&&(u=(15&l)<<12|(63&a)<<6|63&o)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:a=e[i+1],o=e[i+2],s=e[i+3],(192&a)==128&&(192&o)==128&&(192&s)==128&&(u=(15&l)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,f=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=f}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);for(var r="",n=0;nr)throw RangeError("Trying to access beyond buffer length")}function v(e,t,r,n,i,a){if(!s.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw RangeError("Index out of range")}function T(e,t,r,n,i,a){if(r+n>e.length||r<0)throw RangeError("Index out of range")}function w(e,t,r,n,a){return t*=1,r>>>=0,a||T(e,t,r,4,34028234663852886e22,-34028234663852886e22),i.write(e,t,r,n,23,4),r+4}function D(e,t,r,n,a){return t*=1,r>>>=0,a||T(e,t,r,8,17976931348623157e292,-17976931348623157e292),i.write(e,t,r,n,52,8),r+8}s.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var i,a,o,s,u,l,c,f,p=this.length-t;if((void 0===r||r>p)&&(r=p),e.length>0&&(r<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var h=!1;;)switch(n){case"hex":return function(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;var a=t.length;n>a/2&&(n=a/2);for(var o=0;o>8,i.push(r%256),i.push(n);return i}(e,this.length-c),this,c,f);default:if(h)throw TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),h=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},s.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||E(e,t,this.length);for(var n=this[e],i=1,a=0;++a>>=0,t>>>=0,r||E(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},s.prototype.readUInt8=function(e,t){return e>>>=0,t||E(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+0x1000000*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),0x1000000*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||E(e,t,this.length);for(var n=this[e],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||E(e,t,this.length);for(var n=t,i=1,a=this[e+--n];n>0&&(i*=256);)a+=this[e+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},s.prototype.readInt8=function(e,t){return(e>>>=0,t||E(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||E(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?0xffff0000|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||E(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?0xffff0000|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||E(e,4,this.length),i.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||E(e,4,this.length),i.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||E(e,8,this.length),i.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||E(e,8,this.length),i.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,r,n){if(e*=1,t>>>=0,r>>>=0,!n){var i=Math.pow(2,8*r)-1;v(this,e,t,r,i,0)}var a=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,!n){var i=Math.pow(2,8*r)-1;v(this,e,t,r,i,0)}var a=r-1,o=1;for(this[t+a]=255&e;--a>=0&&(o*=256);)this[t+a]=e/o&255;return t+r},s.prototype.writeUInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,r,n){if(e*=1,t>>>=0,!n){var i=Math.pow(2,8*r-1);v(this,e,t,r,i-1,-i)}var a=0,o=1,s=0;for(this[t]=255&e;++a>0)-s&255;return t+r},s.prototype.writeIntBE=function(e,t,r,n){if(e*=1,t>>>=0,!n){var i=Math.pow(2,8*r-1);v(this,e,t,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[t+a]=255&e;--a>=0&&(o*=256);)e<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),e<0&&(e=0xffffffff+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,r){return w(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return w(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return D(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return D(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(!s.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw RangeError("Index out of range");if(n<0)throw RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--a)e[a+t]=this[a+r];else Uint8Array.prototype.set.call(e,this.subarray(r,n),t);return i},s.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw TypeError("Unknown encoding: "+n);if(1===e.length){var i,a=e.charCodeAt(0);("utf8"===n&&a<128||"latin1"===n)&&(e=a)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&r<57344){if(!i){if(r>56319||o+1===n){(t-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else if(r<1114112){if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else throw Error("Invalid code point")}return a}function N(e){for(var t=[],r=0;r=t.length)&&!(i>=e.length);++i)t[i+r]=e[i];return i}function x(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var I=function(){for(var e="0123456789abcdef",t=Array(256),r=0;r<16;++r)for(var n=16*r,i=0;i<16;++i)t[n+i]=e[r]+e[i];return t}()},783:function(e,t){t.read=function(e,t,r,n,i){var a,o,s=8*i-n-1,u=(1<>1,c=-7,f=r?i-1:0,p=r?-1:1,h=e[t+f];for(f+=p,a=h&(1<<-c)-1,h>>=-c,c+=s;c>0;a=256*a+e[t+f],f+=p,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+e[t+f],f+=p,c-=8);if(0===a)a=1-l;else{if(a===u)return o?NaN:1/0*(h?-1:1);o+=Math.pow(2,n),a-=l}return(h?-1:1)*o*Math.pow(2,a-n)},t.write=function(e,t,r,n,i,a){var o,s,u,l=8*a-i-1,c=(1<>1,p=5960464477539062e-23*(23===i),h=n?0:a-1,d=n?1:-1,g=+(t<0||0===t&&1/t<0);for(isNaN(t=Math.abs(t))||t===1/0?(s=+!!isNaN(t),o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+f>=1?t+=p/u:t+=p*Math.pow(2,1-f),t*u>=2&&(o++,u/=2),o+f>=c?(s=0,o=c):o+f>=1?(s=(t*u-1)*Math.pow(2,i),o+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;e[r+h]=255&s,h+=d,s/=256,i-=8);for(o=o<0;e[r+h]=255&o,h+=d,o/=256,l-=8);e[r+h-d]|=128*g}}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var a=r[e]={exports:{}},o=!0;try{t[e](a,a.exports,n),o=!1}finally{o&&delete r[e]}return a.exports}n.ab="//";var i=n(72);e.exports=i}()},6002:(e,t,r)=>{var n=r(770);n.DOMImplementation,n.XMLSerializer,t.DOMParser=r(8962).DOMParser},6302:(e,t,r)=>{var n=r(7925).NAMESPACE,i=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,a=RegExp("[\\-\\.0-9"+i.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),o=RegExp("^"+i.source+a.source+"*(?::"+i.source+a.source+"*)?$");function s(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,s)}function u(){}function l(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function c(e,t,r){for(var i=e.tagName,a=null,o=e.length;o--;){var s=e[o],u=s.qName,l=s.value,c=u.indexOf(":");if(c>0)var p=s.prefix=u.slice(0,c),h=u.slice(c+1),d="xmlns"===p&&h;else h=u,p=null,d="xmlns"===u&&"";s.localName=h,!1!==d&&(null==a&&(a={},f(r,r={})),r[d]=a[d]=l,s.uri=n.XMLNS,t.startPrefixMapping(d,l))}for(var o=e.length;o--;){var p=(s=e[o]).prefix;p&&("xml"===p&&(s.uri=n.XML),"xmlns"!==p&&(s.uri=r[p||""]))}var c=i.indexOf(":");c>0?(p=e.prefix=i.slice(0,c),h=e.localName=i.slice(c+1)):(p=null,h=e.localName=i);var g=e.uri=r[p||""];if(t.startElement(g,h,i,e),!e.closed)return e.currentNSMap=r,e.localNSMap=a,!0;if(t.endElement(g,h,i),a)for(p in a)Object.prototype.hasOwnProperty.call(a,p)&&t.endPrefixMapping(p)}function f(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function p(){this.attributeNames={}}s.prototype=Error(),s.prototype.name=s.name,u.prototype={parse:function(e,t,r){var i=this.domBuilder;i.startDocument(),f(t,t={}),function(e,t,r,i,a){function o(e){var t,n=e.slice(1,-1);return Object.hasOwnProperty.call(r,n)?r[n]:"#"!==n.charAt(0)?(a.error("entity not found:"+e),e):(t=parseInt(n.substr(1).replace("x","0x")))>65535?String.fromCharCode(55296+((t-=65536)>>10),56320+(1023&t)):String.fromCharCode(t)}function u(t){if(t>E){var r=e.substring(E,t).replace(/&#?\w+;/g,o);m&&f(E),i.characters(r,0,t-E),E=t}}function f(t,r){for(;t>=d&&(r=g.exec(e));)d=(h=r.index)+r[0].length,m.lineNumber++;m.columnNumber=t-h+1}for(var h=0,d=0,g=/.*(?:\r\n?|\n)|.*$/g,m=i.locator,b=[{currentNSMap:t}],y={},E=0;;){try{var v=e.indexOf("<",E);if(v<0){if(!e.substr(E).match(/^\s*$/)){var T=i.doc,w=T.createTextNode(e.substr(E));T.appendChild(w),i.currentElement=w}return}switch(v>E&&u(v),e.charAt(v+1)){case"/":var D=e.indexOf(">",v+3),A=e.substring(v+2,D).replace(/[ \t\n\r]+$/g,""),S=b.pop();D<0?(A=e.substring(v+2).replace(/[\s<].*/,""),a.error("end tag name: "+A+" is not complete:"+S.tagName),D=v+1+A.length):A.match(/\s",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);if(i)return i[0].length,r.processingInstruction(i[1],i[2]),n+2}return -1}(e,v,i);break;case"!":m&&f(v),D=function(e,t,r,n){if("-"===e.charAt(t+2)){if("-"===e.charAt(t+3)){var i=e.indexOf("--\x3e",t+4);if(i>t)return r.comment(e,t+4,i-t-4),i+3;n.error("Unclosed comment")}}else{if("CDATA["==e.substr(t+3,6)){var i=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,i-t-9),r.endCDATA(),i+3}var a=function(e,t){var r,n=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);r=i.exec(e);)if(n.push(r),r[1])return n}(e,t),o=a.length;if(o>1&&/!doctype/i.test(a[0][0])){var s=a[1][0],u=!1,l=!1;o>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],l=o>4&&a[4][0]):/^system$/i.test(a[2][0])&&(l=a[3][0]));var c=a[o-1];return r.startDTD(s,u,l),r.endDTD(),c.index+c[0].length}}return -1}(e,v,i,a);break;default:m&&f(v);var x=new p,I=b[b.length-1].currentNSMap,D=function(e,t,r,i,a,o){function s(e,t,n){r.attributeNames.hasOwnProperty(e)&&o.fatalError("Attribute "+e+" redefined"),r.addValue(e,t.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,a),n)}for(var u,l,c=++t,f=0;;){var p=e.charAt(c);switch(p){case"=":if(1===f)u=e.slice(t,c),f=3;else if(2===f)f=3;else throw Error("attribute equal must after attrName");break;case"'":case'"':if(3===f||1===f){if(1===f&&(o.warning('attribute value must after "="'),u=e.slice(t,c)),t=c+1,(c=e.indexOf(p,t))>0)s(u,l=e.slice(t,c),t-1),f=5;else throw Error("attribute value no end '"+p+"' match")}else if(4==f)s(u,l=e.slice(t,c),t),o.warning('attribute "'+u+'" missed start quot('+p+")!!"),t=c+1,f=5;else throw Error('attribute value must after "="');break;case"/":switch(f){case 0:r.setTagName(e.slice(t,c));case 5:case 6:case 7:f=7,r.closed=!0;case 4:case 1:break;case 2:r.closed=!0;break;default:throw Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),0==f&&r.setTagName(e.slice(t,c)),c;case">":switch(f){case 0:r.setTagName(e.slice(t,c));case 5:case 6:case 7:break;case 4:case 1:"/"===(l=e.slice(t,c)).slice(-1)&&(r.closed=!0,l=l.slice(0,-1));case 2:2===f&&(l=u),4==f?(o.warning('attribute "'+l+'" missed quot(")!'),s(u,l,t)):(n.isHTML(i[""])&&l.match(/^(?:disabled|checked|selected)$/i)||o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),s(l,l,t));break;case 3:throw Error("attribute value missed!!")}return c;case"\x80":p=" ";default:if(p<=" ")switch(f){case 0:r.setTagName(e.slice(t,c)),f=6;break;case 1:u=e.slice(t,c),f=2;break;case 4:var l=e.slice(t,c);o.warning('attribute "'+l+'" missed quot(")!!'),s(u,l,t);case 5:f=6}else switch(f){case 2:r.tagName,n.isHTML(i[""])&&u.match(/^(?:disabled|checked|selected)$/i)||o.warning('attribute "'+u+'" missed value!! "'+u+'" instead2!!'),s(u,u,t),t=c,f=1;break;case 5:o.warning('attribute space is required"'+u+'"!!');case 6:f=1,t=c;break;case 3:f=4,t=c;break;case 7:throw Error("elements closed character '/' and '>' must be connected to")}}c++}}(e,v,x,I,o,a),C=x.length;if(!x.closed&&function(e,t,r,n){var i=n[r];return null==i&&((i=e.lastIndexOf(""))",t),o=e.substring(t+1,a);if(/[&<]/.test(o))return/^script$/i.test(r)||(o=o.replace(/&#?\w+;/g,n)),i.characters(o,0,o.length),a}return t+1}(e,D,x.tagName,o,i):D++}}catch(e){if(e instanceof s)throw e;a.error("element parse error: "+e),D=-1}D>E?E=D:u(Math.max(v,E)+1)}}(e,t,r,i,this.errorHandler),i.endDocument()}},p.prototype={setTagName:function(e){if(!o.test(e))throw Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!o.test(e))throw Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:r}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}},t.XMLReader=u,t.ParseError=s},6368:()=>{},6450:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(2638),i=(0,n.W_)([73,68,51]),a=function(e,t){void 0===t&&(t=0);var r=(e=(0,n.W_)(e))[t+5],i=e[t+6]<<21|e[t+7]<<14|e[t+8]<<7|e[t+9];return(16&r)>>4?i+20:i+10},o=function e(t,r){return(void 0===r&&(r=0),(t=(0,n.W_)(t)).length-r<10||!(0,n.L7)(t,i,{offset:r}))?r:(r+=a(t,r),e(t,r))}},7219:(e,t,r)=>{var n=r(2667),i=Object.create||function(){function e(){}return function(t){if(1!=arguments.length)throw Error("Object.create shim only accepts one parameter.");return e.prototype=t,new e}}();function a(e,t){this.name="ParsingError",this.code=e.code,this.message=t||e.message}function o(e){function t(e,t,r,n){return(0|e)*3600+(0|t)*60+(0|r)+(0|n)/1e3}var r=e.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);return r?r[3]?t(r[1],r[2],r[3].replace(":",""),r[4]):r[1]>59?t(r[1],r[2],0,r[4]):t(0,r[1],r[2],r[4]):null}function s(){this.values=i(null)}function u(e,t,r,n){var i=n?e.split(n):[e];for(var a in i){if("string"==typeof i[a]){var o=i[a].split(r);2===o.length&&t(o[0].trim(),o[1].trim())}}}a.prototype=i(Error.prototype),a.prototype.constructor=a,a.Errors={BadSignature:{code:0,message:"Malformed WebVTT signature."},BadTimeStamp:{code:1,message:"Malformed time stamp."}},s.prototype={set:function(e,t){this.get(e)||""===t||(this.values[e]=t)},get:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},has:function(e){return e in this.values},alt:function(e,t,r){for(var n=0;n=0&&t<=100)&&(this.set(e,t),!0)}};var l=n.createElement&&n.createElement("textarea"),c={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},f={white:"rgba(255,255,255,1)",lime:"rgba(0,255,0,1)",cyan:"rgba(0,255,255,1)",red:"rgba(255,0,0,1)",yellow:"rgba(255,255,0,1)",magenta:"rgba(255,0,255,1)",blue:"rgba(0,0,255,1)",black:"rgba(0,0,0,1)"},p={v:"title",lang:"lang"},h={rt:"ruby"};function d(e,t){for(var r,n=e.document.createElement("div"),i=n,a=[];null!==(r=function(){if(!t)return null;var e,r=t.match(/^([^<]*)(<[^>]*>?)?/);return e=r[1]?r[1]:r[2],t=t.substr(e.length),e}());){if("<"===r[0]){if("/"===r[1]){a.length&&a[a.length-1]===r.substr(2).replace(">","")&&(a.pop(),i=i.parentNode);continue}var s,u,d,g,m=o(r.substr(1,r.length-2));if(m){g=e.document.createProcessingInstruction("timestamp",m),i.appendChild(g);continue}var b=r.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);if(!b||!(g=function(t,r){var n=c[t];if(!n)return null;var i=e.document.createElement(n),a=p[t];return a&&r&&(i[a]=r.trim()),i}(b[1],b[3]))||(u=i,h[(d=g).localName]&&h[d.localName]!==u.localName))continue;if(b[2]){var y=b[2].split(".");y.forEach(function(e){var t=/^bg_/.test(e),r=t?e.slice(3):e;if(f.hasOwnProperty(r)){var n=t?"background-color":"color",i=f[r];g.style[n]=i}}),g.className=y.join(" ")}a.push(b[1]),i.appendChild(g),i=g;continue}i.appendChild(e.document.createTextNode((s=r,l.innerHTML=s,s=l.textContent,l.textContent="",s)))}return n}var g=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[2084,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578],[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];function m(){}function b(e,t,r){m.call(this),this.cue=t,this.cueDiv=d(e,t.text);var n={color:"rgba(255, 255, 255, 1)",backgroundColor:"rgba(0, 0, 0, 0.8)",position:"relative",left:0,right:0,top:0,bottom:0,display:"inline",writingMode:""===t.vertical?"horizontal-tb":"lr"===t.vertical?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext"};this.applyStyles(n,this.cueDiv),this.div=e.document.createElement("div"),n={direction:function(e){var t=[],r="";if(!e||!e.childNodes)return"ltr";function n(e,t){for(var r=t.childNodes.length-1;r>=0;r--)e.push(t.childNodes[r])}for(n(t,e);r=function e(t){if(!t||!t.length)return null;var r=t.pop(),i=r.textContent||r.innerText;if(i){var a=i.match(/^.*(\n|\r)/);return a?(t.length=0,a[0]):i}return"ruby"===r.tagName?e(t):r.childNodes?(n(t,r),e(t)):void 0}(t);)for(var i=0;i=r[0]&&e<=r[1])return!0}return!1}(r.charCodeAt(i)))return"rtl";return"ltr"}(this.cueDiv),writingMode:""===t.vertical?"horizontal-tb":"lr"===t.vertical?"vertical-lr":"vertical-rl",unicodeBidi:"plaintext",textAlign:"middle"===t.align?"center":t.align,font:r.font,whiteSpace:"pre-line",position:"absolute"},this.applyStyles(n),this.div.appendChild(this.cueDiv);var i=0;switch(t.positionAlign){case"start":case"line-left":i=t.position;break;case"center":i=t.position-t.size/2;break;case"end":case"line-right":i=t.position-t.size}""===t.vertical?this.applyStyles({left:this.formatStyle(i,"%"),width:this.formatStyle(t.size,"%")}):this.applyStyles({top:this.formatStyle(i,"%"),height:this.formatStyle(t.size,"%")}),this.move=function(e){this.applyStyles({top:this.formatStyle(e.top,"px"),bottom:this.formatStyle(e.bottom,"px"),left:this.formatStyle(e.left,"px"),right:this.formatStyle(e.right,"px"),height:this.formatStyle(e.height,"px"),width:this.formatStyle(e.width,"px")})}}function y(e){var t,r,n,i;if(e.div){r=e.div.offsetHeight,n=e.div.offsetWidth,i=e.div.offsetTop;var a=(a=e.div.childNodes)&&(a=a[0])&&a.getClientRects&&a.getClientRects();e=e.div.getBoundingClientRect(),t=a?Math.max(a[0]&&a[0].height||0,e.height/a.length):0}this.left=e.left,this.right=e.right,this.top=e.top||i,this.height=e.height||r,this.bottom=e.bottom||i+(e.height||r),this.width=e.width||n,this.lineHeight=void 0!==t?t:e.lineHeight}function E(){}m.prototype.applyStyles=function(e,t){for(var r in t=t||this.div,e)e.hasOwnProperty(r)&&(t.style[r]=e[r])},m.prototype.formatStyle=function(e,t){return 0===e?0:e+t},b.prototype=i(m.prototype),b.prototype.constructor=b,y.prototype.move=function(e,t){switch(t=void 0!==t?t:this.lineHeight,e){case"+x":this.left+=t,this.right+=t;break;case"-x":this.left-=t,this.right-=t;break;case"+y":this.top+=t,this.bottom+=t;break;case"-y":this.top-=t,this.bottom-=t}},y.prototype.overlaps=function(e){return this.lefte.left&&this.tope.top},y.prototype.overlapsAny=function(e){for(var t=0;t=e.top&&this.bottom<=e.bottom&&this.left>=e.left&&this.right<=e.right},y.prototype.overlapsOppositeAxis=function(e,t){switch(t){case"+x":return this.lefte.right;case"+y":return this.tope.bottom}},y.prototype.intersectPercentage=function(e){return Math.max(0,Math.min(this.right,e.right)-Math.max(this.left,e.left))*Math.max(0,Math.min(this.bottom,e.bottom)-Math.max(this.top,e.top))/(this.height*this.width)},y.prototype.toCSSCompatValues=function(e){return{top:this.top-e.top,bottom:e.bottom-this.bottom,left:this.left-e.left,right:e.right-this.right,height:this.height,width:this.width}},y.getSimpleBoxPosition=function(e){var t=e.div?e.div.offsetHeight:e.tagName?e.offsetHeight:0,r=e.div?e.div.offsetWidth:e.tagName?e.offsetWidth:0,n=e.div?e.div.offsetTop:e.tagName?e.offsetTop:0;return{left:(e=e.div?e.div.getBoundingClientRect():e.tagName?e.getBoundingClientRect():e).left,right:e.right,top:e.top||n,height:e.height||t,bottom:e.bottom||n+(e.height||t),width:e.width||r}},E.StringDecoder=function(){return{decode:function(e){if(!e)return"";if("string"!=typeof e)throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}},E.convertCueToDOMTree=function(e,t){return e&&t?d(e,t):null},E.processCues=function(e,t,r){if(!e||!t||!r)return null;for(;r.firstChild;)r.removeChild(r.firstChild);var n=e.document.createElement("div");if(n.style.position="absolute",n.style.left="0",n.style.right="0",n.style.top="0",n.style.bottom="0",n.style.margin="1.5%",r.appendChild(n),!function(e){for(var t=0;t=0&&e.line<=100))return e.line;if(!e.track||!e.track.textTrackList||!e.track.textTrackList.mediaElement)return -1;for(var t=e.track,r=t.textTrackList,n=0,i=0;if&&(c=Math.ceil(f/l)*l*(c<0?-1:1)),o<0&&(c+=""===a.vertical?r.height:r.width,s=s.reverse()),i.move(p,c)}else{var h=i.lineHeight/r.height*100;switch(a.lineAlign){case"center":o-=h/2;break;case"end":o-=h}switch(a.vertical){case"":t.applyStyles({top:t.formatStyle(o,"%")});break;case"rl":t.applyStyles({left:t.formatStyle(o,"%")});break;case"lr":t.applyStyles({right:t.formatStyle(o,"%")})}s=["+y","-x","+x","-y"],i=new y(t)}var d=function(e,t){for(var i,a=new y(e),o=1,s=0;su&&(i=new y(e),o=u),e=new y(a)}return i||a}(i,s);t.move(d.toCSSCompatValues(r))}(0,r,o,a),i.displayState=r.div,a.push(y.getSimpleBoxPosition(r))}()},E.Parser=function(e,t,r){r||(r=t,t={}),t||(t={}),this.window=e,this.vttjs=t,this.state="INITIAL",this.buffer="",this.decoder=r||new TextDecoder("utf8"),this.regionList=[]},E.Parser.prototype={reportOrThrowError:function(e){if(e instanceof a)this.onparsingerror&&this.onparsingerror(e);else throw e},parse:function(e){var t=this;function r(){for(var e=t.buffer,r=0;r=0;i--)if(r[i].id===t){n.set(e,r[i].region);break}break;case"vertical":n.alt(e,t,["rl","lr"]);break;case"line":var a=t.split(","),o=a[0];n.integer(e,o),n.percent(e,o)&&n.set("snapToLines",!1),n.alt(e,o,["auto"]),2===a.length&&n.alt("lineAlign",a[1],["start","center","end"]);break;case"position":a=t.split(","),n.percent(e,a[0]),2===a.length&&n.alt("positionAlign",a[1],["start","center","end"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start","center","end","left","right"])}},/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");try{t.line=n.get("line","auto")}catch(e){}t.lineAlign=n.get("lineAlign","start"),t.snapToLines=n.get("snapToLines",!0),t.size=n.get("size",100);try{t.align=n.get("align","center")}catch(e){t.align=n.get("align","middle")}try{t.position=n.get("position","auto")}catch(e){t.position=n.get("position",{start:0,left:0,center:50,middle:50,end:100,right:100},t.align)}t.positionAlign=n.get("positionAlign",{start:"start",left:"start",center:"center",middle:"center",end:"end",right:"end"},t.align)}(e,t)}(i,t.cue,t.regionList)}catch(e){t.reportOrThrowError(e),t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var f=-1!==i.indexOf("--\x3e");if(!i||f&&(c=!0)){t.oncue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}t.cue.text&&(t.cue.text+="\n"),t.cue.text+=i.replace(/\u2028/g,"\n").replace(/u2029/g,"\n");continue;case"BADCUE":i||(t.state="ID");continue}}catch(e){t.reportOrThrowError(e),"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this},flush:function(){try{if(this.buffer+=this.decoder.decode(),(this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state)throw new a(a.Errors.BadSignature)}catch(e){this.reportOrThrowError(e)}return this.onflush&&this.onflush(),this}},e.exports=E},7810:e=>{e.exports=function(e){if(!e)return!1;var r=t.call(e);return"[object Function]"===r||"function"==typeof e&&"[object RegExp]"!==r||"undefined"!=typeof window&&(e===window.setTimeout||e===window.alert||e===window.confirm||e===window.prompt)};var t=Object.prototype.toString},7925:(e,t)=>{"use strict";function r(e,t){return void 0===t&&(t=Object),t&&"function"==typeof t.freeze?t.freeze(e):e}var n=r({HTML:"text/html",isHTML:function(e){return e===n.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),i=r({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===i.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});t.assign=function(e,t){if(null===e||"object"!=typeof e)throw TypeError("target is not an object");for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},t.find=function(e,t,r){if(void 0===r&&(r=Array.prototype),e&&"function"==typeof r.find)return r.find.call(e,t);for(var n=0;n{"use strict";var t=function(){function e(){this.maxAttempts_=1,this.delayFactor_=.1,this.fuzzFactor_=.1,this.initialDelay_=1e3,this.enabled_=!1}var t=e.prototype;return t.getIsEnabled=function(){return this.enabled_},t.enable=function(){this.enabled_=!0},t.disable=function(){this.enabled_=!1},t.reset=function(){this.maxAttempts_=1,this.delayFactor_=.1,this.fuzzFactor_=.1,this.initialDelay_=1e3,this.enabled_=!1},t.getMaxAttempts=function(){return this.maxAttempts_},t.setMaxAttempts=function(e){this.maxAttempts_=e},t.getDelayFactor=function(){return this.delayFactor_},t.setDelayFactor=function(e){this.delayFactor_=e},t.getFuzzFactor=function(){return this.fuzzFactor_},t.setFuzzFactor=function(e){this.fuzzFactor_=e},t.getInitialDelay=function(){return this.initialDelay_},t.setInitialDelay=function(e){this.initialDelay_=e},t.createRetry=function(e){var t=void 0===e?{}:e,n=t.maxAttempts,i=t.delayFactor,a=t.fuzzFactor,o=t.initialDelay;return new r({maxAttempts:n||this.maxAttempts_,delayFactor:i||this.delayFactor_,fuzzFactor:a||this.fuzzFactor_,initialDelay:o||this.initialDelay_})},e}(),r=function(){function e(e){this.maxAttempts_=e.maxAttempts,this.delayFactor_=e.delayFactor,this.fuzzFactor_=e.fuzzFactor,this.currentDelay_=e.initialDelay,this.currentAttempt_=1}var t=e.prototype;return t.moveToNextAttempt=function(){this.currentAttempt_++;var e=this.currentDelay_*this.delayFactor_;this.currentDelay_=this.currentDelay_+e},t.shouldRetry=function(){return this.currentAttempt_{var n;n="undefined"!=typeof window?window:void 0!==r.g?r.g:"undefined"!=typeof self?self:{},e.exports=n},8850:(e,t,r)=>{"use strict";r.d(t,{iX:()=>d});var n=function(){function e(){this.listeners={}}var t=e.prototype;return t.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},t.off=function(e,t){if(!this.listeners[e])return!1;var r=this.listeners[e].indexOf(t);return this.listeners[e]=this.listeners[e].slice(0),this.listeners[e].splice(r,1),r>-1},t.trigger=function(e){var t=this.listeners[e];if(t){if(2==arguments.length)for(var r=t.length,n=0;n-1;t=this.buffer.indexOf("\n"))this.trigger("data",this.buffer.substring(0,t)),this.buffer=this.buffer.substring(t+1)}}let s=function(e){let t=/([0-9.]*)?@?([0-9.]*)?/.exec(e||""),r={};return t[1]&&(r.length=parseInt(t[1],10)),t[2]&&(r.offset=parseInt(t[2],10)),r},u=function(e){let t;let r={};if(!e)return r;let n=e.split(RegExp('(?:^|,)((?:[^=]*)=(?:"[^"]*"|[^,]*))')),i=n.length;for(;i--;)""!==n[i]&&((t=/([^=]*)=(.*)/.exec(n[i]).slice(1))[0]=t[0].replace(/^\s+|\s+$/g,""),t[1]=t[1].replace(/^\s+|\s+$/g,""),t[1]=t[1].replace(/^['"](.*)['"]$/g,"$1"),r[t[0]]=t[1]);return r},l=e=>{let t=e.split("x"),r={};return t[0]&&(r.width=parseInt(t[0],10)),t[1]&&(r.height=parseInt(t[1],10)),r};class c extends n{constructor(){super(),this.customParsers=[],this.tagMappers=[]}push(e){let t,r;if(0!==(e=e.trim()).length){if("#"!==e[0]){this.trigger("data",{type:"uri",uri:e});return}this.tagMappers.reduce((t,r)=>{let n=r(e);return n===e?t:t.concat([n])},[e]).forEach(e=>{for(let t=0;te),this.customParsers.push(i=>{if(e.exec(i))return this.trigger("data",{type:"custom",data:r(i),customType:t,segment:n}),!0})}addTagMapper({expression:e,map:t}){this.tagMappers.push(r=>e.test(r)?t(r):r)}}let f=e=>e.toLowerCase().replace(/-(\w)/g,e=>e[1].toUpperCase()),p=function(e){let t={};return Object.keys(e).forEach(function(r){t[f(r)]=e[r]}),t},h=function(e){let{serverControl:t,targetDuration:r,partTargetDuration:n}=e;if(!t)return;let i="#EXT-X-SERVER-CONTROL",a="holdBack",o="partHoldBack",s=r&&3*r,u=n&&2*n;r&&!t.hasOwnProperty(a)&&(t[a]=s,this.trigger("info",{message:`${i} defaulting HOLD-BACK to targetDuration * 3 (${s}).`})),s&&t[a]{!u.uri&&(u.parts||u.preloadHints)&&(!u.map&&t&&(u.map=t),!u.key&&r&&(u.key=r),u.timeline||"number"!=typeof g||(u.timeline=g),this.manifest.preloadSegment=u)}),this.parseStream.on("data",function(e){let o,c;if(n.manifest.definitions){for(let t in n.manifest.definitions)if(e.uri&&(e.uri=e.uri.replace(`{$${t}}`,n.manifest.definitions[t])),e.attributes)for(let r in e.attributes)"string"==typeof e.attributes[r]&&(e.attributes[r]=e.attributes[r].replace(`{$${t}}`,n.manifest.definitions[t]))}({tag(){(({version(){e.version&&(this.manifest.version=e.version)},"allow-cache"(){this.manifest.allowCache=e.allowed,"allowed"in e||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange(){let t={};"length"in e&&(u.byterange=t,t.length=e.length,"offset"in e||(e.offset=m)),"offset"in e&&(u.byterange=t,t.offset=e.offset),m=t.offset+t.length},endlist(){this.manifest.endList=!0},inf(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),"discontinuitySequence"in this.manifest||(this.manifest.discontinuitySequence=0,this.trigger("info",{message:"defaulting discontinuity sequence to zero"})),e.title&&(u.title=e.title),e.duration>0&&(u.duration=e.duration),0===e.duration&&(u.duration=.01,this.trigger("info",{message:"updating zero segment duration to a small value"})),this.manifest.segments=s},key(){if(!e.attributes){this.trigger("warn",{message:"ignoring key declaration without attribute list"});return}if("NONE"===e.attributes.METHOD){r=null;return}if(!e.attributes.URI){this.trigger("warn",{message:"ignoring key declaration without URI"});return}if("com.apple.streamingkeydelivery"===e.attributes.KEYFORMAT){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.apple.fps.1_0"]={attributes:e.attributes};return}if("com.microsoft.playready"===e.attributes.KEYFORMAT){this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.microsoft.playready"]={uri:e.attributes.URI};return}if("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"===e.attributes.KEYFORMAT){if(-1===["SAMPLE-AES","SAMPLE-AES-CTR","SAMPLE-AES-CENC"].indexOf(e.attributes.METHOD)){this.trigger("warn",{message:"invalid key method provided for Widevine"});return}if("SAMPLE-AES-CENC"===e.attributes.METHOD&&this.trigger("warn",{message:"SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead"}),"data:text/plain;base64,"!==e.attributes.URI.substring(0,23)){this.trigger("warn",{message:"invalid key URI provided for Widevine"});return}if(!(e.attributes.KEYID&&"0x"===e.attributes.KEYID.substring(0,2))){this.trigger("warn",{message:"invalid key ID provided for Widevine"});return}this.manifest.contentProtection=this.manifest.contentProtection||{},this.manifest.contentProtection["com.widevine.alpha"]={attributes:{schemeIdUri:e.attributes.KEYFORMAT,keyId:e.attributes.KEYID.substring(2)},pssh:(0,a.A)(e.attributes.URI.split(",")[1])};return}e.attributes.METHOD||this.trigger("warn",{message:"defaulting key method to AES-128"}),r={method:e.attributes.METHOD||"AES-128",uri:e.attributes.URI},void 0!==e.attributes.IV&&(r.iv=e.attributes.IV)},"media-sequence"(){if(!isFinite(e.number)){this.trigger("warn",{message:"ignoring invalid media sequence: "+e.number});return}this.manifest.mediaSequence=e.number},"discontinuity-sequence"(){if(!isFinite(e.number)){this.trigger("warn",{message:"ignoring invalid discontinuity sequence: "+e.number});return}this.manifest.discontinuitySequence=e.number,g=e.number},"playlist-type"(){if(!/VOD|EVENT/.test(e.playlistType)){this.trigger("warn",{message:"ignoring unknown playlist type: "+e.playlist});return}this.manifest.playlistType=e.playlistType},map(){t={},e.uri&&(t.uri=e.uri),e.byterange&&(t.byterange=e.byterange),r&&(t.key=r)},"stream-inf"(){if(this.manifest.playlists=s,this.manifest.mediaGroups=this.manifest.mediaGroups||d,!e.attributes){this.trigger("warn",{message:"ignoring empty stream-inf attributes"});return}u.attributes||(u.attributes={}),(0,i.A)(u.attributes,e.attributes)},media(){if(this.manifest.mediaGroups=this.manifest.mediaGroups||d,!(e.attributes&&e.attributes.TYPE&&e.attributes["GROUP-ID"]&&e.attributes.NAME)){this.trigger("warn",{message:"ignoring incomplete or missing media group"});return}let t=this.manifest.mediaGroups[e.attributes.TYPE];t[e.attributes["GROUP-ID"]]=t[e.attributes["GROUP-ID"]]||{},o=t[e.attributes["GROUP-ID"]],(c={default:/yes/i.test(e.attributes.DEFAULT)}).default?c.autoselect=!0:c.autoselect=/yes/i.test(e.attributes.AUTOSELECT),e.attributes.LANGUAGE&&(c.language=e.attributes.LANGUAGE),e.attributes.URI&&(c.uri=e.attributes.URI),e.attributes["INSTREAM-ID"]&&(c.instreamId=e.attributes["INSTREAM-ID"]),e.attributes.CHARACTERISTICS&&(c.characteristics=e.attributes.CHARACTERISTICS),e.attributes.FORCED&&(c.forced=/yes/i.test(e.attributes.FORCED)),o[e.attributes.NAME]=c},discontinuity(){g+=1,u.discontinuity=!0,this.manifest.discontinuityStarts.push(s.length)},"program-date-time"(){void 0===this.manifest.dateTimeString&&(this.manifest.dateTimeString=e.dateTimeString,this.manifest.dateTimeObject=e.dateTimeObject),u.dateTimeString=e.dateTimeString,u.dateTimeObject=e.dateTimeObject;let{lastProgramDateTime:t}=this;this.lastProgramDateTime=new Date(e.dateTimeString).getTime(),null===t&&this.manifest.segments.reduceRight((e,t)=>(t.programDateTime=e-1e3*t.duration,t.programDateTime),this.lastProgramDateTime)},targetduration(){if(!isFinite(e.duration)||e.duration<0){this.trigger("warn",{message:"ignoring invalid target duration: "+e.duration});return}this.manifest.targetDuration=e.duration,h.call(this,this.manifest)},start(){if(!e.attributes||isNaN(e.attributes["TIME-OFFSET"])){this.trigger("warn",{message:"ignoring start declaration without appropriate attribute list"});return}this.manifest.start={timeOffset:e.attributes["TIME-OFFSET"],precise:e.attributes.PRECISE}},"cue-out"(){u.cueOut=e.data},"cue-out-cont"(){u.cueOutCont=e.data},"cue-in"(){u.cueIn=e.data},skip(){this.manifest.skip=p(e.attributes),this.warnOnMissingAttributes_("#EXT-X-SKIP",e.attributes,["SKIPPED-SEGMENTS"])},part(){l=!0;let t=this.manifest.segments.length,r=p(e.attributes);u.parts=u.parts||[],u.parts.push(r),r.byterange&&(r.byterange.hasOwnProperty("offset")||(r.byterange.offset=b),b=r.byterange.offset+r.byterange.length);let n=u.parts.length-1;this.warnOnMissingAttributes_(`#EXT-X-PART #${n} for segment #${t}`,e.attributes,["URI","DURATION"]),this.manifest.renditionReports&&this.manifest.renditionReports.forEach((e,t)=>{e.hasOwnProperty("lastPart")||this.trigger("warn",{message:`#EXT-X-RENDITION-REPORT #${t} lacks required attribute(s): LAST-PART`})})},"server-control"(){let t=this.manifest.serverControl=p(e.attributes);t.hasOwnProperty("canBlockReload")||(t.canBlockReload=!1,this.trigger("info",{message:"#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false"})),h.call(this,this.manifest),t.canSkipDateranges&&!t.hasOwnProperty("canSkipUntil")&&this.trigger("warn",{message:"#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set"})},"preload-hint"(){let t=this.manifest.segments.length,r=p(e.attributes),n=r.type&&"PART"===r.type;u.preloadHints=u.preloadHints||[],u.preloadHints.push(r),r.byterange&&!r.byterange.hasOwnProperty("offset")&&(r.byterange.offset=n?b:0,n&&(b=r.byterange.offset+r.byterange.length));let i=u.preloadHints.length-1;if(this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${i} for segment #${t}`,e.attributes,["TYPE","URI"]),r.type)for(let e=0;ee.id===r.id);this.manifest.dateRanges[e]=(0,i.A)(this.manifest.dateRanges[e],r),y[r.id]=(0,i.A)(y[r.id],r),this.manifest.dateRanges.pop()}else y[r.id]=r},"independent-segments"(){this.manifest.independentSegments=!0},"i-frames-only"(){this.manifest.iFramesOnly=!0,this.requiredCompatibilityversion(this.manifest.version,4)},"content-steering"(){this.manifest.contentSteering=p(e.attributes),this.warnOnMissingAttributes_("#EXT-X-CONTENT-STEERING",e.attributes,["SERVER-URI"])},define(){this.manifest.definitions=this.manifest.definitions||{};let t=(e,t)=>{if(e in this.manifest.definitions){this.trigger("error",{message:`EXT-X-DEFINE: Duplicate name ${e}`});return}this.manifest.definitions[e]=t};if("QUERYPARAM"in e.attributes){if("NAME"in e.attributes||"IMPORT"in e.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}let r=this.params.get(e.attributes.QUERYPARAM);if(!r){this.trigger("error",{message:`EXT-X-DEFINE: No query param ${e.attributes.QUERYPARAM}`});return}t(e.attributes.QUERYPARAM,decodeURIComponent(r));return}if("NAME"in e.attributes){if("IMPORT"in e.attributes){this.trigger("error",{message:"EXT-X-DEFINE: Invalid attributes"});return}if(!("VALUE"in e.attributes)||"string"!=typeof e.attributes.VALUE){this.trigger("error",{message:`EXT-X-DEFINE: No value for ${e.attributes.NAME}`});return}t(e.attributes.NAME,e.attributes.VALUE);return}if("IMPORT"in e.attributes){if(!this.mainDefinitions[e.attributes.IMPORT]){this.trigger("error",{message:`EXT-X-DEFINE: No value ${e.attributes.IMPORT} to import, or IMPORT used on main playlist`});return}t(e.attributes.IMPORT,this.mainDefinitions[e.attributes.IMPORT]);return}this.trigger("error",{message:"EXT-X-DEFINE: No attribute"})},"i-frame-playlist"(){this.manifest.iFramePlaylists.push({attributes:e.attributes,uri:e.uri,timeline:g}),this.warnOnMissingAttributes_("#EXT-X-I-FRAME-STREAM-INF",e.attributes,["BANDWIDTH","URI"])}})[e.tagType]||f).call(n)},uri(){u.uri=e.uri,s.push(u),!this.manifest.targetDuration||"duration"in u||(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),u.duration=this.manifest.targetDuration),r&&(u.key=r),u.timeline=g,t&&(u.map=t),b=0,null!==this.lastProgramDateTime&&(u.programDateTime=this.lastProgramDateTime,this.lastProgramDateTime+=1e3*u.duration),u={}},comment(){},custom(){e.segment?(u.custom=u.custom||{},u.custom[e.customType]=e.data):(this.manifest.custom=this.manifest.custom||{},this.manifest.custom[e.customType]=e.data)}})[e.type].call(n)})}requiredCompatibilityversion(e,t){(e{var n=r(7925),i=r(770),a=r(5473),o=r(6302),s=i.DOMImplementation,u=n.NAMESPACE,l=o.ParseError,c=o.XMLReader;function f(e){return e.replace(/\r[\n\u0085]/g,"\n").replace(/[\r\u0085\u2028]/g,"\n")}function p(e){this.options=e||{locator:{}}}function h(){this.cdata=!1}function d(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}function g(e){if(e)return"\n@"+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function m(e,t,r){return"string"==typeof e?e.substr(t,r):e.length>=t+r||t?new java.lang.String(e,t,r)+"":e}function b(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}p.prototype.parseFromString=function(e,t){var r=this.options,n=new c,i=r.domBuilder||new h,o=r.errorHandler,s=r.locator,l=r.xmlns||{},p=/\/x?html?$/.test(t),d=p?a.HTML_ENTITIES:a.XML_ENTITIES;s&&i.setDocumentLocator(s),n.errorHandler=function(e,t,r){if(!e){if(t instanceof h)return t;e=t}var n={},i=e instanceof Function;function a(t){var a=e[t];!a&&i&&(a=2==e.length?function(r){e(t,r)}:e),n[t]=a&&function(e){a("[xmldom "+t+"] "+e+g(r))}||function(){}}return r=r||{},a("warning"),a("error"),a("fatalError"),n}(o,i,s),n.domBuilder=r.domBuilder||i,p&&(l[""]=u.HTML),l.xml=l.xml||u.XML;var m=r.normalizeLineEndings||f;return e&&"string"==typeof e?n.parse(m(e),l,d):n.errorHandler.error("invalid doc source"),i.doc},h.prototype={startDocument:function(){this.doc=new s().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,a=i.createElementNS(e,r||t),o=n.length;b(this,a),this.currentElement=a,this.locator&&d(this.locator,a);for(var s=0;s{"use strict";r.d(t,{A:()=>o});var n=r(8202),i=r.n(n),a=r(5714).Buffer;function o(e){for(var t=i().atob?i().atob(e):a.from(e,"base64").toString("binary"),r=new Uint8Array(t.length),n=0;n{"use strict";r.d(t,{I:()=>a});var n=/^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i,i=/^application\/dash\+xml/i,a=function(e){return n.test(e)?"hls":i.test(e)?"dash":"application/vnd.videojs.vhs+json"===e?"vhs-json":null}},9512:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var n=r(8202),i=r.n(n),a="https://example.com";let o=function(e,t){if(/^[a-z]+:/i.test(t))return t;/^data:/.test(e)&&(e=i().location&&i().location.href||"");var r=/^\/\//.test(e),n=!i().location&&!/\/\//i.test(e),o=new URL(t,e=new(i()).URL(e,i().location||a));return n?o.href.slice(a.length):r?o.href.slice(o.protocol.length):o.href}}}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/9cb54ea0-3a1872b9717ef868.js b/services/v1/media/feedback/static/_next/static/chunks/9cb54ea0-3a1872b9717ef868.js new file mode 100644 index 0000000000000000000000000000000000000000..95ceb9edc5aaee3474450faba45540a061ec2459 --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/9cb54ea0-3a1872b9717ef868.js @@ -0,0 +1,34 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[742],{1935:(e,t,i)=>{let s,r,n,a,o,l;i.d(t,{A:()=>rk});var h=i(8202),d=i.n(h),u=i(2667),c=i.n(u),p=i(4388),m=i.n(p),g=i(364),f=i.n(g),_=i(5407),y=i(9512),v=i(8850),b=i(5231),T=i(9484),S=i(2638),k=i(559),C=i(3280),w=i.n(C),E=i(6450),x=i(2678),I=i(1082),P="8.21.0";let A={},L=function(e,t){return A[e]=A[e]||[],t&&(A[e]=A[e].concat(t)),A[e]},D=function(e,t){let i=L(e).indexOf(t);return!(i<=-1)&&(A[e]=A[e].slice(),A[e].splice(i,1),!0)},O={prefixed:!0},M=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror","fullscreen"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror","-webkit-full-screen"]],U=M[0];for(let e=0;e(s,r,n)=>{let a=t.levels[r],o=RegExp(`^(${a})$`),l=e;if("log"!==s&&n.unshift(s.toUpperCase()+":"),i&&(l=`%c${e}`,n.unshift(i)),n.unshift(l+":"),R){R.push([].concat(n));let e=R.length-1e3;R.splice(0,e>0?e:0)}if(!d().console)return;let h=d().console[s];h||"debug"!==s||(h=d().console.info||d().console.log),h&&a&&o.test(s)&&h[Array.isArray(n)?"apply":"call"](d().console,n)},N=function e(t,i=":",s=""){let r,n="info";function a(...e){r("log",n,e)}return r=B(t,a,s),a.createLogger=(r,n,a)=>{let o=void 0!==n?n:i;return e(`${t} ${o} ${r}`,o,void 0!==a?a:s)},a.createNewLogger=(t,i,s)=>e(t,i,s),a.levels={all:"debug|log|warn|error",off:"",debug:"debug|log|warn|error",info:"log|warn|error",warn:"warn|error",error:"error",DEFAULT:n},a.level=e=>{if("string"==typeof e){if(!a.levels.hasOwnProperty(e))throw Error(`"${e}" in not a valid log level`);n=e}return n},a.history=()=>R?[].concat(R):[],a.history.filter=e=>(R||[]).filter(t=>RegExp(`.*${e}.*`).test(t[0])),a.history.clear=()=>{R&&(R.length=0)},a.history.disable=()=>{null!==R&&(R.length=0,R=null)},a.history.enable=()=>{null===R&&(R=[])},a.error=(...e)=>r("error",n,e),a.warn=(...e)=>r("warn",n,e),a.debug=(...e)=>r("debug",n,e),a}("VIDEOJS"),j=N.createLogger,F=Object.prototype.toString,$=function(e){return V(e)?Object.keys(e):[]};function q(e,t){$(e).forEach(i=>t(e[i],i))}function H(e,t,i=0){return $(e).reduce((i,s)=>t(i,e[s],s),i)}function V(e){return!!e&&"object"==typeof e}function z(e){return V(e)&&"[object Object]"===F.call(e)&&e.constructor===Object}function W(...e){let t={};return e.forEach(e=>{e&&q(e,(e,i)=>{if(!z(e)){t[i]=e;return}z(t[i])||(t[i]={}),t[i]=W(t[i],e)})}),t}function G(e={}){let t=[];for(let i in e)if(e.hasOwnProperty(i)){let s=e[i];t.push(s)}return t}function K(e,t,i,s=!0){let r=i=>Object.defineProperty(e,t,{value:i,enumerable:!0,writable:!0}),n={configurable:!0,enumerable:!0,get(){let e=i();return r(e),e}};return s&&(n.set=r),Object.defineProperty(e,t,n)}var Q=Object.freeze({__proto__:null,each:q,reduce:H,isObject:V,isPlain:z,merge:W,values:G,defineLazyProperty:K});let Y=!1,X=null,J=!1,Z=!1,ee=!1,et=!1,ei=!1,es=null,er=null,en=!!(d().cast&&d().cast.framework&&d().cast.framework.CastReceiverContext),ea=null,eo=!1,el=!1,eh=!1,ed=!1,eu=!1,ec=!1,ep=!1,em=!!(eb()&&("ontouchstart"in d()||d().navigator.maxTouchPoints||d().DocumentTouch&&d().document instanceof d().DocumentTouch)),eg=d().navigator&&d().navigator.userAgentData;if(eg&&eg.platform&&eg.brands&&(J="Android"===eg.platform,ee=!!eg.brands.find(e=>"Microsoft Edge"===e.brand),et=!!eg.brands.find(e=>"Chromium"===e.brand),ei=!ee&&et,es=er=(eg.brands.find(e=>"Chromium"===e.brand)||{}).version||null,el="Windows"===eg.platform),!et){let e=d().navigator&&d().navigator.userAgent||"";Y=/iPod/i.test(e),X=function(){let t=e.match(/OS (\d+)_/i);return t&&t[1]?t[1]:null}(),J=/Android/i.test(e),r=function(){let t=e.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!t)return null;let i=t[1]&&parseFloat(t[1]),s=t[2]&&parseFloat(t[2]);return i&&s?parseFloat(t[1]+"."+t[2]):i||null}(),Z=/Firefox/i.test(e),ee=/Edg/i.test(e),et=/Chrome/i.test(e)||/CriOS/i.test(e),ei=!ee&&et,es=er=function(){let t=e.match(/(Chrome|CriOS)\/(\d+)/);return t&&t[2]?parseFloat(t[2]):null}(),ea=function(){let t=/MSIE\s(\d+)\.\d/.exec(e),i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(e)&&/rv:11.0/.test(e)&&(i=11),i}(),eu=/Tizen/i.test(e),ec=/Web0S/i.test(e),ep=eu||ec,eo=/Safari/i.test(e)&&!ei&&!J&&!ee&&!ep,el=/Windows/i.test(e),eh=/iPad/i.test(e)||eo&&em&&!/iPhone/i.test(e),ed=/iPhone/i.test(e)&&!eh}let ef=ed||eh||Y,e_=(eo||ef)&&!ei;var ey=Object.freeze({__proto__:null,get IS_IPOD(){return Y},get IOS_VERSION(){return X},get IS_ANDROID(){return J},get ANDROID_VERSION(){return r},get IS_FIREFOX(){return Z},get IS_EDGE(){return ee},get IS_CHROMIUM(){return et},get IS_CHROME(){return ei},get CHROMIUM_VERSION(){return es},get CHROME_VERSION(){return er},IS_CHROMECAST_RECEIVER:en,get IE_VERSION(){return ea},get IS_SAFARI(){return eo},get IS_WINDOWS(){return el},get IS_IPAD(){return eh},get IS_IPHONE(){return ed},get IS_TIZEN(){return eu},get IS_WEBOS(){return ec},get IS_SMART_TV(){return ep},TOUCH_ENABLED:em,IS_IOS:ef,IS_ANY_SAFARI:e_});function ev(e){return"string"==typeof e&&!!e.trim()}function eb(){return c()===d().document}function eT(e){return V(e)&&1===e.nodeType}function eS(){try{return d().parent!==d().self}catch(e){return!0}}function ek(e){return function(t,i){if(!ev(t))return c()[e](null);ev(i)&&(i=c().querySelector(i));let s=eT(i)?i:c();return s[e]&&s[e](t)}}function eC(e="div",t={},i={},s){let r=c().createElement(e);return Object.getOwnPropertyNames(t).forEach(function(e){let i=t[e];"textContent"===e?ew(r,i):(r[e]!==i||"tabIndex"===e)&&(r[e]=i)}),Object.getOwnPropertyNames(i).forEach(function(e){r.setAttribute(e,i[e])}),s&&eV(r,s),r}function ew(e,t){return void 0===e.textContent?e.innerText=t:e.textContent=t,e}function eE(e,t){t.firstChild?t.insertBefore(e,t.firstChild):t.appendChild(e)}function ex(e,t){return!function(e){if(e.indexOf(" ")>=0)throw Error("class has illegal whitespace characters")}(t),e.classList.contains(t)}function eI(e,...t){return e.classList.add(...t.reduce((e,t)=>e.concat(t.split(/\s+/)),[])),e}function eP(e,...t){return e?(e.classList.remove(...t.reduce((e,t)=>e.concat(t.split(/\s+/)),[])),e):(N.warn("removeClass was called with an element that doesn't exist"),null)}function eA(e,t,i){return"function"==typeof i&&(i=i(e,t)),"boolean"!=typeof i&&(i=void 0),t.split(/\s+/).forEach(t=>e.classList.toggle(t,i)),e}function eL(e,t){Object.getOwnPropertyNames(t).forEach(function(i){let s=t[i];null==s||!1===s?e.removeAttribute(i):e.setAttribute(i,!0===s?"":s)})}function eD(e){let t={},i=["autoplay","controls","playsinline","loop","muted","default","defaultMuted"];if(e&&e.attributes&&e.attributes.length>0){let s=e.attributes;for(let e=s.length-1;e>=0;e--){let r=s[e].name,n=s[e].value;i.includes(r)&&(n=null!==n),t[r]=n}}return t}function eO(e,t){return e.getAttribute(t)}function eM(e,t,i){e.setAttribute(t,i)}function eU(e,t){e.removeAttribute(t)}function eR(){c().body.focus(),c().onselectstart=function(){return!1}}function eB(){c().onselectstart=function(){return!0}}function eN(e){if(e&&e.getBoundingClientRect&&e.parentNode){let t=e.getBoundingClientRect(),i={};return["bottom","height","left","right","top","width"].forEach(e=>{void 0!==t[e]&&(i[e]=t[e])}),i.height||(i.height=parseFloat(eQ(e,"height"))),i.width||(i.width=parseFloat(eQ(e,"width"))),i}}function ej(e){if(!e||e&&!e.offsetParent)return{left:0,top:0,width:0,height:0};let t=e.offsetWidth,i=e.offsetHeight,s=0,r=0;for(;e.offsetParent&&e!==c()[O.fullscreenElement];)s+=e.offsetLeft,r+=e.offsetTop,e=e.offsetParent;return{left:s,top:r,width:t,height:i}}function eF(e,t){let i={x:0,y:0};if(ef){let t=e;for(;t&&"html"!==t.nodeName.toLowerCase();){let e=eQ(t,"transform");if(/^matrix/.test(e)){let t=e.slice(7,-1).split(/,\s/).map(Number);i.x+=t[4],i.y+=t[5]}else if(/^matrix3d/.test(e)){let t=e.slice(9,-1).split(/,\s/).map(Number);i.x+=t[12],i.y+=t[13]}if(t.assignedSlot&&t.assignedSlot.parentElement&&d().WebKitCSSMatrix){let e=d().getComputedStyle(t.assignedSlot.parentElement).transform,s=new(d()).WebKitCSSMatrix(e);i.x+=s.m41,i.y+=s.m42}t=t.parentNode||t.host}}let s={},r=ej(t.target),n=ej(e),a=n.width,o=n.height,l=t.offsetY-(n.top-r.top),h=t.offsetX-(n.left-r.left);return t.changedTouches&&(h=t.changedTouches[0].pageX-n.left,l=t.changedTouches[0].pageY+n.top,ef&&(h-=i.x,l-=i.y)),s.y=1-Math.max(0,Math.min(1,l/o)),s.x=Math.max(0,Math.min(1,h/a)),s}function e$(e){return V(e)&&3===e.nodeType}function eq(e){for(;e.firstChild;)e.removeChild(e.firstChild);return e}function eH(e){return"function"==typeof e&&(e=e()),(Array.isArray(e)?e:[e]).map(e=>("function"==typeof e&&(e=e()),eT(e)||e$(e))?e:"string"==typeof e&&/\S/.test(e)?c().createTextNode(e):void 0).filter(e=>e)}function eV(e,t){return eH(t).forEach(t=>e.appendChild(t)),e}function ez(e,t){return eV(eq(e),t)}function eW(e){return void 0===e.button&&void 0===e.buttons||0===e.button&&void 0===e.buttons||"mouseup"===e.type&&0===e.button&&0===e.buttons||"mousedown"===e.type&&0===e.button&&0===e.buttons||0===e.button&&1===e.buttons}let eG=ek("querySelector"),eK=ek("querySelectorAll");function eQ(e,t){if(!e||!t)return"";if("function"==typeof d().getComputedStyle){let i;try{i=d().getComputedStyle(e)}catch(e){return""}return i?i.getPropertyValue(t)||i[t]:""}return""}function eY(e){[...c().styleSheets].forEach(t=>{try{let i=[...t.cssRules].map(e=>e.cssText).join(""),s=c().createElement("style");s.textContent=i,e.document.head.appendChild(s)}catch(s){let i=c().createElement("link");i.rel="stylesheet",i.type=t.type,i.media=t.media.mediaText,i.href=t.href,e.document.head.appendChild(i)}})}var eX=Object.freeze({__proto__:null,isReal:eb,isEl:eT,isInFrame:eS,createEl:eC,textContent:ew,prependTo:eE,hasClass:ex,addClass:eI,removeClass:eP,toggleClass:eA,setAttributes:eL,getAttributes:eD,getAttribute:eO,setAttribute:eM,removeAttribute:eU,blockTextSelection:eR,unblockTextSelection:eB,getBoundingClientRect:eN,findPosition:ej,getPointerPosition:eF,isTextNode:e$,emptyEl:eq,normalizeContent:eH,appendContent:eV,insertContent:ez,isSingleLeftClick:eW,$:eG,$$:eK,computedStyle:eQ,copyStyleSheetsToWindow:eY});let eJ=!1,eZ=function(){if(!1===n.options.autoSetup)return;let e=Array.prototype.slice.call(c().getElementsByTagName("video")),t=Array.prototype.slice.call(c().getElementsByTagName("audio")),i=Array.prototype.slice.call(c().getElementsByTagName("video-js")),s=e.concat(t,i);if(s&&s.length>0)for(let e=0,t=s.length;e-1&&(i={passive:!0}),e.addEventListener(t,s.dispatcher,i)}else e.attachEvent&&e.attachEvent("on"+t,s.dispatcher)}}function ti(e,t,i){if(!e8.has(e))return;let s=e8.get(e);if(!s.handlers)return;if(Array.isArray(t))return e6(ti,e,t,i);let r=function(e,t){s.handlers[t]=[],e3(e,t)};if(void 0===t){for(let t in s.handlers)Object.prototype.hasOwnProperty.call(s.handlers||{},t)&&r(e,t);return}let n=s.handlers[t];if(n){if(!i){r(e,t);return}if(i.guid)for(let e=0;e=t&&(e(...s),i=r)}},th=function(e,t,i,s=d()){let r;let n=function(){let n=this,a=arguments,o=function(){r=null,o=null,i||e.apply(n,a)};!r&&i&&e.apply(n,a),s.clearTimeout(r),r=s.setTimeout(o,t)};return n.cancel=()=>{s.clearTimeout(r),r=null},n};var td=Object.freeze({__proto__:null,UPDATE_REFRESH_INTERVAL:30,bind_:to,throttle:tl,debounce:th});class tu{on(e,t){let i=this.addEventListener;this.addEventListener=()=>{},tt(this,e,t),this.addEventListener=i}off(e,t){ti(this,e,t)}one(e,t){let i=this.addEventListener;this.addEventListener=()=>{},tr(this,e,t),this.addEventListener=i}any(e,t){let i=this.addEventListener;this.addEventListener=()=>{},tn(this,e,t),this.addEventListener=i}trigger(e){let t=e.type||e;"string"==typeof e&&(e={type:t}),e=e7(e),this.allowedEvents_[t]&&this["on"+t]&&this["on"+t](e),ts(this,e)}queueTrigger(e){o||(o=new Map);let t=e.type||e,i=o.get(this);i||(i=new Map,o.set(this,i));let s=i.get(t);i.delete(t),d().clearTimeout(s);let r=d().setTimeout(()=>{i.delete(t),0===i.size&&(i=null,o.delete(this)),this.trigger(e)},0);i.set(t,r)}}tu.prototype.allowedEvents_={},tu.prototype.addEventListener=tu.prototype.on,tu.prototype.removeEventListener=tu.prototype.off,tu.prototype.dispatchEvent=tu.prototype.trigger;let tc=e=>"function"==typeof e.name?e.name():"string"==typeof e.name?e.name:e.name_?e.name_:e.constructor&&e.constructor.name?e.constructor.name:typeof e,tp=e=>e instanceof tu||!!e.eventBusEl_&&["on","one","off","trigger"].every(t=>"function"==typeof e[t]),tm=(e,t)=>{tp(e)?t():(e.eventedCallbacks||(e.eventedCallbacks=[]),e.eventedCallbacks.push(t))},tg=e=>"string"==typeof e&&/\S/.test(e)||Array.isArray(e)&&!!e.length,tf=(e,t,i)=>{if(!e||!e.nodeName&&!tp(e))throw Error(`Invalid target for ${tc(t)}#${i}; must be a DOM node or evented object.`)},t_=(e,t,i)=>{if(!tg(e))throw Error(`Invalid event type for ${tc(t)}#${i}; must be a non-empty string or array.`)},ty=(e,t,i)=>{if("function"!=typeof e)throw Error(`Invalid listener for ${tc(t)}#${i}; must be a function.`)},tv=(e,t,i)=>{let s,r,n;let a=t.length<3||t[0]===e||t[0]===e.eventBusEl_;return a?(s=e.eventBusEl_,t.length>=3&&t.shift(),[r,n]=t):(s=t[0],r=t[1],n=t[2]),tf(s,e,i),t_(r,e,i),ty(n,e,i),{isTargetingSelf:a,target:s,type:r,listener:n=to(e,n)}},tb=(e,t,i,s)=>{tf(e,e,t),e.nodeName?ta[t](e,i,s):e[t](i,s)},tT={on(...e){let{isTargetingSelf:t,target:i,type:s,listener:r}=tv(this,e,"on");if(tb(i,"on",s,r),!t){let e=()=>this.off(i,s,r);e.guid=r.guid;let t=()=>this.off("dispose",e);t.guid=r.guid,tb(this,"on","dispose",e),tb(i,"on","dispose",t)}},one(...e){let{isTargetingSelf:t,target:i,type:s,listener:r}=tv(this,e,"one");if(t)tb(i,"one",s,r);else{let e=(...t)=>{this.off(i,s,e),r.apply(null,t)};e.guid=r.guid,tb(i,"one",s,e)}},any(...e){let{isTargetingSelf:t,target:i,type:s,listener:r}=tv(this,e,"any");if(t)tb(i,"any",s,r);else{let e=(...t)=>{this.off(i,s,e),r.apply(null,t)};e.guid=r.guid,tb(i,"any",s,e)}},off(e,t,i){!e||tg(e)?ti(this.eventBusEl_,e,t):(tf(e,this,"off"),t_(t,this,"off"),ty(i,this,"off"),i=to(this,i),this.off("dispose",i),e.nodeName?(ti(e,t,i),ti(e,"dispose",i)):tp(e)&&(e.off(t,i),e.off("dispose",i)))},trigger(e,t){if(tf(this.eventBusEl_,this,"trigger"),!tg(e&&"string"!=typeof e?e.type:e))throw Error(`Invalid event type for ${tc(this)}#trigger; must be a non-empty string or object with a type key that has a non-empty value.`);return ts(this.eventBusEl_,e,t)}};function tS(e,t={}){let{eventBusKey:i}=t;if(i){if(!e[i].nodeName)throw Error(`The eventBusKey "${i}" does not refer to an element.`);e.eventBusEl_=e[i]}else e.eventBusEl_=eC("span",{className:"vjs-event-bus"});return Object.assign(e,tT),e.eventedCallbacks&&e.eventedCallbacks.forEach(e=>{e()}),e.on("dispose",()=>{e.off(),[e,e.el_,e.eventBusEl_].forEach(function(e){e&&e8.has(e)&&e8.delete(e)}),d().setTimeout(()=>{e.eventBusEl_=null},0)}),e}let tk={state:{},setState(e){let t;return"function"==typeof e&&(e=e()),q(e,(e,i)=>{this.state[i]!==e&&((t=t||{})[i]={from:this.state[i],to:e}),this.state[i]=e}),t&&tp(this)&&this.trigger({changes:t,type:"statechanged"}),t}};function tC(e,t){return Object.assign(e,tk),e.state=Object.assign({},e.state,t),"function"==typeof e.handleStateChanged&&tp(e)&&e.on("statechanged",e.handleStateChanged),e}let tw=function(e){return"string"!=typeof e?e:e.replace(/./,e=>e.toLowerCase())},tE=function(e){return"string"!=typeof e?e:e.replace(/./,e=>e.toUpperCase())},tx=function(e,t){return tE(e)===tE(t)};var tI=Object.freeze({__proto__:null,toLowerCase:tw,toTitleCase:tE,titleCaseEquals:tx});class tP{constructor(e,t,i){if(!e&&this.play?this.player_=e=this:this.player_=e,this.isDisposed_=!1,this.parentComponent_=null,this.options_=W({},this.options_),t=this.options_=W(this.options_,t),this.id_=t.id||t.el&&t.el.id,!this.id_){let t=e&&e.id&&e.id()||"no_player";this.id_=`${t}_component_${e5++}`}this.name_=t.name||null,t.el?this.el_=t.el:!1!==t.createEl&&(this.el_=this.createEl()),t.className&&this.el_&&t.className.split(" ").forEach(e=>this.addClass(e)),["on","off","one","any","trigger"].forEach(e=>{this[e]=void 0}),!1!==t.evented&&(tS(this,{eventBusKey:this.el_?"el_":null}),this.handleLanguagechange=this.handleLanguagechange.bind(this),this.on(this.player_,"languagechange",this.handleLanguagechange)),tC(this,this.constructor.defaultState),this.children_=[],this.childIndex_={},this.childNameIndex_={},this.setTimeoutIds_=new Set,this.setIntervalIds_=new Set,this.rafIds_=new Set,this.namedRafs_=new Map,this.clearingTimersOnDispose_=!1,!1!==t.initChildren&&this.initChildren(),this.ready(i),!1!==t.reportTouchActivity&&this.enableTouchActivity()}dispose(e={}){if(!this.isDisposed_){if(this.readyQueue_&&(this.readyQueue_.length=0),this.trigger({type:"dispose",bubbles:!1}),this.isDisposed_=!0,this.children_)for(let e=this.children_.length-1;e>=0;e--)this.children_[e].dispose&&this.children_[e].dispose();this.children_=null,this.childIndex_=null,this.childNameIndex_=null,this.parentComponent_=null,this.el_&&(this.el_.parentNode&&(e.restoreEl?this.el_.parentNode.replaceChild(e.restoreEl,this.el_):this.el_.parentNode.removeChild(this.el_)),this.el_=null),this.player_=null}}isDisposed(){return!!this.isDisposed_}player(){return this.player_}options(e){return e&&(this.options_=W(this.options_,e)),this.options_}el(){return this.el_}createEl(e,t,i){return eC(e,t,i)}localize(e,t,i=e){let s=this.player_.language&&this.player_.language(),r=this.player_.languages&&this.player_.languages(),n=r&&r[s],a=s&&s.split("-")[0],o=r&&r[a],l=i;return n&&n[e]?l=n[e]:o&&o[e]&&(l=o[e]),t&&(l=l.replace(/\{(\d+)\}/g,function(e,i){let s=t[i-1],r=s;return void 0===s&&(r=e),r})),l}handleLanguagechange(){}contentEl(){return this.contentEl_||this.el_}id(){return this.id_}name(){return this.name_}children(){return this.children_}getChildById(e){return this.childIndex_[e]}getChild(e){if(e)return this.childNameIndex_[e]}getDescendant(...e){e=e.reduce((e,t)=>e.concat(t),[]);let t=this;for(let i=0;i=0;i--)if(this.children_[i]===e){t=!0,this.children_.splice(i,1);break}if(!t)return;e.parentComponent_=null,this.childIndex_[e.id()]=null,this.childNameIndex_[tE(e.name())]=null,this.childNameIndex_[tw(e.name())]=null;let i=e.el();i&&i.parentNode===this.contentEl()&&this.contentEl().removeChild(e.el())}initChildren(){let e=this.options_.children;if(e){let t;let i=this.options_,s=tP.getComponent("Tech");(t=Array.isArray(e)?e:Object.keys(e)).concat(Object.keys(this.options_).filter(function(e){return!t.some(function(t){return"string"==typeof t?e===t:e===t.name})})).map(t=>{let i,s;return"string"==typeof t?s=e[i=t]||this.options_[i]||{}:(i=t.name,s=t),{name:i,opts:s}}).filter(e=>{let t=tP.getComponent(e.opts.componentClass||tE(e.name));return t&&!s.isTech(t)}).forEach(e=>{let t=e.name,s=e.opts;if(void 0!==i[t]&&(s=i[t]),!1===s)return;!0===s&&(s={}),s.playerOptions=this.options_.playerOptions;let r=this.addChild(t,s);r&&(this[t]=r)})}}buildCSSClass(){return""}ready(e,t=!1){if(e){if(!this.isReady_){this.readyQueue_=this.readyQueue_||[],this.readyQueue_.push(e);return}t?e.call(this):this.setTimeout(e,1)}}triggerReady(){this.isReady_=!0,this.setTimeout(function(){let e=this.readyQueue_;this.readyQueue_=[],e&&e.length>0&&e.forEach(function(e){e.call(this)},this),this.trigger("ready")},1)}$(e,t){return eG(e,t||this.contentEl())}$$(e,t){return eK(e,t||this.contentEl())}hasClass(e){return ex(this.el_,e)}addClass(...e){eI(this.el_,...e)}removeClass(...e){eP(this.el_,...e)}toggleClass(e,t){eA(this.el_,e,t)}show(){this.removeClass("vjs-hidden")}hide(){this.addClass("vjs-hidden")}lockShowing(){this.addClass("vjs-lock-showing")}unlockShowing(){this.removeClass("vjs-lock-showing")}getAttribute(e){return eO(this.el_,e)}setAttribute(e,t){eM(this.el_,e,t)}removeAttribute(e){eU(this.el_,e)}width(e,t){return this.dimension("width",e,t)}height(e,t){return this.dimension("height",e,t)}dimensions(e,t){this.width(e,!0),this.height(t)}dimension(e,t,i){if(void 0!==t){(null===t||t!=t)&&(t=0),-1!==(""+t).indexOf("%")||-1!==(""+t).indexOf("px")?this.el_.style[e]=t:"auto"===t?this.el_.style[e]="":this.el_.style[e]=t+"px",i||this.trigger("componentresize");return}if(!this.el_)return 0;let s=this.el_.style[e],r=s.indexOf("px");return -1!==r?parseInt(s.slice(0,r),10):parseInt(this.el_["offset"+tE(e)],10)}currentDimension(e){let t=0;if("width"!==e&&"height"!==e)throw Error("currentDimension only accepts width or height value");if(0===(t=parseFloat(t=eQ(this.el_,e)))||isNaN(t)){let i=`offset${tE(e)}`;t=this.el_[i]}return t}currentDimensions(){return{width:this.currentDimension("width"),height:this.currentDimension("height")}}currentWidth(){return this.currentDimension("width")}currentHeight(){return this.currentDimension("height")}getPositions(){let e=this.el_.getBoundingClientRect();return{boundingClientRect:{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left},center:{x:e.left+e.width/2,y:e.top+e.height/2,width:0,height:0,top:e.top+e.height/2,right:e.left+e.width/2,bottom:e.top+e.height/2,left:e.left+e.width/2}}}focus(){this.el_.focus()}blur(){this.el_.blur()}handleKeyDown(e){this.player_&&("Tab"===e.key||this.player_.options_.playerOptions.spatialNavigation&&this.player_.options_.playerOptions.spatialNavigation.enabled||e.stopPropagation(),this.player_.handleKeyDown(e))}handleKeyPress(e){this.handleKeyDown(e)}emitTapEvents(){let e,t=0,i=null;this.on("touchstart",function(s){1===s.touches.length&&(i={pageX:s.touches[0].pageX,pageY:s.touches[0].pageY},t=d().performance.now(),e=!0)}),this.on("touchmove",function(t){if(t.touches.length>1)e=!1;else if(i){let s=t.touches[0].pageX-i.pageX,r=t.touches[0].pageY-i.pageY;Math.sqrt(s*s+r*r)>10&&(e=!1)}});let s=function(){e=!1};this.on("touchleave",s),this.on("touchcancel",s),this.on("touchend",function(s){i=null,!0===e&&d().performance.now()-t<200&&(s.preventDefault(),this.trigger("tap"))})}enableTouchActivity(){let e;if(!this.player()||!this.player().reportUserActivity)return;let t=to(this.player(),this.player().reportUserActivity);this.on("touchstart",function(){t(),this.clearInterval(e),e=this.setInterval(t,250)});let i=function(i){t(),this.clearInterval(e)};this.on("touchmove",t),this.on("touchend",i),this.on("touchcancel",i)}setTimeout(e,t){var i;return e=to(this,e),this.clearTimersOnDispose_(),i=d().setTimeout(()=>{this.setTimeoutIds_.has(i)&&this.setTimeoutIds_.delete(i),e()},t),this.setTimeoutIds_.add(i),i}clearTimeout(e){return this.setTimeoutIds_.has(e)&&(this.setTimeoutIds_.delete(e),d().clearTimeout(e)),e}setInterval(e,t){e=to(this,e),this.clearTimersOnDispose_();let i=d().setInterval(e,t);return this.setIntervalIds_.add(i),i}clearInterval(e){return this.setIntervalIds_.has(e)&&(this.setIntervalIds_.delete(e),d().clearInterval(e)),e}requestAnimationFrame(e){var t;return this.clearTimersOnDispose_(),e=to(this,e),t=d().requestAnimationFrame(()=>{this.rafIds_.has(t)&&this.rafIds_.delete(t),e()}),this.rafIds_.add(t),t}requestNamedAnimationFrame(e,t){this.namedRafs_.has(e)&&this.cancelNamedAnimationFrame(e),this.clearTimersOnDispose_(),t=to(this,t);let i=this.requestAnimationFrame(()=>{t(),this.namedRafs_.has(e)&&this.namedRafs_.delete(e)});return this.namedRafs_.set(e,i),e}cancelNamedAnimationFrame(e){this.namedRafs_.has(e)&&(this.cancelAnimationFrame(this.namedRafs_.get(e)),this.namedRafs_.delete(e))}cancelAnimationFrame(e){return this.rafIds_.has(e)&&(this.rafIds_.delete(e),d().cancelAnimationFrame(e)),e}clearTimersOnDispose_(){!this.clearingTimersOnDispose_&&(this.clearingTimersOnDispose_=!0,this.one("dispose",()=>{[["namedRafs_","cancelNamedAnimationFrame"],["rafIds_","cancelAnimationFrame"],["setTimeoutIds_","clearTimeout"],["setIntervalIds_","clearInterval"]].forEach(([e,t])=>{this[e].forEach((e,i)=>this[t](i))}),this.clearingTimersOnDispose_=!1}))}getIsDisabled(){return!!this.el_.disabled}getIsExpresslyInert(){return this.el_.inert&&!this.el_.ownerDocument.documentElement.inert}getIsFocusable(e){return(e||this.el_).tabIndex>=0&&!(this.getIsDisabled()||this.getIsExpresslyInert())}getIsAvailableToBeFocused(e){var t;function i(e){let t=d().getComputedStyle(e,null),i=t.getPropertyValue("visibility");return"none"!==t.getPropertyValue("display")&&!["hidden","collapse"].includes(i)}return e||(e=this.el()),!!(function(e){if(e.offsetWidth+e.offsetHeight+e.getBoundingClientRect().height+e.getBoundingClientRect().width===0)return!1;let t={x:e.getBoundingClientRect().left+e.offsetWidth/2,y:e.getBoundingClientRect().top+e.offsetHeight/2};if(t.x<0||t.x>(c().documentElement.clientWidth||d().innerWidth)||t.y<0||t.y>(c().documentElement.clientHeight||d().innerHeight))return!1;let i=c().elementFromPoint(t.x,t.y);for(;i;){if(i===e)return!0;if(!i.parentNode)return!1;i=i.parentNode}}(e)&&i((t=e).parentElement)&&i(t)&&"0"!==t.style.opacity&&"0px"!==d().getComputedStyle(t).height&&"0px"!==d().getComputedStyle(t).width)&&(!e.parentElement||!!(e.tabIndex>=0))}static registerComponent(e,t){if("string"!=typeof e||!e)throw Error(`Illegal component name, "${e}"; must be a non-empty string.`);let i=tP.getComponent("Tech"),s=i&&i.isTech(t),r=tP===t||tP.prototype.isPrototypeOf(t.prototype);if(s||!r){let t;throw t=s?"techs must be registered using Tech.registerTech()":"must be a Component subclass",Error(`Illegal component, "${e}"; ${t}.`)}e=tE(e),tP.components_||(tP.components_={});let n=tP.getComponent("Player");if("Player"===e&&n&&n.players){let e=n.players,t=Object.keys(e);if(e&&t.length>0&&t.map(t=>e[t]).every(Boolean))throw Error("Can not register Player component after player has been created.")}return tP.components_[e]=t,tP.components_[tw(e)]=t,t}static getComponent(e){if(e&&tP.components_)return tP.components_[e]}}function tA(e,t,i,s){return!function(e,t,i){if("number"!=typeof t||t<0||t>i)throw Error(`Failed to execute '${e}' on 'TimeRanges': The index provided (${t}) is non-numeric or out of bounds (0-${i}).`)}(e,s,i.length-1),i[s][t]}function tL(e){let t;return t=void 0===e||0===e.length?{length:0,start(){throw Error("This TimeRanges object is empty")},end(){throw Error("This TimeRanges object is empty")}}:{length:e.length,start:tA.bind(null,"start",0,e),end:tA.bind(null,"end",1,e)},d().Symbol&&d().Symbol.iterator&&(t[d().Symbol.iterator]=()=>(e||[]).values()),t}function tD(e,t){return Array.isArray(e)?tL(e):void 0===e||void 0===t?tL():tL([[e,t]])}tP.registerComponent("Component",tP);let tO=function(e,t){let i=Math.floor((e=e<0?0:e)%60),s=Math.floor(e/60%60),r=Math.floor(e/3600),n=Math.floor(t/60%60),a=Math.floor(t/3600);return(isNaN(e)||e===1/0)&&(r=s=i="-"),s=(((r=r>0||a>0?r+":":"")||n>=10)&&s<10?"0"+s:s)+":",r+s+(i=i<10?"0"+i:i)},tM=tO;function tU(e){tM=e}function tR(){tM=tO}function tB(e,t=e){return tM(e,t)}var tN=Object.freeze({__proto__:null,createTimeRanges:tD,createTimeRange:tD,setFormatTime:tU,resetFormatTime:tR,formatTime:tB});function tj(e,t){let i,s,r=0;if(!t)return 0;e&&e.length||(e=tD(0,0));for(let n=0;nt&&(s=t),r+=s-i;return r/t}function tF(e){if(e instanceof tF)return e;"number"==typeof e?this.code=e:"string"==typeof e?this.message=e:V(e)&&("number"==typeof e.code&&(this.code=e.code),Object.assign(this,e)),this.message||(this.message=tF.defaultMessages[this.code]||"")}function t$(e){return null!=e&&"function"==typeof e.then}function tq(e){t$(e)&&e.then(null,e=>{})}tF.prototype.code=0,tF.prototype.message="",tF.prototype.status=null,tF.prototype.metadata=null,tF.errorTypes=["MEDIA_ERR_CUSTOM","MEDIA_ERR_ABORTED","MEDIA_ERR_NETWORK","MEDIA_ERR_DECODE","MEDIA_ERR_SRC_NOT_SUPPORTED","MEDIA_ERR_ENCRYPTED"],tF.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail part-way.",3:"The media playback was aborted due to a corruption problem or because the media used features your browser did not support.",4:"The media could not be loaded, either because the server or network failed or because the format is not supported.",5:"The media is encrypted and we do not have the keys to decrypt it."},tF.MEDIA_ERR_CUSTOM=0,tF.prototype.MEDIA_ERR_CUSTOM=0,tF.MEDIA_ERR_ABORTED=1,tF.prototype.MEDIA_ERR_ABORTED=1,tF.MEDIA_ERR_NETWORK=2,tF.prototype.MEDIA_ERR_NETWORK=2,tF.MEDIA_ERR_DECODE=3,tF.prototype.MEDIA_ERR_DECODE=3,tF.MEDIA_ERR_SRC_NOT_SUPPORTED=4,tF.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4,tF.MEDIA_ERR_ENCRYPTED=5,tF.prototype.MEDIA_ERR_ENCRYPTED=5;let tH=function(e){return["kind","label","language","id","inBandMetadataTrackDispatchType","mode","src"].reduce((t,i,s)=>(e[i]&&(t[i]=e[i]),t),{cues:e.cues&&Array.prototype.map.call(e.cues,function(e){return{startTime:e.startTime,endTime:e.endTime,text:e.text,id:e.id}})})};var tV={textTracksToJson:function(e){let t=e.$$("track"),i=Array.prototype.map.call(t,e=>e.track);return Array.prototype.map.call(t,function(e){let t=tH(e.track);return e.src&&(t.src=e.src),t}).concat(Array.prototype.filter.call(e.textTracks(),function(e){return -1===i.indexOf(e)}).map(tH))},jsonToTextTracks:function(e,t){return e.forEach(function(e){let i=t.addRemoteTextTrack(e).track;!e.src&&e.cues&&e.cues.forEach(e=>i.addCue(e))}),t.textTracks()}};let tz="vjs-modal-dialog";class tW extends tP{constructor(e,t){super(e,t),this.handleKeyDown_=e=>this.handleKeyDown(e),this.close_=e=>this.close(e),this.opened_=this.hasBeenOpened_=this.hasBeenFilled_=!1,this.closeable(!this.options_.uncloseable),this.content(this.options_.content),this.contentEl_=eC("div",{className:`${tz}-content`},{role:"document"}),this.descEl_=eC("p",{className:`${tz}-description vjs-control-text`,id:this.el().getAttribute("aria-describedby")}),ew(this.descEl_,this.description()),this.el_.appendChild(this.descEl_),this.el_.appendChild(this.contentEl_)}createEl(){return super.createEl("div",{className:this.buildCSSClass(),tabIndex:-1},{"aria-describedby":`${this.id()}_description`,"aria-hidden":"true","aria-label":this.label(),role:"dialog","aria-live":"polite"})}dispose(){this.contentEl_=null,this.descEl_=null,this.previouslyActiveEl_=null,super.dispose()}buildCSSClass(){return`${tz} vjs-hidden ${super.buildCSSClass()}`}label(){return this.localize(this.options_.label||"Modal Window")}description(){let e=this.options_.description||this.localize("This is a modal window.");return this.closeable()&&(e+=" "+this.localize("This modal can be closed by pressing the Escape key or activating the close button.")),e}open(){if(this.opened_){this.options_.fillAlways&&this.fill();return}let e=this.player();this.trigger("beforemodalopen"),this.opened_=!0,!this.options_.fillAlways&&(this.hasBeenOpened_||this.hasBeenFilled_)||this.fill(),this.wasPlaying_=!e.paused(),this.options_.pauseOnOpen&&this.wasPlaying_&&e.pause(),this.on("keydown",this.handleKeyDown_),this.hadControls_=e.controls(),e.controls(!1),this.show(),this.conditionalFocus_(),this.el().setAttribute("aria-hidden","false"),this.trigger("modalopen"),this.hasBeenOpened_=!0}opened(e){return"boolean"==typeof e&&this[e?"open":"close"](),this.opened_}close(){if(!this.opened_)return;let e=this.player();this.trigger("beforemodalclose"),this.opened_=!1,this.wasPlaying_&&this.options_.pauseOnOpen&&e.play(),this.off("keydown",this.handleKeyDown_),this.hadControls_&&e.controls(!0),this.hide(),this.el().setAttribute("aria-hidden","true"),this.trigger({type:"modalclose",bubbles:!0}),this.conditionalBlur_(),this.options_.temporary&&this.dispose()}closeable(e){if("boolean"==typeof e){let t=this.closeable_=!!e,i=this.getChild("closeButton");if(t&&!i){let e=this.contentEl_;this.contentEl_=this.el_,i=this.addChild("closeButton",{controlText:"Close Modal Dialog"}),this.contentEl_=e,this.on(i,"close",this.close_)}!t&&i&&(this.off(i,"close",this.close_),this.removeChild(i),i.dispose())}return this.closeable_}fill(){this.fillWith(this.content())}fillWith(e){let t=this.contentEl(),i=t.parentNode,s=t.nextSibling;this.trigger("beforemodalfill"),this.hasBeenFilled_=!0,i.removeChild(t),this.empty(),ez(t,e),this.trigger("modalfill"),s?i.insertBefore(t,s):i.appendChild(t);let r=this.getChild("closeButton");r&&i.appendChild(r.el_),this.trigger("aftermodalfill")}empty(){this.trigger("beforemodalempty"),eq(this.contentEl()),this.trigger("modalempty")}content(e){return void 0!==e&&(this.content_=e),this.content_}conditionalFocus_(){let e=c().activeElement,t=this.player_.el_;this.previouslyActiveEl_=null,(t.contains(e)||t===e)&&(this.previouslyActiveEl_=e,this.focus())}conditionalBlur_(){this.previouslyActiveEl_&&(this.previouslyActiveEl_.focus(),this.previouslyActiveEl_=null)}handleKeyDown(e){let t;if(this.trigger({type:"modalKeydown",originalEvent:e,target:this,bubbles:!0}),e.stopPropagation(),"Escape"===e.key&&this.closeable()){e.preventDefault(),this.close();return}if("Tab"!==e.key)return;let i=this.focusableEls_(),s=this.el_.querySelector(":focus");for(let e=0;e(e instanceof d().HTMLAnchorElement||e instanceof d().HTMLAreaElement)&&e.hasAttribute("href")||(e instanceof d().HTMLInputElement||e instanceof d().HTMLSelectElement||e instanceof d().HTMLTextAreaElement||e instanceof d().HTMLButtonElement)&&!e.hasAttribute("disabled")||e instanceof d().HTMLIFrameElement||e instanceof d().HTMLObjectElement||e instanceof d().HTMLEmbedElement||e.hasAttribute("tabindex")&&-1!==e.getAttribute("tabindex")||e.hasAttribute("contenteditable"))}}tW.prototype.options_={pauseOnOpen:!0,temporary:!0},tP.registerComponent("ModalDialog",tW);class tG extends tu{constructor(e=[]){super(),this.tracks_=[],Object.defineProperty(this,"length",{get(){return this.tracks_.length}});for(let t=0;t{this.trigger({track:e,type:"labelchange",target:this})},tp(e)&&e.addEventListener("labelchange",e.labelchange_)}removeTrack(e){let t;for(let i=0,s=this.length;i=0;t--)if(e[t].enabled){tK(e,e[t]);break}super(e),this.changing_=!1}addTrack(e){e.enabled&&tK(this,e),super.addTrack(e),e.addEventListener&&(e.enabledChange_=()=>{!this.changing_&&(this.changing_=!0,tK(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("enabledchange",e.enabledChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.enabledChange_&&(e.removeEventListener("enabledchange",e.enabledChange_),e.enabledChange_=null)}}let tY=function(e,t){for(let i=0;i=0;t--)if(e[t].selected){tY(e,e[t]);break}super(e),this.changing_=!1,Object.defineProperty(this,"selectedIndex",{get(){for(let e=0;e{!this.changing_&&(this.changing_=!0,tY(this,e),this.changing_=!1,this.trigger("change"))},e.addEventListener("selectedchange",e.selectedChange_))}removeTrack(e){super.removeTrack(e),e.removeEventListener&&e.selectedChange_&&(e.removeEventListener("selectedchange",e.selectedChange_),e.selectedChange_=null)}}class tJ extends tG{addTrack(e){super.addTrack(e),this.queueChange_||(this.queueChange_=()=>this.queueTrigger("change")),this.triggerSelectedlanguagechange||(this.triggerSelectedlanguagechange_=()=>this.trigger("selectedlanguagechange")),e.addEventListener("modechange",this.queueChange_),-1===["metadata","chapters"].indexOf(e.kind)&&e.addEventListener("modechange",this.triggerSelectedlanguagechange_)}removeTrack(e){super.removeTrack(e),e.removeEventListener&&(this.queueChange_&&e.removeEventListener("modechange",this.queueChange_),this.selectedlanguagechange_&&e.removeEventListener("modechange",this.triggerSelectedlanguagechange_))}}class tZ{constructor(e=[]){this.trackElements_=[],Object.defineProperty(this,"length",{get(){return this.trackElements_.length}});for(let t=0,i=e.length;tt[e],set(){}});Object.defineProperty(this,"label",{get:()=>i,set(e){e!==i&&(i=e,this.trigger("labelchange"))}})}}let t3=function(e){return new URL(e,c().baseURI)},t6=function(e){return new URL(e,c().baseURI).href},t7=function(e){if("string"==typeof e){let t=/^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/.exec(e);if(t)return t.pop().toLowerCase()}return""},t9=function(e,t=d().location){return t3(e).origin!==t.origin};var ie=Object.freeze({__proto__:null,parseUrl:t3,getAbsoluteURL:t6,getFileExtension:t7,isCrossOrigin:t9});let it=function(e,t){let i=new(d()).WebVTT.Parser(d(),d().vttjs,d().WebVTT.StringDecoder()),s=[];i.oncue=function(e){t.addCue(e)},i.onparsingerror=function(e){s.push(e)},i.onflush=function(){t.trigger({type:"loadeddata",target:t})},i.parse(e),s.length>0&&(d().console&&d().console.groupCollapsed&&d().console.groupCollapsed(`Text Track parsing errors for ${t.src}`),s.forEach(e=>N.error(e)),d().console&&d().console.groupEnd&&d().console.groupEnd()),i.flush()},ii=function(e,t){let i={uri:e},s=t9(e);s&&(i.cors=s);let r="use-credentials"===t.tech_.crossOrigin();r&&(i.withCredentials=r),m()(i,to(this,function(e,i,s){if(e)return N.error(e,i);t.loaded_=!0,"function"!=typeof d().WebVTT?t.tech_&&t.tech_.any(["vttjsloaded","vttjserror"],e=>{if("vttjserror"===e.type){N.error(`vttjs failed to load, stopping trying to process ${t.src}`);return}return it(s,t)}):it(s,t)}))};class is extends t5{constructor(e={}){if(!e.tech)throw Error("A tech was not provided.");let t=W(e,{kind:t4[e.kind]||"subtitles",language:e.language||e.srclang||""}),i=t8[t.mode]||"disabled",s=t.default;("metadata"===t.kind||"chapters"===t.kind)&&(i="hidden"),super(t),this.tech_=t.tech,this.cues_=[],this.activeCues_=[],this.preload_=!1!==this.tech_.preloadTextTracks;let r=new t0(this.cues_),n=new t0(this.activeCues_),a=!1;this.timeupdateHandler=to(this,function(e={}){if(!this.tech_.isDisposed()){if(!this.tech_.isReady_){"timeupdate"!==e.type&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler));return}this.activeCues=this.activeCues,a&&(this.trigger("cuechange"),a=!1),"timeupdate"!==e.type&&(this.rvf_=this.tech_.requestVideoFrameCallback(this.timeupdateHandler))}}),this.tech_.one("dispose",()=>{this.stopTracking()}),"disabled"!==i&&this.startTracking(),Object.defineProperties(this,{default:{get:()=>s,set(){}},mode:{get:()=>i,set(e){t8[e]&&i!==e&&(i=e,this.preload_||"disabled"===i||0!==this.cues.length||ii(this.src,this),this.stopTracking(),"disabled"!==i&&this.startTracking(),this.trigger("modechange"))}},cues:{get(){return this.loaded_?r:null},set(){}},activeCues:{get(){if(!this.loaded_)return null;if(0===this.cues.length)return n;let e=this.tech_.currentTime(),t=[];for(let i=0,s=this.cues.length;i=e&&t.push(s)}if(a=!1,t.length!==this.activeCues_.length)a=!0;else for(let e=0;ei,set(e){"boolean"==typeof e&&e!==i&&(i=e,this.trigger("enabledchange"))}}),t.enabled&&(this.enabled=t.enabled),this.loaded_=!0}}class ia extends t5{constructor(e={}){let t=W(e,{kind:t1[e.kind]||""});super(t);let i=!1;Object.defineProperty(this,"selected",{get:()=>i,set(e){"boolean"==typeof e&&e!==i&&(i=e,this.trigger("selectedchange"))}}),t.selected&&(this.selected=t.selected)}}class io extends tu{constructor(e={}){let t;super();let i=new is(e);this.kind=i.kind,this.src=i.src,this.srclang=i.language,this.label=i.label,this.default=i.default,Object.defineProperties(this,{readyState:{get:()=>t},track:{get:()=>i}}),t=io.NONE,i.addEventListener("loadeddata",()=>{t=io.LOADED,this.trigger({type:"load",target:this})})}}io.prototype.allowedEvents_={load:"load"},io.NONE=0,io.LOADING=1,io.LOADED=2,io.ERROR=3;let il={audio:{ListClass:tQ,TrackClass:ir,capitalName:"Audio"},video:{ListClass:tX,TrackClass:ia,capitalName:"Video"},text:{ListClass:tJ,TrackClass:is,capitalName:"Text"}};Object.keys(il).forEach(function(e){il[e].getterName=`${e}Tracks`,il[e].privateName=`${e}Tracks_`});let ih={remoteText:{ListClass:tJ,TrackClass:is,capitalName:"RemoteText",getterName:"remoteTextTracks",privateName:"remoteTextTracks_"},remoteTextEl:{ListClass:tZ,TrackClass:io,capitalName:"RemoteTextTrackEls",getterName:"remoteTextTrackEls",privateName:"remoteTextTrackEls_"}},id=Object.assign({},il,ih);ih.names=Object.keys(ih),il.names=Object.keys(il),id.names=[].concat(ih.names).concat(il.names);class iu extends tP{constructor(e={},t=function(){}){e.reportTouchActivity=!1,super(null,e,t),this.onDurationChange_=e=>this.onDurationChange(e),this.trackProgress_=e=>this.trackProgress(e),this.trackCurrentTime_=e=>this.trackCurrentTime(e),this.stopTrackingCurrentTime_=e=>this.stopTrackingCurrentTime(e),this.disposeSourceHandler_=e=>this.disposeSourceHandler(e),this.queuedHanders_=new Set,this.hasStarted_=!1,this.on("playing",function(){this.hasStarted_=!0}),this.on("loadstart",function(){this.hasStarted_=!1}),id.names.forEach(t=>{let i=id[t];e&&e[i.getterName]&&(this[i.privateName]=e[i.getterName])}),this.featuresProgressEvents||this.manualProgressOn(),this.featuresTimeupdateEvents||this.manualTimeUpdatesOn(),["Text","Audio","Video"].forEach(t=>{!1===e[`native${t}Tracks`]&&(this[`featuresNative${t}Tracks`]=!1)}),!1===e.nativeCaptions||!1===e.nativeTextTracks?this.featuresNativeTextTracks=!1:(!0===e.nativeCaptions||!0===e.nativeTextTracks)&&(this.featuresNativeTextTracks=!0),this.featuresNativeTextTracks||this.emulateTextTracks(),this.preloadTextTracks=!1!==e.preloadTextTracks,this.autoRemoteTextTracks_=new id.text.ListClass,this.initTrackListeners(),e.nativeControlsForTouch||this.emitTapEvents(),this.constructor&&(this.name_=this.constructor.name||"Unknown Tech")}triggerSourceset(e){this.isReady_||this.one("ready",()=>this.setTimeout(()=>this.triggerSourceset(e),1)),this.trigger({src:e,type:"sourceset"})}manualProgressOn(){this.on("durationchange",this.onDurationChange_),this.manualProgress=!0,this.one("ready",this.trackProgress_)}manualProgressOff(){this.manualProgress=!1,this.stopTrackingProgress(),this.off("durationchange",this.onDurationChange_)}trackProgress(e){this.stopTrackingProgress(),this.progressInterval=this.setInterval(to(this,function(){let e=this.bufferedPercent();this.bufferedPercent_!==e&&this.trigger("progress"),this.bufferedPercent_=e,1===e&&this.stopTrackingProgress()}),500)}onDurationChange(e){this.duration_=this.duration()}buffered(){return tD(0,0)}bufferedPercent(){return tj(this.buffered(),this.duration_)}stopTrackingProgress(){this.clearInterval(this.progressInterval)}manualTimeUpdatesOn(){this.manualTimeUpdates=!0,this.on("play",this.trackCurrentTime_),this.on("pause",this.stopTrackingCurrentTime_)}manualTimeUpdatesOff(){this.manualTimeUpdates=!1,this.stopTrackingCurrentTime(),this.off("play",this.trackCurrentTime_),this.off("pause",this.stopTrackingCurrentTime_)}trackCurrentTime(){this.currentTimeInterval&&this.stopTrackingCurrentTime(),this.currentTimeInterval=this.setInterval(function(){this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})},250)}stopTrackingCurrentTime(){this.clearInterval(this.currentTimeInterval),this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}dispose(){this.clearTracks(il.names),this.manualProgress&&this.manualProgressOff(),this.manualTimeUpdates&&this.manualTimeUpdatesOff(),super.dispose()}clearTracks(e){(e=[].concat(e)).forEach(e=>{let t=this[`${e}Tracks`]()||[],i=t.length;for(;i--;){let s=t[i];"text"===e&&this.removeRemoteTextTrack(s),t.removeTrack(s)}})}cleanupAutoTextTracks(){let e=this.autoRemoteTextTracks_||[],t=e.length;for(;t--;){let i=e[t];this.removeRemoteTextTrack(i)}}reset(){}crossOrigin(){}setCrossOrigin(){}error(e){return void 0!==e&&(this.error_=new tF(e),this.trigger("error")),this.error_}played(){return this.hasStarted_?tD(0,0):tD()}play(){}setScrubbing(e){}scrubbing(){}setCurrentTime(e){this.manualTimeUpdates&&this.trigger({type:"timeupdate",target:this,manuallyTriggered:!0})}initTrackListeners(){il.names.forEach(e=>{let t=il[e],i=()=>{this.trigger(`${e}trackchange`)},s=this[t.getterName]();s.addEventListener("removetrack",i),s.addEventListener("addtrack",i),this.on("dispose",()=>{s.removeEventListener("removetrack",i),s.removeEventListener("addtrack",i)})})}addWebVttScript_(){if(!d().WebVTT){if(c().body.contains(this.el())){if(!this.options_["vtt.js"]&&z(f())&&Object.keys(f()).length>0){this.trigger("vttjsloaded");return}let e=c().createElement("script");e.src=this.options_["vtt.js"]||"https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js",e.onload=()=>{this.trigger("vttjsloaded")},e.onerror=()=>{this.trigger("vttjserror")},this.on("dispose",()=>{e.onload=null,e.onerror=null}),d().WebVTT=!0,this.el().parentNode.appendChild(e)}else this.ready(this.addWebVttScript_)}}emulateTextTracks(){let e=this.textTracks(),t=this.remoteTextTracks(),i=t=>e.addTrack(t.track),s=t=>e.removeTrack(t.track);t.on("addtrack",i),t.on("removetrack",s),this.addWebVttScript_();let r=()=>this.trigger("texttrackchange"),n=()=>{r();for(let t=0;tthis.autoRemoteTextTracks_.addTrack(i.track)),i}removeRemoteTextTrack(e){let t=this.remoteTextTrackEls().getTrackElementByTrack_(e);this.remoteTextTrackEls().removeTrackElement_(t),this.remoteTextTracks().removeTrack(e),this.autoRemoteTextTracks_.removeTrack(e)}getVideoPlaybackQuality(){return{}}requestPictureInPicture(){return Promise.reject()}disablePictureInPicture(){return!0}setDisablePictureInPicture(){}requestVideoFrameCallback(e){let t=e5++;return!this.isReady_||this.paused()?(this.queuedHanders_.add(t),this.one("playing",()=>{this.queuedHanders_.has(t)&&(this.queuedHanders_.delete(t),e())})):this.requestNamedAnimationFrame(t,e),t}cancelVideoFrameCallback(e){this.queuedHanders_.has(e)?this.queuedHanders_.delete(e):this.cancelNamedAnimationFrame(e)}setPoster(){}playsinline(){}setPlaysinline(){}overrideNativeAudioTracks(e){}overrideNativeVideoTracks(e){}canPlayType(e){return""}static canPlayType(e){return""}static canPlaySource(e,t){return iu.canPlayType(e.type)}static isTech(e){return e.prototype instanceof iu||e instanceof iu||e===iu}static registerTech(e,t){if(iu.techs_||(iu.techs_={}),!iu.isTech(t))throw Error(`Tech ${e} must be a Tech`);if(!iu.canPlayType)throw Error("Techs must have a static canPlayType method on them");if(!iu.canPlaySource)throw Error("Techs must have a static canPlaySource method on them");return e=tE(e),iu.techs_[e]=t,iu.techs_[tw(e)]=t,"Tech"!==e&&iu.defaultTechOrder_.push(e),t}static getTech(e){return e?iu.techs_&&iu.techs_[e]?iu.techs_[e]:(e=tE(e),d()&&d().videojs&&d().videojs[e])?(N.warn(`The ${e} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`),d().videojs[e]):void 0:void 0}}id.names.forEach(function(e){let t=id[e];iu.prototype[t.getterName]=function(){return this[t.privateName]=this[t.privateName]||new t.ListClass,this[t.privateName]}}),iu.prototype.featuresVolumeControl=!0,iu.prototype.featuresMuteControl=!0,iu.prototype.featuresFullscreenResize=!1,iu.prototype.featuresPlaybackRate=!1,iu.prototype.featuresProgressEvents=!1,iu.prototype.featuresSourceset=!1,iu.prototype.featuresTimeupdateEvents=!1,iu.prototype.featuresNativeTextTracks=!1,iu.prototype.featuresVideoFrameCallback=!1,iu.withSourceHandlers=function(e){e.registerSourceHandler=function(t,i){let s=e.sourceHandlers;s||(s=e.sourceHandlers=[]),void 0===i&&(i=s.length),s.splice(i,0,t)},e.canPlayType=function(t){let i;let s=e.sourceHandlers||[];for(let e=0;e=0;r--){let n=e[r];n[t]&&n[t](s,i)}}(e,i,o,a),o}let i_={buffered:1,currentTime:1,duration:1,muted:1,played:1,paused:1,seekable:1,volume:1,ended:1},iy={setCurrentTime:1,setMuted:1,setVolume:1},iv={play:1,pause:1};function ib(e){return(t,i)=>t===im?im:i[e]?i[e](t):t}let iT={opus:"video/ogg",ogv:"video/ogg",mp4:"video/mp4",mov:"video/mp4",m4v:"video/mp4",mkv:"video/x-matroska",m4a:"audio/mp4",mp3:"audio/mpeg",aac:"audio/aac",caf:"audio/x-caf",flac:"audio/flac",oga:"audio/ogg",wav:"audio/wav",m3u8:"application/x-mpegURL",mpd:"application/dash+xml",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",png:"image/png",svg:"image/svg+xml",webp:"image/webp"},iS=function(e=""){return iT[t7(e).toLowerCase()]||""},ik=(e,t)=>{if(!t)return"";if(e.cache_.source.src===t&&e.cache_.source.type)return e.cache_.source.type;let i=e.cache_.sources.filter(e=>e.src===t);if(i.length)return i[0].type;let s=e.$$("source");for(let e=0;e{this.focus(this.updateFocusableComponents()[0])}),this.player_.on("modalclose",()=>{this.refocusComponent()}),this.player_.on("focusin",this.handlePlayerFocus_.bind(this)),this.player_.on("focusout",this.handlePlayerBlur_.bind(this)),this.isListening_=!0,this.player_.errorDisplay&&this.player_.errorDisplay.on("aftermodalfill",()=>{this.updateFocusableComponents(),this.focusableComponents.length&&(this.focusableComponents.length>1?this.focusableComponents[1].focus():this.focusableComponents[0].focus())}))}stop(){this.player_.off("keydown",this.onKeyDown_),this.isListening_=!1}onKeyDown_(e){let t=e.originalEvent?e.originalEvent:e;if(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(t.key)){if(this.isPaused_)return;t.preventDefault();let e=t.key.substring(5).toLowerCase();this.move(e)}else if(ix.isEventKey(t,"play")||ix.isEventKey(t,"pause")||ix.isEventKey(t,"ff")||ix.isEventKey(t,"rw")){t.preventDefault();let e=ix.getEventName(t);this.performMediaAction_(e)}else ix.isEventKey(t,"Back")&&e.target&&"function"==typeof e.target.closeable&&e.target.closeable()&&(t.preventDefault(),e.target.close())}performMediaAction_(e){if(this.player_)switch(e){case"play":this.player_.paused()&&this.player_.play();break;case"pause":this.player_.paused()||this.player_.pause();break;case"ff":this.userSeek_(this.player_.currentTime()+5);break;case"rw":this.userSeek_(this.player_.currentTime()-5)}}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}pause(){this.isPaused_=!0}resume(){this.isPaused_=!1}handlePlayerBlur_(e){let t=e.relatedTarget,i=null,s=this.getCurrentComponent(e.target);t&&(i=!!t.closest(".video-js"),t.classList.contains("vjs-text-track-settings")&&!this.isPaused_&&this.searchForTrackSelect_()),(!e.currentTarget.contains(e.relatedTarget)&&!i||!t)&&(s&&"CloseButton"===s.name()?this.refocusComponent():(this.pause(),s&&s.el()&&(this.lastFocusedComponent_=s)))}handlePlayerFocus_(){this.getCurrentComponent()&&this.getCurrentComponent().getIsFocusable()&&this.resume()}updateFocusableComponents(){let e=this.player_,t=[];function i(e){for(let s of e)s.hasOwnProperty("el_")&&s.getIsFocusable()&&s.getIsAvailableToBeFocused(s.el())&&t.push(s),s.hasOwnProperty("children_")&&s.children_.length>0&&i(s.children_)}return e.children_.forEach(e=>{if(e.hasOwnProperty("el_")){if(e.getIsFocusable&&e.getIsAvailableToBeFocused&&e.getIsFocusable()&&e.getIsAvailableToBeFocused(e.el())){t.push(e);return}e.hasOwnProperty("children_")&&e.children_.length>0?i(e.children_):e.hasOwnProperty("items")&&e.items.length>0?i(e.items):this.findSuitableDOMChild(e)&&t.push(e)}if("ErrorDisplay"===e.name_&&e.opened_){let i=e.el_.querySelector(".vjs-errors-ok-button-container");i&&i.querySelectorAll("button").forEach((e,i)=>{t.push({name:()=>"ModalButton"+(i+1),el:()=>e,getPositions:()=>{let t=e.getBoundingClientRect();return{boundingClientRect:{x:t.x,y:t.y,width:t.width,height:t.height,top:t.top,right:t.right,bottom:t.bottom,left:t.left},center:{x:t.left+t.width/2,y:t.top+t.height/2,width:0,height:0,top:t.top+t.height/2,right:t.left+t.width/2,bottom:t.top+t.height/2,left:t.left+t.width/2}}},getIsAvailableToBeFocused:()=>!0,getIsFocusable:e=>!0,focus:()=>e.focus()})})}}),this.focusableComponents=t,this.focusableComponents}findSuitableDOMChild(e){return e.el()?function t(i){if(e.getIsFocusable(i)&&e.getIsAvailableToBeFocused(i))return i;for(let e=0;e0&&(this.focusableComponents=[],this.trigger({type:"focusableComponentsChanged",focusableComponents:this.focusableComponents}))}move(e){let t=this.getCurrentComponent();if(!t)return;let i=t.getPositions(),s=this.focusableComponents.filter(s=>s!==t&&this.isInDirection_(i.boundingClientRect,s.getPositions().boundingClientRect,e)),r=this.findBestCandidate_(i.center,s,e);r?this.focus(r):this.trigger({type:"endOfFocusableComponents",direction:e,focusedComponent:t})}findBestCandidate_(e,t,i){let s=1/0,r=null;for(let n of t){let t=n.getPositions().center,a=this.calculateDistance_(e,t,i);a=e.right;case"left":return t.right<=e.left;case"down":return t.top>=e.bottom;case"up":return t.bottom<=e.top;default:return!1}}refocusComponent(){if(this.lastFocusedComponent_){this.player_.userActive()||this.player_.userActive(!0),this.updateFocusableComponents();for(let e=0;ethis.handleMouseOver(e),this.handleMouseOut_=e=>this.handleMouseOut(e),this.handleClick_=e=>this.handleClick(e),this.handleKeyDown_=e=>this.handleKeyDown(e),this.emitTapEvents(),this.enable()}createEl(e="div",t={},i={}){t=Object.assign({className:this.buildCSSClass(),tabIndex:0},t),"button"===e&&N.error(`Creating a ClickableComponent with an HTML element of ${e} is not supported; use a Button instead.`),i=Object.assign({role:"button"},i),this.tabIndex_=t.tabIndex;let s=eC(e,t,i);return this.player_.options_.experimentalSvgIcons||s.appendChild(eC("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),this.createControlTextEl(s),s}dispose(){this.controlTextEl_=null,super.dispose()}createControlTextEl(e){return this.controlTextEl_=eC("span",{className:"vjs-control-text"},{"aria-live":"polite"}),e&&e.appendChild(this.controlTextEl_),this.controlText(this.controlText_,e),this.controlTextEl_}controlText(e,t=this.el()){if(void 0===e)return this.controlText_||"Need Text";let i=this.localize(e);this.controlText_=e,ew(this.controlTextEl_,i),this.nonIconControl||this.player_.options_.noUITitleAttributes||t.setAttribute("title",i)}buildCSSClass(){return`vjs-control vjs-button ${super.buildCSSClass()}`}enable(){this.enabled_||(this.enabled_=!0,this.removeClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","false"),void 0!==this.tabIndex_&&this.el_.setAttribute("tabIndex",this.tabIndex_),this.on(["tap","click"],this.handleClick_),this.on("keydown",this.handleKeyDown_))}disable(){this.enabled_=!1,this.addClass("vjs-disabled"),this.el_.setAttribute("aria-disabled","true"),void 0!==this.tabIndex_&&this.el_.removeAttribute("tabIndex"),this.off("mouseover",this.handleMouseOver_),this.off("mouseout",this.handleMouseOut_),this.off(["tap","click"],this.handleClick_),this.off("keydown",this.handleKeyDown_)}handleLanguagechange(){this.controlText(this.controlText_)}handleClick(e){this.options_.clickHandler&&this.options_.clickHandler.call(this,arguments)}handleKeyDown(e){" "===e.key||"Enter"===e.key?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}tP.registerComponent("ClickableComponent",iA);class iL extends iA{constructor(e,t){super(e,t),this.update(),this.update_=e=>this.update(e),e.on("posterchange",this.update_)}dispose(){this.player().off("posterchange",this.update_),super.dispose()}createEl(){return eC("div",{className:"vjs-poster"})}crossOrigin(e){if(void 0===e)return this.$("img")?this.$("img").crossOrigin:this.player_.tech_&&this.player_.tech_.isReady_?this.player_.crossOrigin():this.player_.options_.crossOrigin||this.player_.options_.crossorigin||null;if(null!==e&&"anonymous"!==e&&"use-credentials"!==e){this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${e}"`);return}this.$("img")&&(this.$("img").crossOrigin=e)}update(e){let t=this.player().poster();this.setSrc(t),t?this.show():this.hide()}setSrc(e){if(!e){this.el_.textContent="";return}this.$("img")||this.el_.appendChild(eC("picture",{className:"vjs-poster",tabIndex:-1},{},eC("img",{loading:"lazy",crossOrigin:this.crossOrigin()},{alt:""}))),this.$("img").src=e}handleClick(e){this.player_.controls()&&(this.player_.tech(!0)&&this.player_.tech(!0).focus(),this.player_.paused()?tq(this.player_.play()):this.player_.pause())}}iL.prototype.crossorigin=iL.prototype.crossOrigin,tP.registerComponent("PosterImage",iL);let iD="#222",iO="#ccc",iM={monospace:"monospace",sansSerif:"sans-serif",serif:"serif",monospaceSansSerif:'"Andale Mono", "Lucida Console", monospace',monospaceSerif:'"Courier New", monospace',proportionalSansSerif:"sans-serif",proportionalSerif:"serif",casual:'"Comic Sans MS", Impact, fantasy',script:'"Monotype Corsiva", cursive',smallcaps:'"Andale Mono", "Lucida Console", monospace, sans-serif'};function iU(e,t){let i;if(4===e.length)i=e[1]+e[1]+e[2]+e[2]+e[3]+e[3];else if(7===e.length)i=e.slice(1);else throw Error("Invalid color code provided, "+e+"; must be formatted as e.g. #f0e or #f604e2.");return"rgba("+parseInt(i.slice(0,2),16)+","+parseInt(i.slice(2,4),16)+","+parseInt(i.slice(4,6),16)+","+t+")"}function iR(e,t,i){try{e.style[t]=i}catch(e){return}}function iB(e){return e?`${e}px`:""}class iN extends tP{constructor(e,t,i){super(e,t,i);let s=e=>{this.updateDisplayOverlay(),this.updateDisplay(e)};e.on("loadstart",e=>this.toggleDisplay(e)),e.on("texttrackchange",e=>this.updateDisplay(e)),e.on("loadedmetadata",e=>{this.updateDisplayOverlay(),this.preselectTrack(e)}),e.ready(to(this,function(){if(e.tech_&&e.tech_.featuresNativeTextTracks){this.hide();return}e.on("fullscreenchange",s),e.on("playerresize",s);let t=d().screen.orientation||d(),i=d().screen.orientation?"change":"orientationchange";t.addEventListener(i,s),e.on("dispose",()=>t.removeEventListener(i,s));let r=this.options_.playerOptions.tracks||[];for(let e=0;e0&&t.forEach(e=>{if(e.style.inset){let t=e.style.inset.split(" ");3===t.length&&Object.assign(e.style,{top:t[0],right:t[1],bottom:t[2],left:"unset"})}})}}updateDisplayOverlay(){if(!this.player_.videoHeight()||!d().CSS.supports("inset-inline: 10px"))return;let e=this.player_.currentWidth(),t=this.player_.currentHeight(),i=e/t,s=this.player_.videoWidth()/this.player_.videoHeight(),r=0,n=0;Math.abs(i-s)>.1&&(i>s?r=Math.round((e-t*s)/2):n=Math.round((t-e/s)/2)),iR(this.el_,"insetInline",iB(r)),iR(this.el_,"insetBlock",iB(n))}updateDisplayState(e){let t=this.player_.textTrackSettings.getValues(),i=e.activeCues,s=i.length;for(;s--;){let e=i[s];if(!e)continue;let r=e.displayState;if(t.color&&(r.firstChild.style.color=t.color),t.textOpacity&&iR(r.firstChild,"color",iU(t.color||"#fff",t.textOpacity)),t.backgroundColor&&(r.firstChild.style.backgroundColor=t.backgroundColor),t.backgroundOpacity&&iR(r.firstChild,"backgroundColor",iU(t.backgroundColor||"#000",t.backgroundOpacity)),t.windowColor&&(t.windowOpacity?iR(r,"backgroundColor",iU(t.windowColor,t.windowOpacity)):r.style.backgroundColor=t.windowColor),t.edgeStyle&&("dropshadow"===t.edgeStyle?r.firstChild.style.textShadow=`2px 2px 3px ${iD}, 2px 2px 4px ${iD}, 2px 2px 5px ${iD}`:"raised"===t.edgeStyle?r.firstChild.style.textShadow=`1px 1px ${iD}, 2px 2px ${iD}, 3px 3px ${iD}`:"depressed"===t.edgeStyle?r.firstChild.style.textShadow=`1px 1px ${iO}, 0 1px ${iO}, -1px -1px ${iD}, 0 -1px ${iD}`:"uniform"===t.edgeStyle&&(r.firstChild.style.textShadow=`0 0 4px ${iD}, 0 0 4px ${iD}, 0 0 4px ${iD}, 0 0 4px ${iD}`)),t.fontPercent&&1!==t.fontPercent){let e=d().parseFloat(r.style.fontSize);r.style.fontSize=e*t.fontPercent+"px",r.style.height="auto",r.style.top="auto"}t.fontFamily&&"default"!==t.fontFamily&&("small-caps"===t.fontFamily?r.firstChild.style.fontVariant="small-caps":r.firstChild.style.fontFamily=iM[t.fontFamily])}}updateForTrack(e){if(Array.isArray(e)||(e=[e]),"function"!=typeof d().WebVTT||e.every(e=>!e.activeCues))return;let t=[];for(let i=0;ithis.handleMouseDown(e))}buildCSSClass(){return"vjs-big-play-button"}handleClick(e){let t=this.player_.play();if(this.mouseused_&&"clientX"in e&&"clientY"in e){tq(t),this.player_.tech(!0)&&this.player_.tech(!0).focus();return}let i=this.player_.getChild("controlBar"),s=i&&i.getChild("playToggle");if(!s){this.player_.tech(!0).focus();return}let r=()=>s.focus();t$(t)?t.then(r,()=>{}):this.setTimeout(r,1)}handleKeyDown(e){this.mouseused_=!1,super.handleKeyDown(e)}handleMouseDown(e){this.mouseused_=!0}}i$.prototype.controlText_="Play Video",tP.registerComponent("BigPlayButton",i$);class iq extends iF{constructor(e,t){super(e,t),this.setIcon("cancel"),this.controlText(t&&t.controlText||this.localize("Close"))}buildCSSClass(){return`vjs-close-button ${super.buildCSSClass()}`}handleClick(e){this.trigger({type:"close",bubbles:!1})}handleKeyDown(e){"Escape"===e.key?(e.preventDefault(),e.stopPropagation(),this.trigger("click")):super.handleKeyDown(e)}}tP.registerComponent("CloseButton",iq);class iH extends iF{constructor(e,t={}){super(e,t),t.replay=void 0===t.replay||t.replay,this.setIcon("play"),this.on(e,"play",e=>this.handlePlay(e)),this.on(e,"pause",e=>this.handlePause(e)),t.replay&&this.on(e,"ended",e=>this.handleEnded(e))}buildCSSClass(){return`vjs-play-control ${super.buildCSSClass()}`}handleClick(e){this.player_.paused()?tq(this.player_.play()):this.player_.pause()}handleSeeked(e){this.removeClass("vjs-ended"),this.player_.paused()?this.handlePause(e):this.handlePlay(e)}handlePlay(e){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.setIcon("pause"),this.controlText("Pause")}handlePause(e){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.setIcon("play"),this.controlText("Play")}handleEnded(e){this.removeClass("vjs-playing"),this.addClass("vjs-ended"),this.setIcon("replay"),this.controlText("Replay"),this.one(this.player_,"seeked",e=>this.handleSeeked(e))}}iH.prototype.controlText_="Play",tP.registerComponent("PlayToggle",iH);class iV extends tP{constructor(e,t){super(e,t),this.on(e,["timeupdate","ended","seeking"],e=>this.update(e)),this.updateTextNode_()}createEl(){let e=this.buildCSSClass(),t=super.createEl("div",{className:`${e} vjs-time-control vjs-control`}),i=eC("span",{className:"vjs-control-text",textContent:`${this.localize(this.labelText_)}\u00a0`},{role:"presentation"});return t.appendChild(i),this.contentEl_=eC("span",{className:`${e}-display`},{role:"presentation"}),t.appendChild(this.contentEl_),t}dispose(){this.contentEl_=null,this.textNode_=null,super.dispose()}update(e){(this.player_.options_.enableSmoothSeeking||"seeking"!==e.type)&&this.updateContent(e)}updateTextNode_(e=0){e=tB(e),this.formattedTime_!==e&&(this.formattedTime_=e,this.requestNamedAnimationFrame("TimeDisplay#updateTextNode_",()=>{if(!this.contentEl_)return;let e=this.textNode_;e&&this.contentEl_.firstChild!==e&&(e=null,N.warn("TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.")),this.textNode_=c().createTextNode(this.formattedTime_),this.textNode_&&(e?this.contentEl_.replaceChild(this.textNode_,e):this.contentEl_.appendChild(this.textNode_))}))}updateContent(e){}}iV.prototype.labelText_="Time",iV.prototype.controlText_="Time",tP.registerComponent("TimeDisplay",iV);class iz extends iV{buildCSSClass(){return"vjs-current-time"}updateContent(e){let t;t=this.player_.ended()?this.player_.duration():this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime(),this.updateTextNode_(t)}}iz.prototype.labelText_="Current Time",iz.prototype.controlText_="Current Time",tP.registerComponent("CurrentTimeDisplay",iz);class iW extends iV{constructor(e,t){super(e,t);let i=e=>this.updateContent(e);this.on(e,"durationchange",i),this.on(e,"loadstart",i),this.on(e,"loadedmetadata",i)}buildCSSClass(){return"vjs-duration"}updateContent(e){let t=this.player_.duration();this.updateTextNode_(t)}}iW.prototype.labelText_="Duration",iW.prototype.controlText_="Duration",tP.registerComponent("DurationDisplay",iW);class iG extends tP{createEl(){let e=super.createEl("div",{className:"vjs-time-control vjs-time-divider"},{"aria-hidden":!0}),t=super.createEl("div"),i=super.createEl("span",{textContent:"/"});return t.appendChild(i),e.appendChild(t),e}}tP.registerComponent("TimeDivider",iG);class iK extends iV{constructor(e,t){super(e,t),this.on(e,"durationchange",e=>this.updateContent(e))}buildCSSClass(){return"vjs-remaining-time"}createEl(){let e=super.createEl();return!1!==this.options_.displayNegative&&e.insertBefore(eC("span",{},{"aria-hidden":!0},"-"),this.contentEl_),e}updateContent(e){let t;"number"==typeof this.player_.duration()&&(t=this.player_.ended()?0:this.player_.remainingTimeDisplay?this.player_.remainingTimeDisplay():this.player_.remainingTime(),this.updateTextNode_(t))}}iK.prototype.labelText_="Remaining Time",iK.prototype.controlText_="Remaining Time",tP.registerComponent("RemainingTimeDisplay",iK);class iQ extends tP{constructor(e,t){super(e,t),this.updateShowing(),this.on(this.player(),"durationchange",e=>this.updateShowing(e))}createEl(){let e=super.createEl("div",{className:"vjs-live-control vjs-control"});return this.contentEl_=eC("div",{className:"vjs-live-display"},{"aria-live":"off"}),this.contentEl_.appendChild(eC("span",{className:"vjs-control-text",textContent:`${this.localize("Stream Type")}\u00a0`})),this.contentEl_.appendChild(c().createTextNode(this.localize("LIVE"))),e.appendChild(this.contentEl_),e}dispose(){this.contentEl_=null,super.dispose()}updateShowing(e){this.player().duration()===1/0?this.show():this.hide()}}tP.registerComponent("LiveDisplay",iQ);class iY extends iF{constructor(e,t){super(e,t),this.updateLiveEdgeStatus(),this.player_.liveTracker&&(this.updateLiveEdgeStatusHandler_=e=>this.updateLiveEdgeStatus(e),this.on(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_))}createEl(){let e=super.createEl("button",{className:"vjs-seek-to-live-control vjs-control"});return this.setIcon("circle",e),this.textEl_=eC("span",{className:"vjs-seek-to-live-text",textContent:this.localize("LIVE")},{"aria-hidden":"true"}),e.appendChild(this.textEl_),e}updateLiveEdgeStatus(){!this.player_.liveTracker||this.player_.liveTracker.atLiveEdge()?(this.setAttribute("aria-disabled",!0),this.addClass("vjs-at-live-edge"),this.controlText("Seek to live, currently playing live")):(this.setAttribute("aria-disabled",!1),this.removeClass("vjs-at-live-edge"),this.controlText("Seek to live, currently behind live"))}handleClick(){this.player_.liveTracker.seekToLiveEdge()}dispose(){this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.updateLiveEdgeStatusHandler_),this.textEl_=null,super.dispose()}}function iX(e,t,i){return Math.min(i,Math.max(t,isNaN(e=Number(e))?t:e))}iY.prototype.controlText_="Seek to live, currently playing live",tP.registerComponent("SeekToLive",iY);var iJ=Object.freeze({__proto__:null,clamp:iX});class iZ extends tP{constructor(e,t){super(e,t),this.handleMouseDown_=e=>this.handleMouseDown(e),this.handleMouseUp_=e=>this.handleMouseUp(e),this.handleKeyDown_=e=>this.handleKeyDown(e),this.handleClick_=e=>this.handleClick(e),this.handleMouseMove_=e=>this.handleMouseMove(e),this.update_=e=>this.update(e),this.bar=this.getChild(this.options_.barName),this.vertical(!!this.options_.vertical),this.enable()}enabled(){return this.enabled_}enable(){!this.enabled()&&(this.on("mousedown",this.handleMouseDown_),this.on("touchstart",this.handleMouseDown_),this.on("keydown",this.handleKeyDown_),this.on("click",this.handleClick_),this.on(this.player_,"controlsvisible",this.update),this.playerEvent&&this.on(this.player_,this.playerEvent,this.update),this.removeClass("disabled"),this.setAttribute("tabindex",0),this.enabled_=!0)}disable(){if(!this.enabled())return;let e=this.bar.el_.ownerDocument;this.off("mousedown",this.handleMouseDown_),this.off("touchstart",this.handleMouseDown_),this.off("keydown",this.handleKeyDown_),this.off("click",this.handleClick_),this.off(this.player_,"controlsvisible",this.update_),this.off(e,"mousemove",this.handleMouseMove_),this.off(e,"mouseup",this.handleMouseUp_),this.off(e,"touchmove",this.handleMouseMove_),this.off(e,"touchend",this.handleMouseUp_),this.removeAttribute("tabindex"),this.addClass("disabled"),this.playerEvent&&this.off(this.player_,this.playerEvent,this.update),this.enabled_=!1}createEl(e,t={},i={}){return t.className=t.className+" vjs-slider",t=Object.assign({tabIndex:0},t),i=Object.assign({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100},i),super.createEl(e,t,i)}handleMouseDown(e){let t=this.bar.el_.ownerDocument;"mousedown"===e.type&&e.preventDefault(),"touchstart"!==e.type||ei||e.preventDefault(),eR(),this.addClass("vjs-sliding"),this.trigger("slideractive"),this.on(t,"mousemove",this.handleMouseMove_),this.on(t,"mouseup",this.handleMouseUp_),this.on(t,"touchmove",this.handleMouseMove_),this.on(t,"touchend",this.handleMouseUp_),this.handleMouseMove(e,!0)}handleMouseMove(e){}handleMouseUp(e){let t=this.bar.el_.ownerDocument;eB(),this.removeClass("vjs-sliding"),this.trigger("sliderinactive"),this.off(t,"mousemove",this.handleMouseMove_),this.off(t,"mouseup",this.handleMouseUp_),this.off(t,"touchmove",this.handleMouseMove_),this.off(t,"touchend",this.handleMouseUp_),this.update()}update(){if(!this.el_||!this.bar)return;let e=this.getProgress();return e===this.progress_||(this.progress_=e,this.requestNamedAnimationFrame("Slider#update",()=>{let t=this.vertical()?"height":"width";this.bar.el().style[t]=(100*e).toFixed(2)+"%"})),e}getProgress(){return Number(iX(this.getPercent(),0,1).toFixed(4))}calculateDistance(e){let t=eF(this.el_,e);return this.vertical()?t.y:t.x}handleKeyDown(e){let t=this.options_.playerOptions.spatialNavigation,i=t&&t.enabled,s=t&&t.horizontalSeek;i?s&&"ArrowLeft"===e.key||!s&&"ArrowDown"===e.key?(e.preventDefault(),e.stopPropagation(),this.stepBack()):s&&"ArrowRight"===e.key||!s&&"ArrowUp"===e.key?(e.preventDefault(),e.stopPropagation(),this.stepForward()):super.handleKeyDown(e):"ArrowLeft"===e.key||"ArrowDown"===e.key?(e.preventDefault(),e.stopPropagation(),this.stepBack()):"ArrowUp"===e.key||"ArrowRight"===e.key?(e.preventDefault(),e.stopPropagation(),this.stepForward()):super.handleKeyDown(e)}handleClick(e){e.stopPropagation(),e.preventDefault()}vertical(e){if(void 0===e)return this.vertical_||!1;this.vertical_=!!e,this.vertical_?this.addClass("vjs-slider-vertical"):this.addClass("vjs-slider-horizontal")}}tP.registerComponent("Slider",iZ);let i0=(e,t)=>iX(e/t*100,0,100).toFixed(2)+"%";class i1 extends tP{constructor(e,t){super(e,t),this.partEls_=[],this.on(e,"progress",e=>this.update(e))}createEl(){let e=super.createEl("div",{className:"vjs-load-progress"}),t=eC("span",{className:"vjs-control-text"}),i=eC("span",{textContent:this.localize("Loaded")}),s=c().createTextNode(": ");return this.percentageEl_=eC("span",{className:"vjs-control-text-loaded-percentage",textContent:"0%"}),e.appendChild(t),t.appendChild(i),t.appendChild(s),t.appendChild(this.percentageEl_),e}dispose(){this.partEls_=null,this.percentageEl_=null,super.dispose()}update(e){this.requestNamedAnimationFrame("LoadProgressBar#update",()=>{let e=this.player_.liveTracker,t=this.player_.buffered(),i=e&&e.isLive()?e.seekableEnd():this.player_.duration(),s=this.player_.bufferedEnd(),r=this.partEls_,n=i0(s,i);this.percent_!==n&&(this.el_.style.width=n,ew(this.percentageEl_,n),this.percent_=n);for(let e=0;et.length;e--)this.el_.removeChild(r[e-1]);r.length=t.length})}}tP.registerComponent("LoadProgressBar",i1);class i2 extends tP{constructor(e,t){super(e,t),this.update=tl(to(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-time-tooltip"},{"aria-hidden":"true"})}update(e,t,i){let s=ej(this.el_),r=eN(this.player_.el()),n=e.width*t;if(!r||!s)return;let a=e.left-r.left+n,o=e.width-n+(r.right-e.right);o||(o=e.width-n,a=n);let l=s.width/2;as.width&&(l=s.width),l=Math.round(l),this.el_.style.right=`-${l}px`,this.write(i)}write(e){ew(this.el_,e)}updateTime(e,t,i,s){this.requestNamedAnimationFrame("TimeTooltip#updateTime",()=>{let r;let n=this.player_.duration();if(this.player_.liveTracker&&this.player_.liveTracker.isLive()){let e=this.player_.liveTracker.liveWindow(),i=e-t*e;r=(i<1?"":"-")+tB(i,e)}else r=tB(i,n);this.update(e,t,r),s&&s()})}}tP.registerComponent("TimeTooltip",i2);class i4 extends tP{constructor(e,t){super(e,t),this.setIcon("circle"),this.update=tl(to(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-play-progress vjs-slider-bar"},{"aria-hidden":"true"})}update(e,t){let i=this.getChild("timeTooltip");if(!i)return;let s=this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime();i.updateTime(e,t,s)}}i4.prototype.options_={children:[]},ef||J||i4.prototype.options_.children.push("timeTooltip"),tP.registerComponent("PlayProgressBar",i4);class i8 extends tP{constructor(e,t){super(e,t),this.update=tl(to(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t){let i=t*this.player_.duration();this.getChild("timeTooltip").updateTime(e,t,i,()=>{this.el_.style.left=`${e.width*t}px`})}}i8.prototype.options_={children:["timeTooltip"]},tP.registerComponent("MouseTimeDisplay",i8);class i5 extends iZ{constructor(e,t){(t=W(i5.prototype.options_,t)).children=[...t.children];let i=e.options_.disableSeekWhileScrubbingOnMobile&&(ef||J);(ef||J)&&!i||t.children.splice(1,0,"mouseTimeDisplay"),super(e,t),this.shouldDisableSeekWhileScrubbingOnMobile_=i,this.pendingSeekTime_=null,this.setEventHandlers_()}setEventHandlers_(){this.update_=to(this,this.update),this.update=tl(this.update_,30),this.on(this.player_,["durationchange","timeupdate"],this.update),this.on(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.on(this.player_.liveTracker,"liveedgechange",this.update),this.updateInterval=null,this.enableIntervalHandler_=e=>this.enableInterval_(e),this.disableIntervalHandler_=e=>this.disableInterval_(e),this.on(this.player_,["playing"],this.enableIntervalHandler_),this.on(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in c()&&"visibilityState"in c()&&this.on(c(),"visibilitychange",this.toggleVisibility_)}toggleVisibility_(e){"hidden"===c().visibilityState?(this.cancelNamedAnimationFrame("SeekBar#update"),this.cancelNamedAnimationFrame("Slider#update"),this.disableInterval_(e)):(this.player_.ended()||this.player_.paused()||this.enableInterval_(),this.update())}enableInterval_(){!this.updateInterval&&(this.updateInterval=this.setInterval(this.update,30))}disableInterval_(e){(!(this.player_.liveTracker&&this.player_.liveTracker.isLive())||!e||"ended"===e.type)&&this.updateInterval&&(this.clearInterval(this.updateInterval),this.updateInterval=null)}createEl(){return super.createEl("div",{className:"vjs-progress-holder"},{"aria-label":this.localize("Progress Bar")})}update(e){if("hidden"===c().visibilityState)return;let t=super.update();return this.requestNamedAnimationFrame("SeekBar#update",()=>{let e=this.player_.ended()?this.player_.duration():this.getCurrentTime_(),i=this.player_.liveTracker,s=this.player_.duration();i&&i.isLive()&&(s=this.player_.liveTracker.liveCurrentTime()),this.percent_!==t&&(this.el_.setAttribute("aria-valuenow",(100*t).toFixed(2)),this.percent_=t),(this.currentTime_!==e||this.duration_!==s)&&(this.el_.setAttribute("aria-valuetext",this.localize("progress bar timing: currentTime={1} duration={2}",[tB(e,s),tB(s,s)],"{1} of {2}")),this.currentTime_=e,this.duration_=s),this.bar&&this.bar.update(eN(this.el()),this.getProgress())}),t}userSeek_(e){this.player_.liveTracker&&this.player_.liveTracker.isLive()&&this.player_.liveTracker.nextSeekedFromUser(),this.player_.currentTime(e)}getCurrentTime_(){return this.player_.scrubbing()?this.player_.getCache().currentTime:this.player_.currentTime()}getPercent(){let e;if(this.pendingSeekTime_)return this.pendingSeekTime_/this.player_.duration();let t=this.getCurrentTime_(),i=this.player_.liveTracker;return i&&i.isLive()?(e=(t-i.seekableStart())/i.liveWindow(),i.atLiveEdge()&&(e=1)):e=t/this.player_.duration(),e}handleMouseDown(e){eW(e)&&(e.stopPropagation(),this.videoWasPlaying=!this.player_.paused(),this.shouldDisableSeekWhileScrubbingOnMobile_||this.player_.pause(),super.handleMouseDown(e))}handleMouseMove(e,t=!1){let i;if(!eW(e)||isNaN(this.player_.duration()))return;t||this.player_.scrubbing()||this.player_.scrubbing(!0);let s=this.calculateDistance(e),r=this.player_.liveTracker;if(r&&r.isLive()){if(s>=.99){r.seekToLiveEdge();return}let e=r.seekableStart(),t=r.liveCurrentTime();if((i=e+s*r.liveWindow())>=t&&(i=t),i<=e&&(i=e+.1),i===1/0)return}else(i=s*this.player_.duration())===this.player_.duration()&&(i-=.1);this.shouldDisableSeekWhileScrubbingOnMobile_?this.pendingSeekTime_=i:this.userSeek_(i),this.player_.options_.enableSmoothSeeking&&this.update()}enable(){super.enable();let e=this.getChild("mouseTimeDisplay");e&&e.show()}disable(){super.disable();let e=this.getChild("mouseTimeDisplay");e&&e.hide()}handleMouseUp(e){super.handleMouseUp(e),e&&e.stopPropagation(),this.player_.scrubbing(!1),this.pendingSeekTime_&&(this.userSeek_(this.pendingSeekTime_),this.pendingSeekTime_=null),this.player_.trigger({type:"timeupdate",target:this,manuallyTriggered:!0}),this.videoWasPlaying?tq(this.player_.play()):this.update_()}stepForward(){this.userSeek_(this.player_.currentTime()+5)}stepBack(){this.userSeek_(this.player_.currentTime()-5)}handleAction(e){this.player_.paused()?this.player_.play():this.player_.pause()}handleKeyDown(e){let t=this.player_.liveTracker;if(" "===e.key||"Enter"===e.key)e.preventDefault(),e.stopPropagation(),this.handleAction(e);else if("Home"===e.key)e.preventDefault(),e.stopPropagation(),this.userSeek_(0);else if("End"===e.key)e.preventDefault(),e.stopPropagation(),t&&t.isLive()?this.userSeek_(t.liveCurrentTime()):this.userSeek_(this.player_.duration());else if(/^[0-9]$/.test(e.key)){e.preventDefault(),e.stopPropagation();let i=.1*parseInt(e.key,10);t&&t.isLive()?this.userSeek_(t.seekableStart()+t.liveWindow()*i):this.userSeek_(this.player_.duration()*i)}else"PageDown"===e.key?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()-60)):"PageUp"===e.key?(e.preventDefault(),e.stopPropagation(),this.userSeek_(this.player_.currentTime()+60)):super.handleKeyDown(e)}dispose(){this.disableInterval_(),this.off(this.player_,["durationchange","timeupdate"],this.update),this.off(this.player_,["ended"],this.update_),this.player_.liveTracker&&this.off(this.player_.liveTracker,"liveedgechange",this.update),this.off(this.player_,["playing"],this.enableIntervalHandler_),this.off(this.player_,["ended","pause","waiting"],this.disableIntervalHandler_),"hidden"in c()&&"visibilityState"in c()&&this.off(c(),"visibilitychange",this.toggleVisibility_),super.dispose()}}i5.prototype.options_={children:["loadProgressBar","playProgressBar"],barName:"playProgressBar"},tP.registerComponent("SeekBar",i5);class i3 extends tP{constructor(e,t){super(e,t),this.handleMouseMove=tl(to(this,this.handleMouseMove),30),this.throttledHandleMouseSeek=tl(to(this,this.handleMouseSeek),30),this.handleMouseUpHandler_=e=>this.handleMouseUp(e),this.handleMouseDownHandler_=e=>this.handleMouseDown(e),this.enable()}createEl(){return super.createEl("div",{className:"vjs-progress-control vjs-control"})}handleMouseMove(e){let t=this.getChild("seekBar");if(!t)return;let i=t.getChild("playProgressBar"),s=t.getChild("mouseTimeDisplay");if(!i&&!s)return;let r=t.el(),n=ej(r),a=eF(r,e).x;a=iX(a,0,1),s&&s.update(n,a),i&&i.update(n,t.getProgress())}handleMouseSeek(e){let t=this.getChild("seekBar");t&&t.handleMouseMove(e)}enabled(){return this.enabled_}disable(){if(this.children().forEach(e=>e.disable&&e.disable()),this.enabled()&&(this.off(["mousedown","touchstart"],this.handleMouseDownHandler_),this.off(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeListenersAddedOnMousedownAndTouchstart(),this.addClass("disabled"),this.enabled_=!1,this.player_.scrubbing())){let e=this.getChild("seekBar");this.player_.scrubbing(!1),e.videoWasPlaying&&tq(this.player_.play())}}enable(){this.children().forEach(e=>e.enable&&e.enable()),!this.enabled()&&(this.on(["mousedown","touchstart"],this.handleMouseDownHandler_),this.on(this.el_,["mousemove","touchmove"],this.handleMouseMove),this.removeClass("disabled"),this.enabled_=!0)}removeListenersAddedOnMousedownAndTouchstart(){let e=this.el_.ownerDocument;this.off(e,"mousemove",this.throttledHandleMouseSeek),this.off(e,"touchmove",this.throttledHandleMouseSeek),this.off(e,"mouseup",this.handleMouseUpHandler_),this.off(e,"touchend",this.handleMouseUpHandler_)}handleMouseDown(e){let t=this.el_.ownerDocument,i=this.getChild("seekBar");i&&i.handleMouseDown(e),this.on(t,"mousemove",this.throttledHandleMouseSeek),this.on(t,"touchmove",this.throttledHandleMouseSeek),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){let t=this.getChild("seekBar");t&&t.handleMouseUp(e),this.removeListenersAddedOnMousedownAndTouchstart()}}i3.prototype.options_={children:["seekBar"]},tP.registerComponent("ProgressControl",i3);class i6 extends iF{constructor(e,t){super(e,t),this.setIcon("picture-in-picture-enter"),this.on(e,["enterpictureinpicture","leavepictureinpicture"],e=>this.handlePictureInPictureChange(e)),this.on(e,["disablepictureinpicturechanged","loadedmetadata"],e=>this.handlePictureInPictureEnabledChange(e)),this.on(e,["loadedmetadata","audioonlymodechange","audiopostermodechange"],()=>this.handlePictureInPictureAudioModeChange()),this.disable()}buildCSSClass(){return`vjs-picture-in-picture-control vjs-hidden ${super.buildCSSClass()}`}handlePictureInPictureAudioModeChange(){if(!("audio"===this.player_.currentType().substring(0,5)||this.player_.audioPosterMode()||this.player_.audioOnlyMode())){this.show();return}this.player_.isInPictureInPicture()&&this.player_.exitPictureInPicture(),this.hide()}handlePictureInPictureEnabledChange(){c().pictureInPictureEnabled&&!1===this.player_.disablePictureInPicture()||this.player_.options_.enableDocumentPictureInPicture&&"documentPictureInPicture"in d()?this.enable():this.disable()}handlePictureInPictureChange(e){this.player_.isInPictureInPicture()?(this.setIcon("picture-in-picture-exit"),this.controlText("Exit Picture-in-Picture")):(this.setIcon("picture-in-picture-enter"),this.controlText("Picture-in-Picture")),this.handlePictureInPictureEnabledChange()}handleClick(e){this.player_.isInPictureInPicture()?this.player_.exitPictureInPicture():this.player_.requestPictureInPicture()}show(){"function"==typeof c().exitPictureInPicture&&super.show()}}i6.prototype.controlText_="Picture-in-Picture",tP.registerComponent("PictureInPictureToggle",i6);class i7 extends iF{constructor(e,t){super(e,t),this.setIcon("fullscreen-enter"),this.on(e,"fullscreenchange",e=>this.handleFullscreenChange(e)),!1===c()[e.fsApi_.fullscreenEnabled]&&this.disable()}buildCSSClass(){return`vjs-fullscreen-control ${super.buildCSSClass()}`}handleFullscreenChange(e){this.player_.isFullscreen()?(this.controlText("Exit Fullscreen"),this.setIcon("fullscreen-exit")):(this.controlText("Fullscreen"),this.setIcon("fullscreen-enter"))}handleClick(e){this.player_.isFullscreen()?this.player_.exitFullscreen():this.player_.requestFullscreen()}}i7.prototype.controlText_="Fullscreen",tP.registerComponent("FullscreenToggle",i7);let i9=function(e,t){t.tech_&&!t.tech_.featuresVolumeControl&&e.addClass("vjs-hidden"),e.on(t,"loadstart",function(){t.tech_.featuresVolumeControl?e.removeClass("vjs-hidden"):e.addClass("vjs-hidden")})};class se extends tP{createEl(){let e=super.createEl("div",{className:"vjs-volume-level"});return this.setIcon("circle",e),e.appendChild(super.createEl("span",{className:"vjs-control-text"})),e}}tP.registerComponent("VolumeLevel",se);class st extends tP{constructor(e,t){super(e,t),this.update=tl(to(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-volume-tooltip"},{"aria-hidden":"true"})}update(e,t,i,s){if(!i){let i=eN(this.el_),s=eN(this.player_.el()),r=e.width*t;if(!s||!i)return;let n=e.left-s.left+r,a=e.width-r+(s.right-e.right),o=i.width/2;ni.width&&(o=i.width),this.el_.style.right=`-${o}px`}this.write(`${s}%`)}write(e){ew(this.el_,e)}updateVolume(e,t,i,s,r){this.requestNamedAnimationFrame("VolumeLevelTooltip#updateVolume",()=>{this.update(e,t,i,s.toFixed(0)),r&&r()})}}tP.registerComponent("VolumeLevelTooltip",st);class si extends tP{constructor(e,t){super(e,t),this.update=tl(to(this,this.update),30)}createEl(){return super.createEl("div",{className:"vjs-mouse-display"})}update(e,t,i){this.getChild("volumeLevelTooltip").updateVolume(e,t,i,100*t,()=>{i?this.el_.style.bottom=`${e.height*t}px`:this.el_.style.left=`${e.width*t}px`})}}si.prototype.options_={children:["volumeLevelTooltip"]},tP.registerComponent("MouseVolumeLevelDisplay",si);class ss extends iZ{constructor(e,t){super(e,t),this.on("slideractive",e=>this.updateLastVolume_(e)),this.on(e,"volumechange",e=>this.updateARIAAttributes(e)),e.ready(()=>this.updateARIAAttributes())}createEl(){return super.createEl("div",{className:"vjs-volume-bar vjs-slider-bar"},{"aria-label":this.localize("Volume Level"),"aria-live":"polite"})}handleMouseDown(e){eW(e)&&super.handleMouseDown(e)}handleMouseMove(e){let t=this.getChild("mouseVolumeLevelDisplay");if(t){let i=this.el(),s=eN(i),r=this.vertical(),n=eF(i,e);n=iX(n=r?n.y:n.x,0,1),t.update(s,n,r)}eW(e)&&(this.checkMuted(),this.player_.volume(this.calculateDistance(e)))}checkMuted(){this.player_.muted()&&this.player_.muted(!1)}getPercent(){return this.player_.muted()?0:this.player_.volume()}stepForward(){this.checkMuted(),this.player_.volume(this.player_.volume()+.1)}stepBack(){this.checkMuted(),this.player_.volume(this.player_.volume()-.1)}updateARIAAttributes(e){let t=this.player_.muted()?0:this.volumeAsPercentage_();this.el_.setAttribute("aria-valuenow",t),this.el_.setAttribute("aria-valuetext",t+"%")}volumeAsPercentage_(){return Math.round(100*this.player_.volume())}updateLastVolume_(){let e=this.player_.volume();this.one("sliderinactive",()=>{0===this.player_.volume()&&this.player_.lastVolume_(e)})}}ss.prototype.options_={children:["volumeLevel"],barName:"volumeLevel"},ef||J||ss.prototype.options_.children.splice(0,0,"mouseVolumeLevelDisplay"),ss.prototype.playerEvent="volumechange",tP.registerComponent("VolumeBar",ss);class sr extends tP{constructor(e,t={}){t.vertical=t.vertical||!1,(void 0===t.volumeBar||z(t.volumeBar))&&(t.volumeBar=t.volumeBar||{},t.volumeBar.vertical=t.vertical),super(e,t),i9(this,e),this.throttledHandleMouseMove=tl(to(this,this.handleMouseMove),30),this.handleMouseUpHandler_=e=>this.handleMouseUp(e),this.on("mousedown",e=>this.handleMouseDown(e)),this.on("touchstart",e=>this.handleMouseDown(e)),this.on("mousemove",e=>this.handleMouseMove(e)),this.on(this.volumeBar,["focus","slideractive"],()=>{this.volumeBar.addClass("vjs-slider-active"),this.addClass("vjs-slider-active"),this.trigger("slideractive")}),this.on(this.volumeBar,["blur","sliderinactive"],()=>{this.volumeBar.removeClass("vjs-slider-active"),this.removeClass("vjs-slider-active"),this.trigger("sliderinactive")})}createEl(){let e="vjs-volume-horizontal";return this.options_.vertical&&(e="vjs-volume-vertical"),super.createEl("div",{className:`vjs-volume-control vjs-control ${e}`})}handleMouseDown(e){let t=this.el_.ownerDocument;this.on(t,"mousemove",this.throttledHandleMouseMove),this.on(t,"touchmove",this.throttledHandleMouseMove),this.on(t,"mouseup",this.handleMouseUpHandler_),this.on(t,"touchend",this.handleMouseUpHandler_)}handleMouseUp(e){let t=this.el_.ownerDocument;this.off(t,"mousemove",this.throttledHandleMouseMove),this.off(t,"touchmove",this.throttledHandleMouseMove),this.off(t,"mouseup",this.handleMouseUpHandler_),this.off(t,"touchend",this.handleMouseUpHandler_)}handleMouseMove(e){this.volumeBar.handleMouseMove(e)}}sr.prototype.options_={children:["volumeBar"]},tP.registerComponent("VolumeControl",sr);let sn=function(e,t){t.tech_&&!t.tech_.featuresMuteControl&&e.addClass("vjs-hidden"),e.on(t,"loadstart",function(){t.tech_.featuresMuteControl?e.removeClass("vjs-hidden"):e.addClass("vjs-hidden")})};class sa extends iF{constructor(e,t){super(e,t),sn(this,e),this.on(e,["loadstart","volumechange"],e=>this.update(e))}buildCSSClass(){return`vjs-mute-control ${super.buildCSSClass()}`}handleClick(e){let t=this.player_.volume(),i=this.player_.lastVolume_();0===t?(this.player_.volume(i<.1?.1:i),this.player_.muted(!1)):this.player_.muted(!this.player_.muted())}update(e){this.updateIcon_(),this.updateControlText_()}updateIcon_(){let e=this.player_.volume(),t=3;this.setIcon("volume-high"),ef&&this.player_.tech_&&this.player_.tech_.el_&&this.player_.muted(this.player_.tech_.el_.muted),0===e||this.player_.muted()?(this.setIcon("volume-mute"),t=0):e<.33?(this.setIcon("volume-low"),t=1):e<.67&&(this.setIcon("volume-medium"),t=2),eP(this.el_,[0,1,2,3].reduce((e,t)=>e+`${t?" ":""}vjs-vol-${t}`,"")),eI(this.el_,`vjs-vol-${t}`)}updateControlText_(){let e=this.player_.muted()||0===this.player_.volume()?"Unmute":"Mute";this.controlText()!==e&&this.controlText(e)}}sa.prototype.controlText_="Mute",tP.registerComponent("MuteToggle",sa);class so extends tP{constructor(e,t={}){void 0!==t.inline?t.inline=t.inline:t.inline=!0,(void 0===t.volumeControl||z(t.volumeControl))&&(t.volumeControl=t.volumeControl||{},t.volumeControl.vertical=!t.inline),super(e,t),this.handleKeyPressHandler_=e=>this.handleKeyPress(e),this.on(e,["loadstart"],e=>this.volumePanelState_(e)),this.on(this.muteToggle,"keyup",e=>this.handleKeyPress(e)),this.on(this.volumeControl,"keyup",e=>this.handleVolumeControlKeyUp(e)),this.on("keydown",e=>this.handleKeyPress(e)),this.on("mouseover",e=>this.handleMouseOver(e)),this.on("mouseout",e=>this.handleMouseOut(e)),this.on(this.volumeControl,["slideractive"],this.sliderActive_),this.on(this.volumeControl,["sliderinactive"],this.sliderInactive_)}sliderActive_(){this.addClass("vjs-slider-active")}sliderInactive_(){this.removeClass("vjs-slider-active")}volumePanelState_(){this.volumeControl.hasClass("vjs-hidden")&&this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-hidden"),this.volumeControl.hasClass("vjs-hidden")&&!this.muteToggle.hasClass("vjs-hidden")&&this.addClass("vjs-mute-toggle-only")}createEl(){let e="vjs-volume-panel-horizontal";return this.options_.inline||(e="vjs-volume-panel-vertical"),super.createEl("div",{className:`vjs-volume-panel vjs-control ${e}`})}dispose(){this.handleMouseOut(),super.dispose()}handleVolumeControlKeyUp(e){"Escape"===e.key&&this.muteToggle.focus()}handleMouseOver(e){this.addClass("vjs-hover"),tt(c(),"keyup",this.handleKeyPressHandler_)}handleMouseOut(e){this.removeClass("vjs-hover"),ti(c(),"keyup",this.handleKeyPressHandler_)}handleKeyPress(e){"Escape"===e.key&&this.handleMouseOut()}}so.prototype.options_={children:["muteToggle","volumeControl"]},tP.registerComponent("VolumePanel",so);class sl extends iF{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipForwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`forward-${this.skipTime}`),this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipForwardTime(){let e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.forward}buildCSSClass(){return`vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`}handleClick(e){let t;if(isNaN(this.player_.duration()))return;let i=this.player_.currentTime(),s=this.player_.liveTracker,r=s&&s.isLive()?s.seekableEnd():this.player_.duration();t=i+this.skipTime<=r?i+this.skipTime:r,this.player_.currentTime(t)}handleLanguagechange(){this.controlText(this.localize("Skip forward {1} seconds",[this.skipTime]))}}sl.prototype.controlText_="Skip Forward",tP.registerComponent("SkipForward",sl);class sh extends iF{constructor(e,t){super(e,t),this.validOptions=[5,10,30],this.skipTime=this.getSkipBackwardTime(),this.skipTime&&this.validOptions.includes(this.skipTime)?(this.setIcon(`replay-${this.skipTime}`),this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime.toLocaleString(e.language())])),this.show()):this.hide()}getSkipBackwardTime(){let e=this.options_.playerOptions;return e.controlBar&&e.controlBar.skipButtons&&e.controlBar.skipButtons.backward}buildCSSClass(){return`vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`}handleClick(e){let t;let i=this.player_.currentTime(),s=this.player_.liveTracker,r=s&&s.isLive()&&s.seekableStart();t=r&&i-this.skipTime<=r?r:i>=this.skipTime?i-this.skipTime:0,this.player_.currentTime(t)}handleLanguagechange(){this.controlText(this.localize("Skip backward {1} seconds",[this.skipTime]))}}sh.prototype.controlText_="Skip Backward",tP.registerComponent("SkipBackward",sh);class sd extends tP{constructor(e,t){super(e,t),t&&(this.menuButton_=t.menuButton),this.focusedChild_=-1,this.on("keydown",e=>this.handleKeyDown(e)),this.boundHandleBlur_=e=>this.handleBlur(e),this.boundHandleTapClick_=e=>this.handleTapClick(e)}addEventListenerForItem(e){e instanceof tP&&(this.on(e,"blur",this.boundHandleBlur_),this.on(e,["tap","click"],this.boundHandleTapClick_))}removeEventListenerForItem(e){e instanceof tP&&(this.off(e,"blur",this.boundHandleBlur_),this.off(e,["tap","click"],this.boundHandleTapClick_))}removeChild(e){"string"==typeof e&&(e=this.getChild(e)),this.removeEventListenerForItem(e),super.removeChild(e)}addItem(e){let t=this.addChild(e);t&&this.addEventListenerForItem(t)}createEl(){let e=this.options_.contentElType||"ul";this.contentEl_=eC(e,{className:"vjs-menu-content"}),this.contentEl_.setAttribute("role","menu");let t=super.createEl("div",{append:this.contentEl_,className:"vjs-menu"});return t.appendChild(this.contentEl_),tt(t,"click",function(e){e.preventDefault(),e.stopImmediatePropagation()}),t}dispose(){this.contentEl_=null,this.boundHandleBlur_=null,this.boundHandleTapClick_=null,super.dispose()}handleBlur(e){let t=e.relatedTarget||c().activeElement;if(!this.children().some(e=>e.el()===t)){let e=this.menuButton_;e&&e.buttonPressed_&&t!==e.el().firstChild&&e.unpressButton()}}handleTapClick(e){if(this.menuButton_){this.menuButton_.unpressButton();let t=this.children();if(!Array.isArray(t))return;let i=t.filter(t=>t.el()===e.target)[0];i&&"CaptionSettingsMenuItem"!==i.name()&&this.menuButton_.focus()}}handleKeyDown(e){"ArrowLeft"===e.key||"ArrowDown"===e.key?(e.preventDefault(),e.stopPropagation(),this.stepForward()):("ArrowRight"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),e.stopPropagation(),this.stepBack())}stepForward(){let e=0;void 0!==this.focusedChild_&&(e=this.focusedChild_+1),this.focus(e)}stepBack(){let e=0;void 0!==this.focusedChild_&&(e=this.focusedChild_-1),this.focus(e)}focus(e=0){let t=this.children().slice();t.length&&t[0].hasClass("vjs-menu-title")&&t.shift(),t.length>0&&(e<0?e=0:e>=t.length&&(e=t.length-1),this.focusedChild_=e,t[e].el_.focus())}}tP.registerComponent("Menu",sd);class su extends tP{constructor(e,t={}){super(e,t),this.menuButton_=new iF(e,t),this.menuButton_.controlText(this.controlText_),this.menuButton_.el_.setAttribute("aria-haspopup","true");let i=iF.prototype.buildCSSClass();this.menuButton_.el_.className=this.buildCSSClass()+" "+i,this.menuButton_.removeClass("vjs-control"),this.addChild(this.menuButton_),this.update(),this.enabled_=!0;let s=e=>this.handleClick(e);this.handleMenuKeyUp_=e=>this.handleMenuKeyUp(e),this.on(this.menuButton_,"tap",s),this.on(this.menuButton_,"click",s),this.on(this.menuButton_,"keydown",e=>this.handleKeyDown(e)),this.on(this.menuButton_,"mouseenter",()=>{this.addClass("vjs-hover"),this.menu.show(),tt(c(),"keyup",this.handleMenuKeyUp_)}),this.on("mouseleave",e=>this.handleMouseLeave(e)),this.on("keydown",e=>this.handleSubmenuKeyDown(e))}update(){let e=this.createMenu();this.menu&&(this.menu.dispose(),this.removeChild(this.menu)),this.menu=e,this.addChild(e),this.buttonPressed_=!1,this.menuButton_.el_.setAttribute("aria-expanded","false"),this.items&&this.items.length<=this.hideThreshold_?(this.hide(),this.menu.contentEl_.removeAttribute("role")):(this.show(),this.menu.contentEl_.setAttribute("role","menu"))}createMenu(){let e=new sd(this.player_,{menuButton:this});if(this.hideThreshold_=0,this.options_.title){let t=eC("li",{className:"vjs-menu-title",textContent:tE(this.options_.title),tabIndex:-1}),i=new tP(this.player_,{el:t});e.addItem(i)}if(this.items=this.createItems(),this.items)for(let t=0;t{this.handleTracksChange.apply(this,e)},n=(...e)=>{this.handleSelectedLanguageChange.apply(this,e)};if(e.on(["loadstart","texttrackchange"],r),s.addEventListener("change",r),s.addEventListener("selectedlanguagechange",n),this.on("dispose",function(){e.off(["loadstart","texttrackchange"],r),s.removeEventListener("change",r),s.removeEventListener("selectedlanguagechange",n)}),void 0===s.onchange){let e;this.on(["tap","click"],function(){if("object"!=typeof d().Event)try{e=new(d()).Event("change")}catch(e){}e||(e=c().createEvent("Event")).initEvent("change",!0,!0),s.dispatchEvent(e)})}this.handleTracksChange()}handleClick(e){let t=this.track,i=this.player_.textTracks();if(super.handleClick(e),i)for(let e=0;e-1&&"showing"===s.mode){i=!1;break}}i!==this.isSelected_&&this.selected(i)}handleSelectedLanguageChange(e){let t=this.player().textTracks(),i=!0;for(let e=0,s=t.length;e-1&&"showing"===s.mode){i=!1;break}}i&&(this.player_.cache_.selectedLanguage={enabled:!1})}handleLanguagechange(){this.$(".vjs-menu-item-text").textContent=this.player_.localize(this.options_.label),super.handleLanguagechange()}}tP.registerComponent("OffTextTrackMenuItem",sg);class sf extends sc{constructor(e,t={}){t.tracks=e.textTracks(),super(e,t)}createItems(e=[],t=sm){let i;this.label_&&(i=`${this.label_} off`),e.push(new sg(this.player_,{kinds:this.kinds_,kind:this.kind_,label:i})),this.hideThreshold_+=1;let s=this.player_.textTracks();Array.isArray(this.kinds_)||(this.kinds_=[this.kind_]);for(let i=0;i-1){let i=new t(this.player_,{track:r,kinds:this.kinds_,kind:this.kind_,selectable:!0,multiSelectable:!1});i.addClass(`vjs-${r.kind}-menu-item`),e.push(i)}}return e}}tP.registerComponent("TextTrackButton",sf);class s_ extends sp{constructor(e,t){let i=t.track,s=t.cue,r=e.currentTime();t.selectable=!0,t.multiSelectable=!1,t.label=s.text,t.selected=s.startTime<=r&&r{this.items.forEach(e=>{e.selected(this.track_.activeCues[0]===e.cue)})}}buildCSSClass(){return`vjs-chapters-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-chapters-button ${super.buildWrapperCSSClass()}`}update(e){if(e&&e.track&&"chapters"!==e.track.kind)return;let t=this.findChaptersTrack();t!==this.track_?(this.setTrack(t),super.update()):(!this.items||t&&t.cues&&t.cues.length!==this.items.length)&&super.update()}setTrack(e){if(this.track_!==e){if(this.updateHandler_||(this.updateHandler_=this.update.bind(this)),this.track_){let e=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);e&&e.removeEventListener("load",this.updateHandler_),this.track_.removeEventListener("cuechange",this.selectCurrentItem_),this.track_=null}if(this.track_=e,this.track_){this.track_.mode="hidden";let e=this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);e&&e.addEventListener("load",this.updateHandler_),this.track_.addEventListener("cuechange",this.selectCurrentItem_)}}}findChaptersTrack(){let e=this.player_.textTracks()||[];for(let t=e.length-1;t>=0;t--){let i=e[t];if(i.kind===this.kind_)return i}}getMenuCaption(){return this.track_&&this.track_.label?this.track_.label:this.localize(tE(this.kind_))}createMenu(){return this.options_.title=this.getMenuCaption(),super.createMenu()}createItems(){let e=[];if(!this.track_)return e;let t=this.track_.cues;if(!t)return e;for(let i=0,s=t.length;i-1&&(this.label_="captions",this.setIcon("captions")),this.menuButton_.controlText(tE(this.label_))}buildCSSClass(){return`vjs-subs-caps-button ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-subs-caps-button ${super.buildWrapperCSSClass()}`}createItems(){let e=[];return!(this.player().tech_&&this.player().tech_.featuresNativeTextTracks)&&this.player().getChild("textTrackSettings")&&(e.push(new sT(this.player_,{kind:this.label_})),this.hideThreshold_+=1),e=super.createItems(e,sk)}}sC.prototype.kinds_=["captions","subtitles"],sC.prototype.controlText_="Subtitles",tP.registerComponent("SubsCapsButton",sC);class sw extends sp{constructor(e,t){let i=t.track,s=e.audioTracks();t.label=i.label||i.language||"Unknown",t.selected=i.enabled,super(e,t),this.track=i,this.addClass(`vjs-${i.kind}-menu-item`);let r=(...e)=>{this.handleTracksChange.apply(this,e)};s.addEventListener("change",r),this.on("dispose",()=>{s.removeEventListener("change",r)})}createEl(e,t,i){let s=super.createEl(e,t,i),r=s.querySelector(".vjs-menu-item-text");return["main-desc","descriptions"].indexOf(this.options_.track.kind)>=0&&(r.appendChild(eC("span",{className:"vjs-icon-placeholder"},{"aria-hidden":!0})),r.appendChild(eC("span",{className:"vjs-control-text",textContent:" "+this.localize("Descriptions")}))),s}handleClick(e){if(super.handleClick(e),this.track.enabled=!0,this.player_.tech_.featuresNativeAudioTracks){let e=this.player_.audioTracks();for(let t=0;tthis.update(e))}handleClick(e){super.handleClick(),this.player().playbackRate(this.rate)}update(e){this.selected(this.player().playbackRate()===this.rate)}}sx.prototype.contentElType="button",tP.registerComponent("PlaybackRateMenuItem",sx);class sI extends su{constructor(e,t){super(e,t),this.menuButton_.el_.setAttribute("aria-describedby",this.labelElId_),this.updateVisibility(),this.updateLabel(),this.on(e,"loadstart",e=>this.updateVisibility(e)),this.on(e,"ratechange",e=>this.updateLabel(e)),this.on(e,"playbackrateschange",e=>this.handlePlaybackRateschange(e))}createEl(){let e=super.createEl();return this.labelElId_="vjs-playback-rate-value-label-"+this.id_,this.labelEl_=eC("div",{className:"vjs-playback-rate-value",id:this.labelElId_,textContent:"1x"}),e.appendChild(this.labelEl_),e}dispose(){this.labelEl_=null,super.dispose()}buildCSSClass(){return`vjs-playback-rate ${super.buildCSSClass()}`}buildWrapperCSSClass(){return`vjs-playback-rate ${super.buildWrapperCSSClass()}`}createItems(){let e=this.playbackRates(),t=[];for(let i=e.length-1;i>=0;i--)t.push(new sx(this.player(),{rate:e[i]+"x"}));return t}handlePlaybackRateschange(e){this.update()}playbackRates(){let e=this.player();return e.playbackRates&&e.playbackRates()||[]}playbackRateSupported(){return this.player().tech_&&this.player().tech_.featuresPlaybackRate&&this.playbackRates()&&this.playbackRates().length>0}updateVisibility(e){this.playbackRateSupported()?this.removeClass("vjs-hidden"):this.addClass("vjs-hidden")}updateLabel(e){this.playbackRateSupported()&&(this.labelEl_.textContent=this.player().playbackRate()+"x")}}sI.prototype.controlText_="Playback Rate",tP.registerComponent("PlaybackRateMenuButton",sI);class sP extends tP{buildCSSClass(){return`vjs-spacer ${super.buildCSSClass()}`}createEl(e="div",t={},i={}){return t.className||(t.className=this.buildCSSClass()),super.createEl(e,t,i)}}tP.registerComponent("Spacer",sP);class sA extends sP{buildCSSClass(){return`vjs-custom-control-spacer ${super.buildCSSClass()}`}createEl(){return super.createEl("div",{className:this.buildCSSClass(),textContent:"\xa0"})}}tP.registerComponent("CustomControlSpacer",sA);class sL extends tP{createEl(){return super.createEl("div",{className:"vjs-control-bar",dir:"ltr"})}}sL.prototype.options_={children:["playToggle","skipBackward","skipForward","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","liveDisplay","seekToLive","remainingTimeDisplay","customControlSpacer","playbackRateMenuButton","chaptersButton","descriptionsButton","subsCapsButton","audioTrackButton","pictureInPictureToggle","fullscreenToggle"]},tP.registerComponent("ControlBar",sL);class sD extends tW{constructor(e,t){super(e,t),this.on(e,"error",e=>{this.open(e)})}buildCSSClass(){return`vjs-error-display ${super.buildCSSClass()}`}content(){let e=this.player().error();return e?this.localize(e.message):""}}sD.prototype.options_=Object.assign({},tW.prototype.options_,{pauseOnOpen:!1,fillAlways:!0,temporary:!1,uncloseable:!0}),tP.registerComponent("ErrorDisplay",sD);class sO extends tP{constructor(e,t={}){super(e,t),this.el_.setAttribute("aria-labelledby",this.selectLabelledbyIds)}createEl(){return this.selectLabelledbyIds=[this.options_.legendId,this.options_.labelId].join(" ").trim(),eC("select",{id:this.options_.id},{},this.options_.SelectOptions.map(e=>{let t=(this.options_.labelId?this.options_.labelId:`vjs-track-option-${e5++}`)+"-"+e[1].replace(/\W+/g,""),i=eC("option",{id:t,value:this.localize(e[0]),textContent:this.localize(e[1])});return i.setAttribute("aria-labelledby",`${this.selectLabelledbyIds} ${t}`),i}))}}tP.registerComponent("TextTrackSelect",sO);class sM extends tP{constructor(e,t={}){super(e,t);let i=eC("legend",{textContent:this.localize(this.options_.legendText),id:this.options_.legendId});for(let t of(this.el().appendChild(i),this.options_.selects)){let i=this.options_.selectConfigs[t],s=i.className,r=i.id.replace("%s",this.options_.id_),n=null,a=`vjs_select_${e5++}`;if("colors"===this.options_.type){n=eC("span",{className:s});let e=eC("label",{id:r,className:"vjs-label",textContent:this.localize(i.label)});e.setAttribute("for",a),n.appendChild(e)}let o=new sO(e,{SelectOptions:i.options,legendId:this.options_.legendId,id:a,labelId:r});this.addChild(o),"colors"===this.options_.type&&(n.appendChild(o.el()),this.el().appendChild(n))}}createEl(){return eC("fieldset",{className:this.options_.className})}}tP.registerComponent("TextTrackFieldset",sM);class sU extends tP{constructor(e,t={}){super(e,t);let i=this.options_.textTrackComponentid,s=new sM(e,{id_:i,legendId:`captions-text-legend-${i}`,legendText:this.localize("Text"),className:"vjs-fg vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(s);let r=new sM(e,{id_:i,legendId:`captions-background-${i}`,legendText:this.localize("Text Background"),className:"vjs-bg vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(r);let n=new sM(e,{id_:i,legendId:`captions-window-${i}`,legendText:this.localize("Caption Area Background"),className:"vjs-window vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"colors"});this.addChild(n)}createEl(){return eC("div",{className:"vjs-track-settings-colors"})}}tP.registerComponent("TextTrackSettingsColors",sU);class sR extends tP{constructor(e,t={}){super(e,t);let i=this.options_.textTrackComponentid,s=new sM(e,{id_:i,legendId:`captions-font-size-${i}`,legendText:"Font Size",className:"vjs-font-percent vjs-track-setting",selects:this.options_.fieldSets[0],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(s);let r=new sM(e,{id_:i,legendId:`captions-edge-style-${i}`,legendText:this.localize("Text Edge Style"),className:"vjs-edge-style vjs-track-setting",selects:this.options_.fieldSets[1],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(r);let n=new sM(e,{id_:i,legendId:`captions-font-family-${i}`,legendText:this.localize("Font Family"),className:"vjs-font-family vjs-track-setting",selects:this.options_.fieldSets[2],selectConfigs:this.options_.selectConfigs,type:"font"});this.addChild(n)}createEl(){return eC("div",{className:"vjs-track-settings-font"})}}tP.registerComponent("TextTrackSettingsFont",sR);class sB extends tP{constructor(e,t={}){super(e,t);let i=this.localize("restore all settings to the default values"),s=new iF(e,{controlText:i,className:"vjs-default-button"});s.el().classList.remove("vjs-control","vjs-button"),s.el().textContent=this.localize("Reset"),this.addChild(s);let r=new iF(e,{controlText:i,className:"vjs-done-button"});r.el().classList.remove("vjs-control","vjs-button"),r.el().textContent=this.localize("Done"),this.addChild(r)}createEl(){return eC("div",{className:"vjs-track-settings-controls"})}}tP.registerComponent("TrackSettingsControls",sB);let sN="vjs-text-track-settings",sj=["#000","Black"],sF=["#00F","Blue"],s$=["#0FF","Cyan"],sq=["#0F0","Green"],sH=["#F0F","Magenta"],sV=["#F00","Red"],sz=["#FFF","White"],sW=["#FF0","Yellow"],sG=["1","Opaque"],sK=["0.5","Semi-Transparent"],sQ=["0","Transparent"],sY={backgroundColor:{selector:".vjs-bg-color > select",id:"captions-background-color-%s",label:"Color",options:[sj,sz,sV,sq,sF,sW,sH,s$],className:"vjs-bg-color"},backgroundOpacity:{selector:".vjs-bg-opacity > select",id:"captions-background-opacity-%s",label:"Opacity",options:[sG,sK,sQ],className:"vjs-bg-opacity vjs-opacity"},color:{selector:".vjs-text-color > select",id:"captions-foreground-color-%s",label:"Color",options:[sz,sj,sV,sq,sF,sW,sH,s$],className:"vjs-text-color"},edgeStyle:{selector:".vjs-edge-style > select",id:"",label:"Text Edge Style",options:[["none","None"],["raised","Raised"],["depressed","Depressed"],["uniform","Uniform"],["dropshadow","Drop shadow"]]},fontFamily:{selector:".vjs-font-family > select",id:"",label:"Font Family",options:[["proportionalSansSerif","Proportional Sans-Serif"],["monospaceSansSerif","Monospace Sans-Serif"],["proportionalSerif","Proportional Serif"],["monospaceSerif","Monospace Serif"],["casual","Casual"],["script","Script"],["small-caps","Small Caps"]]},fontPercent:{selector:".vjs-font-percent > select",id:"",label:"Font Size",options:[["0.50","50%"],["0.75","75%"],["1.00","100%"],["1.25","125%"],["1.50","150%"],["1.75","175%"],["2.00","200%"],["3.00","300%"],["4.00","400%"]],default:2,parser:e=>"1.00"===e?null:Number(e)},textOpacity:{selector:".vjs-text-opacity > select",id:"captions-foreground-opacity-%s",label:"Opacity",options:[sG,sK],className:"vjs-text-opacity vjs-opacity"},windowColor:{selector:".vjs-window-color > select",id:"captions-window-color-%s",label:"Color",className:"vjs-window-color"},windowOpacity:{selector:".vjs-window-opacity > select",id:"captions-window-opacity-%s",label:"Opacity",options:[sQ,sK,sG],className:"vjs-window-opacity vjs-opacity"}};function sX(e,t){if(t&&(e=t(e)),e&&"none"!==e)return e}sY.windowColor.options=sY.backgroundColor.options;class sJ extends tW{constructor(e,t){t.temporary=!1,super(e,t),this.updateDisplay=this.updateDisplay.bind(this),this.fill(),this.hasBeenOpened_=this.hasBeenFilled_=!0,this.renderModalComponents(e),this.endDialog=eC("p",{className:"vjs-control-text",textContent:this.localize("End of dialog window.")}),this.el().appendChild(this.endDialog),this.setDefaults(),void 0===t.persistTextTrackSettings&&(this.options_.persistTextTrackSettings=this.options_.playerOptions.persistTextTrackSettings),this.bindFunctionsToSelectsAndButtons(),this.options_.persistTextTrackSettings&&this.restoreSettings()}renderModalComponents(e){let t=new sU(e,{textTrackComponentid:this.id_,selectConfigs:sY,fieldSets:[["color","textOpacity"],["backgroundColor","backgroundOpacity"],["windowColor","windowOpacity"]]});this.addChild(t);let i=new sR(e,{textTrackComponentid:this.id_,selectConfigs:sY,fieldSets:[["fontPercent"],["edgeStyle"],["fontFamily"]]});this.addChild(i);let s=new sB(e);this.addChild(s)}bindFunctionsToSelectsAndButtons(){this.on(this.$(".vjs-done-button"),["click","tap"],()=>{this.saveSettings(),this.close()}),this.on(this.$(".vjs-default-button"),["click","tap"],()=>{this.setDefaults(),this.updateDisplay()}),q(sY,e=>{this.on(this.$(e.selector),"change",this.updateDisplay)})}dispose(){this.endDialog=null,super.dispose()}label(){return this.localize("Caption Settings Dialog")}description(){return this.localize("Beginning of dialog window. Escape will cancel and close the window.")}buildCSSClass(){return super.buildCSSClass()+" vjs-text-track-settings"}getValues(){return H(sY,(e,t,i)=>{var s,r;let n=(s=this.$(t.selector),r=t.parser,sX(s.options[s.options.selectedIndex].value,r));return void 0!==n&&(e[i]=n),e},{})}setValues(e){q(sY,(t,i)=>{!function(e,t,i){if(t){for(let s=0;s{let t=e.hasOwnProperty("default")?e.default:0;this.$(e.selector).selectedIndex=t})}restoreSettings(){let e;try{e=JSON.parse(d().localStorage.getItem(sN))}catch(e){N.warn(e)}e&&this.setValues(e)}saveSettings(){if(!this.options_.persistTextTrackSettings)return;let e=this.getValues();try{Object.keys(e).length?d().localStorage.setItem(sN,JSON.stringify(e)):d().localStorage.removeItem(sN)}catch(e){N.warn(e)}}updateDisplay(){let e=this.player_.getChild("textTrackDisplay");e&&e.updateDisplay()}handleLanguagechange(){this.fill(),this.renderModalComponents(this.player_),this.bindFunctionsToSelectsAndButtons()}}tP.registerComponent("TextTrackSettings",sJ);class sZ extends tP{constructor(e,t){let i=t.ResizeObserver||d().ResizeObserver;null===t.ResizeObserver&&(i=!1),super(e,W({createEl:!i,reportTouchActivity:!1},t)),this.ResizeObserver=t.ResizeObserver||d().ResizeObserver,this.loadListener_=null,this.resizeObserver_=null,this.debouncedHandler_=th(()=>{this.resizeHandler()},100,!1,this),i?(this.resizeObserver_=new this.ResizeObserver(this.debouncedHandler_),this.resizeObserver_.observe(e.el())):(this.loadListener_=()=>{if(!this.el_||!this.el_.contentWindow)return;let e=this.debouncedHandler_,t=this.unloadListener_=function(){ti(this,"resize",e),ti(this,"unload",t),t=null};tt(this.el_.contentWindow,"unload",t),tt(this.el_.contentWindow,"resize",e)},this.one("load",this.loadListener_))}createEl(){return super.createEl("iframe",{className:"vjs-resize-manager",tabIndex:-1,title:this.localize("No content")},{"aria-hidden":"true"})}resizeHandler(){this.player_&&this.player_.trigger&&this.player_.trigger("playerresize")}dispose(){this.debouncedHandler_&&this.debouncedHandler_.cancel(),this.resizeObserver_&&(this.player_.el()&&this.resizeObserver_.unobserve(this.player_.el()),this.resizeObserver_.disconnect()),this.loadListener_&&this.off("load",this.loadListener_),this.el_&&this.el_.contentWindow&&this.unloadListener_&&this.unloadListener_.call(this.el_.contentWindow),this.ResizeObserver=null,this.resizeObserver=null,this.debouncedHandler_=null,this.loadListener_=null,super.dispose()}}tP.registerComponent("ResizeManager",sZ);let s0={trackingThreshold:20,liveTolerance:15};class s1 extends tP{constructor(e,t){super(e,W(s0,t,{createEl:!1})),this.trackLiveHandler_=()=>this.trackLive_(),this.handlePlay_=e=>this.handlePlay(e),this.handleFirstTimeupdate_=e=>this.handleFirstTimeupdate(e),this.handleSeeked_=e=>this.handleSeeked(e),this.seekToLiveEdge_=e=>this.seekToLiveEdge(e),this.reset_(),this.on(this.player_,"durationchange",e=>this.handleDurationchange(e)),this.on(this.player_,"canplay",()=>this.toggleTracking())}trackLive_(){let e=this.player_.seekable();if(!e||!e.length)return;let t=Number(d().performance.now().toFixed(4)),i=-1===this.lastTime_?0:(t-this.lastTime_)/1e3;this.lastTime_=t,this.pastSeekEnd_=this.pastSeekEnd()+i;let s=this.liveCurrentTime(),r=this.player_.currentTime(),n=this.player_.paused()||this.seekedBehindLive_||Math.abs(s-r)>this.options_.liveTolerance;this.timeupdateSeen_&&s!==1/0||(n=!1),n!==this.behindLiveEdge_&&(this.behindLiveEdge_=n,this.trigger("liveedgechange"))}handleDurationchange(){this.toggleTracking()}toggleTracking(){this.player_.duration()===1/0&&this.liveWindow()>=this.options_.trackingThreshold?(this.player_.options_.liveui&&this.player_.addClass("vjs-liveui"),this.startTracking()):(this.player_.removeClass("vjs-liveui"),this.stopTracking())}startTracking(){!this.isTracking()&&(this.timeupdateSeen_||(this.timeupdateSeen_=this.player_.hasStarted()),this.trackingInterval_=this.setInterval(this.trackLiveHandler_,30),this.trackLive_(),this.on(this.player_,["play","pause"],this.trackLiveHandler_),this.timeupdateSeen_?this.on(this.player_,"seeked",this.handleSeeked_):(this.one(this.player_,"play",this.handlePlay_),this.one(this.player_,"timeupdate",this.handleFirstTimeupdate_)))}handleFirstTimeupdate(){this.timeupdateSeen_=!0,this.on(this.player_,"seeked",this.handleSeeked_)}handleSeeked(){let e=Math.abs(this.liveCurrentTime()-this.player_.currentTime());this.seekedBehindLive_=this.nextSeekedFromUser_&&e>2,this.nextSeekedFromUser_=!1,this.trackLive_()}handlePlay(){this.one(this.player_,"timeupdate",this.seekToLiveEdge_)}reset_(){this.lastTime_=-1,this.pastSeekEnd_=0,this.lastSeekEnd_=-1,this.behindLiveEdge_=!0,this.timeupdateSeen_=!1,this.seekedBehindLive_=!1,this.nextSeekedFromUser_=!1,this.clearInterval(this.trackingInterval_),this.trackingInterval_=null,this.off(this.player_,["play","pause"],this.trackLiveHandler_),this.off(this.player_,"seeked",this.handleSeeked_),this.off(this.player_,"play",this.handlePlay_),this.off(this.player_,"timeupdate",this.handleFirstTimeupdate_),this.off(this.player_,"timeupdate",this.seekToLiveEdge_)}nextSeekedFromUser(){this.nextSeekedFromUser_=!0}stopTracking(){this.isTracking()&&(this.reset_(),this.trigger("liveedgechange"))}seekableEnd(){let e=this.player_.seekable(),t=[],i=e?e.length:0;for(;i--;)t.push(e.end(i));return t.length?t.sort()[t.length-1]:1/0}seekableStart(){let e=this.player_.seekable(),t=[],i=e?e.length:0;for(;i--;)t.push(e.start(i));return t.length?t.sort()[0]:0}liveWindow(){let e=this.liveCurrentTime();return e===1/0?0:e-this.seekableStart()}isLive(){return this.isTracking()}atLiveEdge(){return!this.behindLiveEdge()}liveCurrentTime(){return this.pastSeekEnd()+this.seekableEnd()}pastSeekEnd(){let e=this.seekableEnd();return -1!==this.lastSeekEnd_&&e!==this.lastSeekEnd_&&(this.pastSeekEnd_=0),this.lastSeekEnd_=e,this.pastSeekEnd_}behindLiveEdge(){return this.behindLiveEdge_}isTracking(){return"number"==typeof this.trackingInterval_}seekToLiveEdge(){this.seekedBehindLive_=!1,!this.atLiveEdge()&&(this.nextSeekedFromUser_=!1,this.player_.currentTime(this.liveCurrentTime()))}dispose(){this.stopTracking(),super.dispose()}}tP.registerComponent("LiveTracker",s1);class s2 extends tP{constructor(e,t){super(e,t),this.on("statechanged",e=>this.updateDom_()),this.updateDom_()}createEl(){return this.els={title:eC("div",{className:"vjs-title-bar-title",id:`vjs-title-bar-title-${e5++}`}),description:eC("div",{className:"vjs-title-bar-description",id:`vjs-title-bar-description-${e5++}`})},eC("div",{className:"vjs-title-bar"},{},G(this.els))}updateDom_(){let e=this.player_.tech_,t=e&&e.el_,i={title:"aria-labelledby",description:"aria-describedby"};["title","description"].forEach(e=>{let s=this.state[e],r=this.els[e],n=i[e];eq(r),s&&ew(r,s),t&&(t.removeAttribute(n),s&&t.setAttribute(n,r.id))}),this.state.title||this.state.description?this.show():this.hide()}update(e){this.setState(e)}dispose(){let e=this.player_.tech_,t=e&&e.el_;t&&(t.removeAttribute("aria-labelledby"),t.removeAttribute("aria-describedby")),super.dispose(),this.els=null}}tP.registerComponent("TitleBar",s2);let s4={initialDisplay:4e3,position:[],takeFocus:!1};class s8 extends iF{constructor(e,t){super(e,t=W(s4,t)),this.controlText(t.controlText),this.hide(),this.on(this.player_,["useractive","userinactive"],e=>{this.removeClass("force-display")})}buildCSSClass(){return`vjs-transient-button focus-visible ${this.options_.position.map(e=>`vjs-${e}`).join(" ")}`}createEl(){let e=eC("button",{},{type:"button",class:this.buildCSSClass()},eC("span"));return this.controlTextEl_=e.querySelector("span"),e}show(){super.show(),this.addClass("force-display"),this.options_.takeFocus&&this.el().focus({preventScroll:!0}),this.forceDisplayTimeout=this.player_.setTimeout(()=>{this.removeClass("force-display")},this.options_.initialDisplay)}hide(){this.removeClass("force-display"),super.hide()}dispose(){this.player_.clearTimeout(this.forceDisplayTimeout),super.dispose()}}tP.registerComponent("TransientButton",s8);let s5=e=>{let t=e.el();if(t.hasAttribute("src"))return e.triggerSourceset(t.src),!0;let i=e.$$("source"),s=[],r="";if(!i.length)return!1;for(let e=0;e{let i={};for(let s=0;ss6([e.el(),d().HTMLMediaElement.prototype,d().Element.prototype,s3],"innerHTML"),s9=function(e){let t=e.el();if(t.resetSourceWatch_)return;let i={},s=s7(e),r=i=>(...s)=>{let r=i.apply(t,s);return s5(e),r};["append","appendChild","insertAdjacentHTML"].forEach(e=>{t[e]&&(i[e]=t[e],t[e]=r(i[e]))}),Object.defineProperty(t,"innerHTML",W(s,{set:r(s.set)})),t.resetSourceWatch_=()=>{t.resetSourceWatch_=null,Object.keys(i).forEach(e=>{t[e]=i[e]}),Object.defineProperty(t,"innerHTML",s)},e.one("sourceset",t.resetSourceWatch_)},re=Object.defineProperty({},"src",{get(){return this.hasAttribute("src")?t6(d().Element.prototype.getAttribute.call(this,"src")):""},set(e){return d().Element.prototype.setAttribute.call(this,"src",e),e}}),rt=e=>s6([e.el(),d().HTMLMediaElement.prototype,re],"src"),ri=function(e){if(!e.featuresSourceset)return;let t=e.el();if(t.resetSourceset_)return;let i=rt(e),s=t.setAttribute,r=t.load;Object.defineProperty(t,"src",W(i,{set:s=>{let r=i.set.call(t,s);return e.triggerSourceset(t.src),r}})),t.setAttribute=(i,r)=>{let n=s.call(t,i,r);return/src/i.test(i)&&e.triggerSourceset(t.src),n},t.load=()=>{let i=r.call(t);return s5(e)||(e.triggerSourceset(""),s9(e)),i},t.currentSrc?e.triggerSourceset(t.currentSrc):s5(e)||s9(e),t.resetSourceset_=()=>{t.resetSourceset_=null,t.load=r,t.setAttribute=s,Object.defineProperty(t,"src",i),t.resetSourceWatch_&&t.resetSourceWatch_()}};class rs extends iu{constructor(e,t){super(e,t);let i=e.source,s=!1;if(this.featuresVideoFrameCallback=this.featuresVideoFrameCallback&&"VIDEO"===this.el_.tagName,i&&(this.el_.currentSrc!==i.src||e.tag&&3===e.tag.initNetworkState_)?this.setSource(i):this.handleLateInit_(this.el_),e.enableSourceset&&this.setupSourcesetHandling_(),this.isScrubbing_=!1,this.el_.hasChildNodes()){let e=this.el_.childNodes,t=e.length,i=[];for(;t--;){let r=e[t];"track"===r.nodeName.toLowerCase()&&(this.featuresNativeTextTracks?(this.remoteTextTrackEls().addTrackElement_(r),this.remoteTextTracks().addTrack(r.track),this.textTracks().addTrack(r.track),!s&&!this.el_.hasAttribute("crossorigin")&&t9(r.src)&&(s=!0)):i.push(r))}for(let e=0;e{e=[];for(let i=0;it.removeEventListener("change",i));let s=()=>{for(let t=0;t{t.removeEventListener("change",i),t.removeEventListener("change",s),t.addEventListener("change",s)}),this.on("webkitendfullscreen",()=>{t.removeEventListener("change",i),t.addEventListener("change",i),t.removeEventListener("change",s)})}overrideNative_(e,t){if(t!==this[`featuresNative${e}Tracks`])return;let i=e.toLowerCase();this[`${i}TracksListeners_`]&&Object.keys(this[`${i}TracksListeners_`]).forEach(e=>{this.el()[`${i}Tracks`].removeEventListener(e,this[`${i}TracksListeners_`][e])}),this[`featuresNative${e}Tracks`]=!t,this[`${i}TracksListeners_`]=null,this.proxyNativeTracksForType_(i)}overrideNativeAudioTracks(e){this.overrideNative_("Audio",e)}overrideNativeVideoTracks(e){this.overrideNative_("Video",e)}proxyNativeTracksForType_(e){let t=il[e],i=this.el()[t.getterName],s=this[t.getterName]();if(!this[`featuresNative${t.capitalName}Tracks`]||!i||!i.addEventListener)return;let r={change:t=>{let i={type:"change",target:s,currentTarget:s,srcElement:s};s.trigger(i),"text"===e&&this[ih.remoteText.getterName]().trigger(i)},addtrack(e){s.addTrack(e.track)},removetrack(e){s.removeTrack(e.track)}},n=function(){let e=[];for(let t=0;t{let t=r[e];i.addEventListener(e,t),this.on("dispose",s=>i.removeEventListener(e,t))}),this.on("loadstart",n),this.on("dispose",e=>this.off("loadstart",n))}proxyNativeTracks_(){il.names.forEach(e=>{this.proxyNativeTracksForType_(e)})}createEl(){let e=this.options_.tag;if(!e||!(this.options_.playerElIngest||this.movingMediaElementInDOM)){if(e){let t=e.cloneNode(!0);e.parentNode&&e.parentNode.insertBefore(t,e),rs.disposeMediaElement(e),e=t}else{e=c().createElement("video");let t=W({},this.options_.tag&&eD(this.options_.tag));em&&!0===this.options_.nativeControlsForTouch||delete t.controls,eL(e,Object.assign(t,{id:this.options_.techId,class:"vjs-tech"}))}e.playerId=this.options_.playerId}void 0!==this.options_.preload&&eM(e,"preload",this.options_.preload),void 0!==this.options_.disablePictureInPicture&&(e.disablePictureInPicture=this.options_.disablePictureInPicture);let t=["loop","muted","playsinline","autoplay"];for(let i=0;i=2&&t.push("loadeddata"),e.readyState>=3&&t.push("canplay"),e.readyState>=4&&t.push("canplaythrough"),this.ready(function(){t.forEach(function(e){this.trigger(e)},this)})}setScrubbing(e){this.isScrubbing_=e}scrubbing(){return this.isScrubbing_}setCurrentTime(e){try{this.isScrubbing_&&this.el_.fastSeek&&e_?this.el_.fastSeek(e):this.el_.currentTime=e}catch(e){N(e,"Video is not ready. (Video.js)")}}duration(){if(this.el_.duration===1/0&&J&&ei&&0===this.el_.currentTime){let e=()=>{this.el_.currentTime>0&&(this.el_.duration===1/0&&this.trigger("durationchange"),this.off("timeupdate",e))};return this.on("timeupdate",e),NaN}return this.el_.duration||NaN}width(){return this.el_.offsetWidth}height(){return this.el_.offsetHeight}proxyWebkitFullscreen_(){if(!("webkitDisplayingFullscreen"in this.el_))return;let e=function(){this.trigger("fullscreenchange",{isFullscreen:!1}),this.el_.controls&&!this.options_.nativeControlsForTouch&&this.controls()&&(this.el_.controls=!1)},t=function(){"webkitPresentationMode"in this.el_&&"picture-in-picture"!==this.el_.webkitPresentationMode&&(this.one("webkitendfullscreen",e),this.trigger("fullscreenchange",{isFullscreen:!0,nativeIOSFullscreen:!0}))};this.on("webkitbeginfullscreen",t),this.on("dispose",()=>{this.off("webkitbeginfullscreen",t),this.off("webkitendfullscreen",e)})}supportsFullScreen(){return"function"==typeof this.el_.webkitEnterFullScreen}enterFullScreen(){let e=this.el_;if(e.paused&&e.networkState<=e.HAVE_METADATA)tq(this.el_.play()),this.setTimeout(function(){e.pause();try{e.webkitEnterFullScreen()}catch(e){this.trigger("fullscreenerror",e)}},0);else try{e.webkitEnterFullScreen()}catch(e){this.trigger("fullscreenerror",e)}}exitFullScreen(){if(!this.el_.webkitDisplayingFullscreen){this.trigger("fullscreenerror",Error("The video is not fullscreen"));return}this.el_.webkitExitFullScreen()}requestPictureInPicture(){return this.el_.requestPictureInPicture()}requestVideoFrameCallback(e){return this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.requestVideoFrameCallback(e):super.requestVideoFrameCallback(e)}cancelVideoFrameCallback(e){this.featuresVideoFrameCallback&&!this.el_.webkitKeys?this.el_.cancelVideoFrameCallback(e):super.cancelVideoFrameCallback(e)}src(e){if(void 0===e)return this.el_.src;this.setSrc(e)}addSourceElement(e,t){if(!e)return N.error("Invalid source URL."),!1;let i={src:e};t&&(i.type=t);let s=eC("source",{},i);return this.el_.appendChild(s),!0}removeSourceElement(e){if(!e)return N.error("Source URL is required to remove the source element."),!1;for(let t of this.el_.querySelectorAll("source"))if(t.src===e)return this.el_.removeChild(t),!0;return N.warn(`No matching source element found with src: ${e}`),!1}reset(){rs.resetMediaElement(this.el_)}currentSrc(){return this.currentSource_?this.currentSource_.src:this.el_.currentSrc}setControls(e){this.el_.controls=!!e}addTextTrack(e,t,i){return this.featuresNativeTextTracks?this.el_.addTextTrack(e,t,i):super.addTextTrack(e,t,i)}createRemoteTextTrack(e){if(!this.featuresNativeTextTracks)return super.createRemoteTextTrack(e);let t=c().createElement("track");return e.kind&&(t.kind=e.kind),e.label&&(t.label=e.label),(e.language||e.srclang)&&(t.srclang=e.language||e.srclang),e.default&&(t.default=e.default),e.id&&(t.id=e.id),e.src&&(t.src=e.src),t}addRemoteTextTrack(e,t){let i=super.addRemoteTextTrack(e,t);return this.featuresNativeTextTracks&&this.el().appendChild(i),i}removeRemoteTextTrack(e){if(super.removeRemoteTextTrack(e),this.featuresNativeTextTracks){let t=this.$$("track"),i=t.length;for(;i--;)(e===t[i]||e===t[i].track)&&this.el().removeChild(t[i])}}getVideoPlaybackQuality(){if("function"==typeof this.el().getVideoPlaybackQuality)return this.el().getVideoPlaybackQuality();let e={};return void 0!==this.el().webkitDroppedFrameCount&&void 0!==this.el().webkitDecodedFrameCount&&(e.droppedVideoFrames=this.el().webkitDroppedFrameCount,e.totalVideoFrames=this.el().webkitDecodedFrameCount),d().performance&&(e.creationTime=d().performance.now()),e}}K(rs,"TEST_VID",function(){if(!eb())return;let e=c().createElement("video"),t=c().createElement("track");return t.kind="captions",t.srclang="en",t.label="English",e.appendChild(t),e}),rs.isSupported=function(){try{rs.TEST_VID.volume=.5}catch(e){return!1}return!!(rs.TEST_VID&&rs.TEST_VID.canPlayType)},rs.canPlayType=function(e){return rs.TEST_VID.canPlayType(e)},rs.canPlaySource=function(e,t){return rs.canPlayType(e.type)},rs.canControlVolume=function(){try{let e=rs.TEST_VID.volume;rs.TEST_VID.volume=e/2+.1;let t=e!==rs.TEST_VID.volume;if(t&&ef)return d().setTimeout(()=>{rs&&rs.prototype&&(rs.prototype.featuresVolumeControl=e!==rs.TEST_VID.volume)}),!1;return t}catch(e){return!1}},rs.canMuteVolume=function(){try{let e=rs.TEST_VID.muted;return rs.TEST_VID.muted=!e,rs.TEST_VID.muted?eM(rs.TEST_VID,"muted","muted"):eU(rs.TEST_VID,"muted","muted"),e!==rs.TEST_VID.muted}catch(e){return!1}},rs.canControlPlaybackRate=function(){if(J&&ei&&er<58)return!1;try{let e=rs.TEST_VID.playbackRate;return rs.TEST_VID.playbackRate=e/2+.1,e!==rs.TEST_VID.playbackRate}catch(e){return!1}},rs.canOverrideAttributes=function(){try{let e=()=>{};Object.defineProperty(c().createElement("video"),"src",{get:e,set:e}),Object.defineProperty(c().createElement("audio"),"src",{get:e,set:e}),Object.defineProperty(c().createElement("video"),"innerHTML",{get:e,set:e}),Object.defineProperty(c().createElement("audio"),"innerHTML",{get:e,set:e})}catch(e){return!1}return!0},rs.supportsNativeTextTracks=function(){return e_||ef&&ei},rs.supportsNativeVideoTracks=function(){return!!(rs.TEST_VID&&rs.TEST_VID.videoTracks)},rs.supportsNativeAudioTracks=function(){return!!(rs.TEST_VID&&rs.TEST_VID.audioTracks)},rs.Events=["loadstart","suspend","abort","error","emptied","stalled","loadedmetadata","loadeddata","canplay","canplaythrough","playing","waiting","seeking","seeked","ended","durationchange","timeupdate","progress","play","pause","ratechange","resize","volumechange"],[["featuresMuteControl","canMuteVolume"],["featuresPlaybackRate","canControlPlaybackRate"],["featuresSourceset","canOverrideAttributes"],["featuresNativeTextTracks","supportsNativeTextTracks"],["featuresNativeVideoTracks","supportsNativeVideoTracks"],["featuresNativeAudioTracks","supportsNativeAudioTracks"]].forEach(function([e,t]){K(rs.prototype,e,()=>rs[t](),!0)}),rs.prototype.featuresVolumeControl=rs.canControlVolume(),rs.prototype.movingMediaElementInDOM=!ef,rs.prototype.featuresFullscreenResize=!0,rs.prototype.featuresProgressEvents=!0,rs.prototype.featuresTimeupdateEvents=!0,rs.prototype.featuresVideoFrameCallback=!!(rs.TEST_VID&&rs.TEST_VID.requestVideoFrameCallback),rs.disposeMediaElement=function(e){if(e){for(e.parentNode&&e.parentNode.removeChild(e);e.hasChildNodes();)e.removeChild(e.firstChild);e.removeAttribute("src"),"function"==typeof e.load&&function(){try{e.load()}catch(e){}}()}},rs.resetMediaElement=function(e){if(!e)return;let t=e.querySelectorAll("source"),i=t.length;for(;i--;)e.removeChild(t[i]);e.removeAttribute("src"),"function"==typeof e.load&&function(){try{e.load()}catch(e){}}()},["muted","defaultMuted","autoplay","controls","loop","playsinline"].forEach(function(e){rs.prototype[e]=function(){return this.el_[e]||this.el_.hasAttribute(e)}}),["muted","defaultMuted","autoplay","loop","playsinline"].forEach(function(e){rs.prototype["set"+tE(e)]=function(t){this.el_[e]=t,t?this.el_.setAttribute(e,e):this.el_.removeAttribute(e)}}),["paused","currentTime","buffered","volume","poster","preload","error","seeking","seekable","ended","playbackRate","defaultPlaybackRate","disablePictureInPicture","played","networkState","readyState","videoWidth","videoHeight","crossOrigin"].forEach(function(e){rs.prototype[e]=function(){return this.el_[e]}}),["volume","src","poster","preload","playbackRate","defaultPlaybackRate","disablePictureInPicture","crossOrigin"].forEach(function(e){rs.prototype["set"+tE(e)]=function(t){this.el_[e]=t}}),["pause","load","play"].forEach(function(e){rs.prototype[e]=function(){return this.el_[e]()}}),iu.withSourceHandlers(rs),rs.nativeSourceHandler={},rs.nativeSourceHandler.canPlayType=function(e){try{return rs.TEST_VID.canPlayType(e)}catch(e){return""}},rs.nativeSourceHandler.canHandleSource=function(e,t){if(e.type)return rs.nativeSourceHandler.canPlayType(e.type);if(e.src){let t=t7(e.src);return rs.nativeSourceHandler.canPlayType(`video/${t}`)}return""},rs.nativeSourceHandler.handleSource=function(e,t,i){t.setSrc(e.src)},rs.nativeSourceHandler.dispose=function(){},rs.registerSourceHandler(rs.nativeSourceHandler),iu.registerTech("Html5",rs);let rr=["progress","abort","suspend","emptied","stalled","loadedmetadata","loadeddata","timeupdate","resize","volumechange","texttrackchange"],rn={canplay:"CanPlay",canplaythrough:"CanPlayThrough",playing:"Playing",seeked:"Seeked"},ra=["tiny","xsmall","small","medium","large","xlarge","huge"],ro={};ra.forEach(e=>{let t="x"===e.charAt(0)?`x-${e.substring(1)}`:e;ro[e]=`vjs-layout-${t}`});let rl={tiny:210,xsmall:320,small:425,medium:768,large:1440,xlarge:2560,huge:1/0};class rh extends tP{constructor(e,t,i){if(e.id=e.id||t.id||`vjs_video_${e5++}`,(t=Object.assign(rh.getTagSettings(e),t)).initChildren=!1,t.createEl=!1,t.evented=!1,t.reportTouchActivity=!1,!t.language){let i=e.closest("[lang]");i&&(t.language=i.getAttribute("lang"))}if(super(null,t,i),this.boundDocumentFullscreenChange_=e=>this.documentFullscreenChange_(e),this.boundFullWindowOnEscKey_=e=>this.fullWindowOnEscKey(e),this.boundUpdateStyleEl_=e=>this.updateStyleEl_(e),this.boundApplyInitTime_=e=>this.applyInitTime_(e),this.boundUpdateCurrentBreakpoint_=e=>this.updateCurrentBreakpoint_(e),this.boundHandleTechClick_=e=>this.handleTechClick_(e),this.boundHandleTechDoubleClick_=e=>this.handleTechDoubleClick_(e),this.boundHandleTechTouchStart_=e=>this.handleTechTouchStart_(e),this.boundHandleTechTouchMove_=e=>this.handleTechTouchMove_(e),this.boundHandleTechTouchEnd_=e=>this.handleTechTouchEnd_(e),this.boundHandleTechTap_=e=>this.handleTechTap_(e),this.boundUpdatePlayerHeightOnAudioOnlyMode_=e=>this.updatePlayerHeightOnAudioOnlyMode_(e),this.isFullscreen_=!1,this.log=j(this.id_),this.fsApi_=O,this.isPosterFromTech_=!1,this.queuedCallbacks_=[],this.isReady_=!1,this.hasStarted_=!1,this.userActive_=!1,this.debugEnabled_=!1,this.audioOnlyMode_=!1,this.audioPosterMode_=!1,this.audioOnlyCache_={controlBarHeight:null,playerHeight:null,hiddenChildren:[]},!this.options_||!this.options_.techOrder||!this.options_.techOrder.length)throw Error("No techOrder specified. Did you overwrite videojs.options instead of just changing the properties you want to override?");if(this.tag=e,this.tagAttributes=e&&eD(e),this.language(this.options_.language),t.languages){let e={};Object.getOwnPropertyNames(t.languages).forEach(function(i){e[i.toLowerCase()]=t.languages[i]}),this.languages_=e}else this.languages_=rh.prototype.options_.languages;this.resetCache_(),this.poster_=t.poster||"",this.controls_=!!t.controls,e.controls=!1,e.removeAttribute("controls"),this.changingSrc_=!1,this.playCallbacks_=[],this.playTerminatedQueue_=[],e.hasAttribute("autoplay")?this.autoplay(!0):this.autoplay(this.options_.autoplay),t.plugins&&Object.keys(t.plugins).forEach(e=>{if("function"!=typeof this[e])throw Error(`plugin "${e}" does not exist`)}),this.scrubbing_=!1,this.el_=this.createEl(),tS(this,{eventBusKey:"el_"}),this.fsApi_.requestFullscreen&&(tt(c(),this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),this.on(this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_)),this.fluid_&&this.on(["playerreset","resize"],this.boundUpdateStyleEl_);let s=W(this.options_);if(t.plugins&&Object.keys(t.plugins).forEach(e=>{this[e](t.plugins[e])}),t.debug&&this.debug(!0),this.options_.playerOptions=s,this.middleware_=[],this.playbackRates(t.playbackRates),t.experimentalSvgIcons){let e=new(d()).DOMParser().parseFromString('\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n',"image/svg+xml");if(e.querySelector("parsererror"))N.warn("Failed to load SVG Icons. Falling back to Font Icons."),this.options_.experimentalSvgIcons=null;else{let t=e.documentElement;t.style.display="none",this.el_.appendChild(t),this.addClass("vjs-svg-icons-enabled")}}this.initChildren(),this.isAudio("audio"===e.nodeName.toLowerCase()),this.controls()?this.addClass("vjs-controls-enabled"):this.addClass("vjs-controls-disabled"),this.el_.setAttribute("role","region"),this.isAudio()?this.el_.setAttribute("aria-label",this.localize("Audio Player")):this.el_.setAttribute("aria-label",this.localize("Video Player")),this.isAudio()&&this.addClass("vjs-audio"),t.spatialNavigation&&t.spatialNavigation.enabled&&(this.spatialNavigation=new iI(this),this.addClass("vjs-spatial-navigation-enabled")),em&&this.addClass("vjs-touch-enabled"),ef||this.addClass("vjs-workinghover"),rh.players[this.id_]=this;let r=P.split(".")[0];this.addClass(`vjs-v${r}`),this.userActive(!0),this.reportUserActivity(),this.one("play",e=>this.listenForUserActivity_(e)),this.on("keydown",e=>this.handleKeyDown(e)),this.on("languagechange",e=>this.handleLanguagechange(e)),this.breakpoints(this.options_.breakpoints),this.responsive(this.options_.responsive),this.on("ready",()=>{this.audioPosterMode(this.options_.audioPosterMode),this.audioOnlyMode(this.options_.audioOnlyMode)})}dispose(){this.trigger("dispose"),this.off("dispose"),ti(c(),this.fsApi_.fullscreenchange,this.boundDocumentFullscreenChange_),ti(c(),"keydown",this.boundFullWindowOnEscKey_),this.styleEl_&&this.styleEl_.parentNode&&(this.styleEl_.parentNode.removeChild(this.styleEl_),this.styleEl_=null),rh.players[this.id_]=null,this.tag&&this.tag.player&&(this.tag.player=null),this.el_&&this.el_.player&&(this.el_.player=null),this.tech_&&(this.tech_.dispose(),this.isPosterFromTech_=!1,this.poster_=""),this.playerElIngest_&&(this.playerElIngest_=null),this.tag&&(this.tag=null),ip.hasOwnProperty(this.id())&&delete ip[this.id()],id.names.forEach(e=>{let t=this[id[e].getterName]();t&&t.off&&t.off()}),super.dispose({restoreEl:this.options_.restoreEl})}createEl(){let e,t=this.tag,i=this.playerElIngest_=t.parentNode&&t.parentNode.hasAttribute&&t.parentNode.hasAttribute("data-vjs-player"),s="video-js"===this.tag.tagName.toLowerCase();i?e=this.el_=t.parentNode:s||(e=this.el_=super.createEl("div"));let r=eD(t);if(s){for(e=this.el_=t,t=this.tag=c().createElement("video");e.children.length;)t.appendChild(e.firstChild);ex(e,"video-js")||eI(e,"video-js"),e.appendChild(t),i=this.playerElIngest_=e,Object.keys(e).forEach(i=>{try{t[i]=e[i]}catch(e){}})}t.setAttribute("tabindex","-1"),r.tabindex="-1",ei&&el&&(t.setAttribute("role","application"),r.role="application"),t.removeAttribute("width"),t.removeAttribute("height"),"width"in r&&delete r.width,"height"in r&&delete r.height,Object.getOwnPropertyNames(r).forEach(function(i){s&&"class"===i||e.setAttribute(i,r[i]),s&&t.setAttribute(i,r[i])}),t.playerId=t.id,t.id+="_html5_api",t.className="vjs-tech",t.player=e.player=this,this.addClass("vjs-paused");let n=["IS_SMART_TV","IS_TIZEN","IS_WEBOS","IS_ANDROID","IS_IPAD","IS_IPHONE","IS_CHROMECAST_RECEIVER"].filter(e=>ey[e]).map(e=>"vjs-device-"+e.substring(3).toLowerCase().replace(/\_/g,"-"));if(this.addClass(...n),!0!==d().VIDEOJS_NO_DYNAMIC_STYLE){this.styleEl_=e2("vjs-styles-dimensions");let e=eG(".vjs-styles-defaults"),t=eG("head");t.insertBefore(this.styleEl_,e?e.nextSibling:t.firstChild)}this.fill_=!1,this.fluid_=!1,this.width(this.options_.width),this.height(this.options_.height),this.fill(this.options_.fill),this.fluid(this.options_.fluid),this.aspectRatio(this.options_.aspectRatio),this.crossOrigin(this.options_.crossOrigin||this.options_.crossorigin);let a=t.getElementsByTagName("a");for(let e=0;e{this.on(["playerreset","resize"],this.boundUpdateStyleEl_)})):this.removeClass("vjs-fluid"),this.updateStyleEl_()}fill(e){if(void 0===e)return!!this.fill_;this.fill_=!!e,e?(this.addClass("vjs-fill"),this.fluid(!1)):this.removeClass("vjs-fill")}aspectRatio(e){if(void 0===e)return this.aspectRatio_;if(!/^\d+\:\d+$/.test(e))throw Error("Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.");this.aspectRatio_=e,this.fluid(!0),this.updateStyleEl_()}updateStyleEl_(){let e,t,i,s;if(!0===d().VIDEOJS_NO_DYNAMIC_STYLE){let e="number"==typeof this.width_?this.width_:this.options_.width,t="number"==typeof this.height_?this.height_:this.options_.height,i=this.tech_&&this.tech_.el();i&&(e>=0&&(i.width=e),t>=0&&(i.height=t));return}let r=(void 0!==this.aspectRatio_&&"auto"!==this.aspectRatio_?this.aspectRatio_:this.videoWidth()>0?this.videoWidth()+":"+this.videoHeight():"16:9").split(":"),n=r[1]/r[0];e=void 0!==this.width_?this.width_:void 0!==this.height_?this.height_/n:this.videoWidth()||300,t=void 0!==this.height_?this.height_:e*n,s=/^[^a-zA-Z]/.test(this.id())?"dimensions-"+this.id():this.id()+"-dimensions",this.addClass(s),e4(this.styleEl_,` + .${s} { + width: ${e}px; + height: ${t}px; + } + + .${s}.vjs-fluid:not(.vjs-audio-only-mode) { + padding-top: ${100*n}%; + } + `)}loadTech_(e,t){this.tech_&&this.unloadTech_();let i=tE(e),s=e.charAt(0).toLowerCase()+e.slice(1);"Html5"!==i&&this.tag&&(iu.getTech("Html5").disposeMediaElement(this.tag),this.tag.player=null,this.tag=null),this.techName_=i,this.isReady_=!1;let r=this.autoplay();("string"==typeof this.autoplay()||!0===this.autoplay()&&this.options_.normalizeAutoplay)&&(r=!1);let n={source:t,autoplay:r,nativeControlsForTouch:this.options_.nativeControlsForTouch,playerId:this.id(),techId:`${this.id()}_${s}_api`,playsinline:this.options_.playsinline,preload:this.options_.preload,loop:this.options_.loop,disablePictureInPicture:this.options_.disablePictureInPicture,muted:this.options_.muted,poster:this.poster(),language:this.language(),playerElIngest:this.playerElIngest_||!1,"vtt.js":this.options_["vtt.js"],canOverridePoster:!!this.options_.techCanOverridePoster,enableSourceset:this.options_.enableSourceset};id.names.forEach(e=>{let t=id[e];n[t.getterName]=this[t.privateName]}),Object.assign(n,this.options_[i]),Object.assign(n,this.options_[s]),Object.assign(n,this.options_[e.toLowerCase()]),this.tag&&(n.tag=this.tag),t&&t.src===this.cache_.src&&this.cache_.currentTime>0&&(n.startTime=this.cache_.currentTime);let a=iu.getTech(e);if(!a)throw Error(`No Tech named '${i}' exists! '${i}' should be registered using videojs.registerTech()'`);this.tech_=new a(n),this.tech_.ready(to(this,this.handleTechReady_),!0),tV.jsonToTextTracks(this.textTracksJson_||[],this.tech_),rr.forEach(e=>{this.on(this.tech_,e,t=>this[`handleTech${tE(e)}_`](t))}),Object.keys(rn).forEach(e=>{this.on(this.tech_,e,t=>{if(0===this.tech_.playbackRate()&&this.tech_.seeking()){this.queuedCallbacks_.push({callback:this[`handleTech${rn[e]}_`].bind(this),event:t});return}this[`handleTech${rn[e]}_`](t)})}),this.on(this.tech_,"loadstart",e=>this.handleTechLoadStart_(e)),this.on(this.tech_,"sourceset",e=>this.handleTechSourceset_(e)),this.on(this.tech_,"waiting",e=>this.handleTechWaiting_(e)),this.on(this.tech_,"ended",e=>this.handleTechEnded_(e)),this.on(this.tech_,"seeking",e=>this.handleTechSeeking_(e)),this.on(this.tech_,"play",e=>this.handleTechPlay_(e)),this.on(this.tech_,"pause",e=>this.handleTechPause_(e)),this.on(this.tech_,"durationchange",e=>this.handleTechDurationChange_(e)),this.on(this.tech_,"fullscreenchange",(e,t)=>this.handleTechFullscreenChange_(e,t)),this.on(this.tech_,"fullscreenerror",(e,t)=>this.handleTechFullscreenError_(e,t)),this.on(this.tech_,"enterpictureinpicture",e=>this.handleTechEnterPictureInPicture_(e)),this.on(this.tech_,"leavepictureinpicture",e=>this.handleTechLeavePictureInPicture_(e)),this.on(this.tech_,"error",e=>this.handleTechError_(e)),this.on(this.tech_,"posterchange",e=>this.handleTechPosterChange_(e)),this.on(this.tech_,"textdata",e=>this.handleTechTextData_(e)),this.on(this.tech_,"ratechange",e=>this.handleTechRateChange_(e)),this.on(this.tech_,"loadedmetadata",this.boundUpdateStyleEl_),this.usingNativeControls(this.techGet_("controls")),this.controls()&&!this.usingNativeControls()&&this.addTechControlsListeners_(),this.tech_.el().parentNode===this.el()||"Html5"===i&&this.tag||eE(this.tech_.el(),this.el()),this.tag&&(this.tag.player=null,this.tag=null)}unloadTech_(){id.names.forEach(e=>{let t=id[e];this[t.privateName]=this[t.getterName]()}),this.textTracksJson_=tV.textTracksToJson(this.tech_),this.isReady_=!1,this.tech_.dispose(),this.tech_=!1,this.isPosterFromTech_&&(this.poster_="",this.trigger("posterchange")),this.isPosterFromTech_=!1}tech(e){return void 0===e&&N.warn("Using the tech directly can be dangerous. I hope you know what you're doing.\nSee https://github.com/videojs/video.js/issues/2617 for more info.\n"),this.tech_}version(){return{"video.js":P}}addTechControlsListeners_(){this.removeTechControlsListeners_(),this.on(this.tech_,"click",this.boundHandleTechClick_),this.on(this.tech_,"dblclick",this.boundHandleTechDoubleClick_),this.on(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.on(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.on(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.on(this.tech_,"tap",this.boundHandleTechTap_)}removeTechControlsListeners_(){this.off(this.tech_,"tap",this.boundHandleTechTap_),this.off(this.tech_,"touchstart",this.boundHandleTechTouchStart_),this.off(this.tech_,"touchmove",this.boundHandleTechTouchMove_),this.off(this.tech_,"touchend",this.boundHandleTechTouchEnd_),this.off(this.tech_,"click",this.boundHandleTechClick_),this.off(this.tech_,"dblclick",this.boundHandleTechDoubleClick_)}handleTechReady_(){this.triggerReady(),this.cache_.volume&&this.techCall_("setVolume",this.cache_.volume),this.handleTechPosterChange_(),this.handleTechDurationChange_()}handleTechLoadStart_(){this.removeClass("vjs-ended","vjs-seeking"),this.error(null),this.handleTechDurationChange_(),this.paused()&&this.hasStarted(!1),this.trigger("loadstart"),this.manualAutoplay_(!0===this.autoplay()&&this.options_.normalizeAutoplay?"play":this.autoplay())}manualAutoplay_(e){let t;if(!this.tech_||"string"!=typeof e)return;let i=()=>{let e=this.muted();this.muted(!0);let t=()=>{this.muted(e)};this.playTerminatedQueue_.push(t);let i=this.play();if(t$(i))return i.catch(e=>{throw t(),Error(`Rejection at manualAutoplay. Restoring muted value. ${e||""}`)})};if("any"!==e||this.muted()?t="muted"!==e||this.muted()?this.play():i():t$(t=this.play())&&(t=t.catch(i)),t$(t))return t.then(()=>{this.trigger({type:"autoplay-success",autoplay:e})}).catch(()=>{this.trigger({type:"autoplay-failure",autoplay:e})})}updateSourceCaches_(e=""){let t=e,i="";"string"!=typeof t&&(t=e.src,i=e.type),this.cache_.source=this.cache_.source||{},this.cache_.sources=this.cache_.sources||[],t&&!i&&(i=ik(this,t)),this.cache_.source=W({},e,{src:t,type:i});let s=this.cache_.sources.filter(e=>e.src&&e.src===t),r=[],n=this.$$("source"),a=[];for(let e=0;ethis.updateSourceCaches_(e),i=this.currentSource().src,s=e.src;i&&!/^blob:/.test(i)&&/^blob:/.test(s)&&(!this.lastSource_||this.lastSource_.tech!==s&&this.lastSource_.player!==i)&&(t=()=>{}),t(s),e.src||this.tech_.any(["sourceset","loadstart"],e=>{if("sourceset"===e.type)return;let t=this.techGet_("currentSrc");this.lastSource_.tech=t,this.updateSourceCaches_(t)})}this.lastSource_={player:this.currentSource().src,tech:e.src},this.trigger({src:e.src,type:"sourceset"})}hasStarted(e){if(void 0===e)return this.hasStarted_;e!==this.hasStarted_&&(this.hasStarted_=e,this.hasStarted_?this.addClass("vjs-has-started"):this.removeClass("vjs-has-started"))}handleTechPlay_(){this.removeClass("vjs-ended","vjs-paused"),this.addClass("vjs-playing"),this.hasStarted(!0),this.trigger("play")}handleTechRateChange_(){this.tech_.playbackRate()>0&&0===this.cache_.lastPlaybackRate&&(this.queuedCallbacks_.forEach(e=>e.callback(e.event)),this.queuedCallbacks_=[]),this.cache_.lastPlaybackRate=this.tech_.playbackRate(),this.trigger("ratechange")}handleTechWaiting_(){this.addClass("vjs-waiting"),this.trigger("waiting");let e=this.currentTime(),t=()=>{e!==this.currentTime()&&(this.removeClass("vjs-waiting"),this.off("timeupdate",t))};this.on("timeupdate",t)}handleTechCanPlay_(){this.removeClass("vjs-waiting"),this.trigger("canplay")}handleTechCanPlayThrough_(){this.removeClass("vjs-waiting"),this.trigger("canplaythrough")}handleTechPlaying_(){this.removeClass("vjs-waiting"),this.trigger("playing")}handleTechSeeking_(){this.addClass("vjs-seeking"),this.trigger("seeking")}handleTechSeeked_(){this.removeClass("vjs-seeking","vjs-ended"),this.trigger("seeked")}handleTechPause_(){this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.trigger("pause")}handleTechEnded_(){this.addClass("vjs-ended"),this.removeClass("vjs-waiting"),this.options_.loop?(this.currentTime(0),this.play()):this.paused()||this.pause(),this.trigger("ended")}handleTechDurationChange_(){this.duration(this.techGet_("duration"))}handleTechClick_(e){this.controls_&&(void 0===this.options_||void 0===this.options_.userActions||void 0===this.options_.userActions.click||!1!==this.options_.userActions.click)&&(void 0!==this.options_&&void 0!==this.options_.userActions&&"function"==typeof this.options_.userActions.click?this.options_.userActions.click.call(this,e):this.paused()?tq(this.play()):this.pause())}handleTechDoubleClick_(e){this.controls_&&(Array.prototype.some.call(this.$$(".vjs-control-bar, .vjs-modal-dialog"),t=>t.contains(e.target))||void 0!==this.options_&&void 0!==this.options_.userActions&&void 0!==this.options_.userActions.doubleClick&&!1===this.options_.userActions.doubleClick||(void 0!==this.options_&&void 0!==this.options_.userActions&&"function"==typeof this.options_.userActions.doubleClick?this.options_.userActions.doubleClick.call(this,e):this.isInPictureInPicture()&&!c().pictureInPictureElement?this.exitPictureInPicture():this.isFullscreen()?this.exitFullscreen():this.requestFullscreen()))}handleTechTap_(){this.userActive(!this.userActive())}handleTechTouchStart_(){this.userWasActive=this.userActive()}handleTechTouchMove_(){this.userWasActive&&this.reportUserActivity()}handleTechTouchEnd_(e){e.cancelable&&e.preventDefault()}toggleFullscreenClass_(){this.isFullscreen()?this.addClass("vjs-fullscreen"):this.removeClass("vjs-fullscreen")}documentFullscreenChange_(e){let t=e.target.player;if(t&&t!==this)return;let i=this.el(),s=c()[this.fsApi_.fullscreenElement]===i;!s&&i.matches&&(s=i.matches(":"+this.fsApi_.fullscreen)),this.isFullscreen(s)}handleTechFullscreenChange_(e,t){t&&(t.nativeIOSFullscreen&&(this.addClass("vjs-ios-native-fs"),this.tech_.one("webkitendfullscreen",()=>{this.removeClass("vjs-ios-native-fs")})),this.isFullscreen(t.isFullscreen))}handleTechFullscreenError_(e,t){this.trigger("fullscreenerror",t)}togglePictureInPictureClass_(){this.isInPictureInPicture()?this.addClass("vjs-picture-in-picture"):this.removeClass("vjs-picture-in-picture")}handleTechEnterPictureInPicture_(e){this.isInPictureInPicture(!0)}handleTechLeavePictureInPicture_(e){this.isInPictureInPicture(!1)}handleTechError_(){let e=this.tech_.error();e&&this.error(e)}handleTechTextData_(){let e=null;arguments.length>1&&(e=arguments[1]),this.trigger("textdata",e)}getCache(){return this.cache_}resetCache_(){this.cache_={currentTime:0,initTime:0,inactivityTimeout:this.options_.inactivityTimeout,duration:NaN,lastVolume:1,lastPlaybackRate:this.defaultPlaybackRate(),media:null,src:"",source:{},sources:[],playbackRates:[],volume:1}}techCall_(e,t){this.ready(function(){if(e in iy){var i;return i=this.middleware_,this.tech_[e](i.reduce(ib(e),t))}if(e in iv)return ig(this.middleware_,this.tech_,e,t);try{this.tech_&&this.tech_[e](t)}catch(e){throw N(e),e}},!0)}techGet_(e){if(this.tech_&&this.tech_.isReady_){if(e in i_){var t,i;return t=this.middleware_,i=this.tech_,t.reduceRight(ib(e),i[e]())}if(e in iv)return ig(this.middleware_,this.tech_,e);try{return this.tech_[e]()}catch(t){if(void 0===this.tech_[e])throw N(`Video.js: ${e} method not defined for ${this.techName_} playback technology.`,t),t;if("TypeError"===t.name)throw N(`Video.js: ${e} unavailable on ${this.techName_} playback technology element.`,t),this.tech_.isReady_=!1,t;throw N(t),t}}}play(){return new Promise(e=>{this.play_(e)})}play_(e=tq){this.playCallbacks_.push(e);let t=!!(!this.changingSrc_&&(this.src()||this.currentSrc())),i=!!(e_||ef);if(this.waitToPlay_&&(this.off(["ready","loadstart"],this.waitToPlay_),this.waitToPlay_=null),!this.isReady_||!t){this.waitToPlay_=e=>{this.play_()},this.one(["ready","loadstart"],this.waitToPlay_),!t&&i&&this.load();return}let s=this.techGet_("play");i&&this.hasClass("vjs-ended")&&this.resetProgressBar_(),null===s?this.runPlayTerminatedQueue_():this.runPlayCallbacks_(s)}runPlayTerminatedQueue_(){let e=this.playTerminatedQueue_.slice(0);this.playTerminatedQueue_=[],e.forEach(function(e){e()})}runPlayCallbacks_(e){let t=this.playCallbacks_.slice(0);this.playCallbacks_=[],this.playTerminatedQueue_=[],t.forEach(function(t){t(e)})}pause(){this.techCall_("pause")}paused(){return!1!==this.techGet_("paused")}played(){return this.techGet_("played")||tD(0,0)}scrubbing(e){if(void 0===e)return this.scrubbing_;this.scrubbing_=!!e,this.techCall_("setScrubbing",this.scrubbing_),e?this.addClass("vjs-scrubbing"):this.removeClass("vjs-scrubbing")}currentTime(e){if(void 0===e)return this.cache_.currentTime=this.techGet_("currentTime")||0,this.cache_.currentTime;if(e<0&&(e=0),!this.isReady_||this.changingSrc_||!this.tech_||!this.tech_.isReady_){this.cache_.initTime=e,this.off("canplay",this.boundApplyInitTime_),this.one("canplay",this.boundApplyInitTime_);return}this.techCall_("setCurrentTime",e),this.cache_.initTime=0,isFinite(e)&&(this.cache_.currentTime=Number(e))}applyInitTime_(){this.currentTime(this.cache_.initTime)}duration(e){if(void 0===e)return void 0!==this.cache_.duration?this.cache_.duration:NaN;(e=parseFloat(e))<0&&(e=1/0),e===this.cache_.duration||(this.cache_.duration=e,e===1/0?this.addClass("vjs-live"):this.removeClass("vjs-live"),isNaN(e)||this.trigger("durationchange"))}remainingTime(){return this.duration()-this.currentTime()}remainingTimeDisplay(){return Math.floor(this.duration())-Math.floor(this.currentTime())}buffered(){let e=this.techGet_("buffered");return e&&e.length||(e=tD(0,0)),e}seekable(){let e=this.techGet_("seekable");return e&&e.length||(e=tD(0,0)),e}seeking(){return this.techGet_("seeking")}ended(){return this.techGet_("ended")}networkState(){return this.techGet_("networkState")}readyState(){return this.techGet_("readyState")}bufferedPercent(){return tj(this.buffered(),this.duration())}bufferedEnd(){let e=this.buffered(),t=this.duration(),i=e.end(e.length-1);return i>t&&(i=t),i}volume(e){let t;if(void 0!==e){t=Math.max(0,Math.min(1,e)),this.cache_.volume=t,this.techCall_("setVolume",t),t>0&&this.lastVolume_(t);return}return isNaN(t=parseFloat(this.techGet_("volume")))?1:t}muted(e){if(void 0!==e){this.techCall_("setMuted",e);return}return this.techGet_("muted")||!1}defaultMuted(e){return void 0!==e&&this.techCall_("setDefaultMuted",e),this.techGet_("defaultMuted")||!1}lastVolume_(e){if(void 0!==e&&0!==e){this.cache_.lastVolume=e;return}return this.cache_.lastVolume}supportsFullScreen(){return this.techGet_("supportsFullScreen")||!1}isFullscreen(e){if(void 0!==e){let t=this.isFullscreen_;this.isFullscreen_=!!e,this.isFullscreen_!==t&&this.fsApi_.prefixed&&this.trigger("fullscreenchange"),this.toggleFullscreenClass_();return}return this.isFullscreen_}requestFullscreen(e){this.isInPictureInPicture()&&this.exitPictureInPicture();let t=this;return new Promise((i,s)=>{function r(){t.off("fullscreenerror",a),t.off("fullscreenchange",n)}function n(){r(),i()}function a(e,t){r(),s(t)}t.one("fullscreenchange",n),t.one("fullscreenerror",a);let o=t.requestFullscreenHelper_(e);o&&(o.then(r,r),o.then(i,s))})}requestFullscreenHelper_(e){let t;if(this.fsApi_.prefixed||(t=this.options_.fullscreen&&this.options_.fullscreen.options||{},void 0===e||(t=e)),this.fsApi_.requestFullscreen){let e=this.el_[this.fsApi_.requestFullscreen](t);return e&&e.then(()=>this.isFullscreen(!0),()=>this.isFullscreen(!1)),e}this.tech_.supportsFullScreen()&&!0==!this.options_.preferFullWindow?this.techCall_("enterFullScreen"):this.enterFullWindow()}exitFullscreen(){let e=this;return new Promise((t,i)=>{function s(){e.off("fullscreenerror",n),e.off("fullscreenchange",r)}function r(){s(),t()}function n(e,t){s(),i(t)}e.one("fullscreenchange",r),e.one("fullscreenerror",n);let a=e.exitFullscreenHelper_();a&&(a.then(s,s),a.then(t,i))})}exitFullscreenHelper_(){if(this.fsApi_.requestFullscreen){let e=c()[this.fsApi_.exitFullscreen]();return e&&tq(e.then(()=>this.isFullscreen(!1))),e}this.tech_.supportsFullScreen()&&!0==!this.options_.preferFullWindow?this.techCall_("exitFullScreen"):this.exitFullWindow()}enterFullWindow(){this.isFullscreen(!0),this.isFullWindow=!0,this.docOrigOverflow=c().documentElement.style.overflow,tt(c(),"keydown",this.boundFullWindowOnEscKey_),c().documentElement.style.overflow="hidden",eI(c().body,"vjs-full-window"),this.trigger("enterFullWindow")}fullWindowOnEscKey(e){"Escape"===e.key&&!0===this.isFullscreen()&&(this.isFullWindow?this.exitFullWindow():this.exitFullscreen())}exitFullWindow(){this.isFullscreen(!1),this.isFullWindow=!1,ti(c(),"keydown",this.boundFullWindowOnEscKey_),c().documentElement.style.overflow=this.docOrigOverflow,eP(c().body,"vjs-full-window"),this.trigger("exitFullWindow")}disablePictureInPicture(e){if(void 0===e)return this.techGet_("disablePictureInPicture");this.techCall_("setDisablePictureInPicture",e),this.options_.disablePictureInPicture=e,this.trigger("disablepictureinpicturechanged")}isInPictureInPicture(e){if(void 0!==e){this.isInPictureInPicture_=!!e,this.togglePictureInPictureClass_();return}return!!this.isInPictureInPicture_}requestPictureInPicture(){if(this.options_.enableDocumentPictureInPicture&&d().documentPictureInPicture){let e=c().createElement(this.el().tagName);return e.classList=this.el().classList,e.classList.add("vjs-pip-container"),this.posterImage&&e.appendChild(this.posterImage.el().cloneNode(!0)),this.titleBar&&e.appendChild(this.titleBar.el().cloneNode(!0)),e.appendChild(eC("p",{className:"vjs-pip-text"},{},this.localize("Playing in picture-in-picture"))),d().documentPictureInPicture.requestWindow({width:this.videoWidth(),height:this.videoHeight()}).then(t=>(eY(t),this.el_.parentNode.insertBefore(e,this.el_),t.document.body.appendChild(this.el_),t.document.body.classList.add("vjs-pip-window"),this.player_.isInPictureInPicture(!0),this.player_.trigger({type:"enterpictureinpicture",pipWindow:t}),t.addEventListener("pagehide",t=>{let i=t.target.querySelector(".video-js");e.parentNode.replaceChild(i,e),this.player_.isInPictureInPicture(!1),this.player_.trigger("leavepictureinpicture")}),t))}return"pictureInPictureEnabled"in c()&&!1===this.disablePictureInPicture()?this.techGet_("requestPictureInPicture"):Promise.reject("No PiP mode is available")}exitPictureInPicture(){return d().documentPictureInPicture&&d().documentPictureInPicture.window?(d().documentPictureInPicture.window.close(),Promise.resolve()):"pictureInPictureEnabled"in c()?c().exitPictureInPicture():void 0}handleKeyDown(e){let{userActions:t}=this.options_;if(t&&t.hotkeys)!(e=>{let t=e.tagName.toLowerCase();return!!e.isContentEditable||("input"===t?-1===["button","checkbox","hidden","radio","reset","submit"].indexOf(e.type):-1!==["textarea"].indexOf(t))})(this.el_.ownerDocument.activeElement)&&("function"==typeof t.hotkeys?t.hotkeys.call(this,e):this.handleHotkeys(e))}handleHotkeys(e){let{fullscreenKey:t=t=>"f"===e.key.toLowerCase(),muteKey:i=t=>"m"===e.key.toLowerCase(),playPauseKey:s=t=>"k"===e.key.toLowerCase()||" "===e.key.toLowerCase()}=this.options_.userActions?this.options_.userActions.hotkeys:{};if(t.call(this,e)){e.preventDefault(),e.stopPropagation();let t=tP.getComponent("FullscreenToggle");!1!==c()[this.fsApi_.fullscreenEnabled]&&t.prototype.handleClick.call(this,e)}else i.call(this,e)?(e.preventDefault(),e.stopPropagation(),tP.getComponent("MuteToggle").prototype.handleClick.call(this,e)):s.call(this,e)&&(e.preventDefault(),e.stopPropagation(),tP.getComponent("PlayToggle").prototype.handleClick.call(this,e))}canPlayType(e){let t;for(let i=0,s=this.options_.techOrder;i[e,iu.getTech(e)]).filter(([e,t])=>t?t.isSupported():(N.error(`The "${e}" tech is undefined. Skipped browser support check for that tech.`),!1)),s=function(e,t,i){let s;return e.some(e=>t.some(t=>{if(s=i(e,t))return!0})),s},r=([e,t],i)=>{if(t.canPlaySource(i,this.options_[e.toLowerCase()]))return{source:i,tech:e}};if(this.options_.sourceOrder)t=s(e,i,(e,t)=>r(t,e));else t=s(i,e,r);return t||!1}handleSrc_(e,t){if(void 0===e)return this.cache_.src||"";this.resetRetryOnError_&&this.resetRetryOnError_();let i=iC(e);if(!i.length){this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0);return}if(this.changingSrc_=!0,t||(this.cache_.sources=i),this.updateSourceCaches_(i[0]),!function(e,t,i){e.setTimeout(()=>(function e(t={},i=[],s,r,n=[],a=!1){let[o,...l]=i;if("string"==typeof o)e(t,ic[o],s,r,n,a);else if(o){let i=function(e,t){let i=ip[e.id()],s=null;if(null==i)return s=t(e),ip[e.id()]=[[t,s]],s;for(let e=0;e{if(this.middleware_=s,t||(this.cache_.sources=i),this.updateSourceCaches_(e),this.src_(e))return i.length>1?this.handleSrc_(i.slice(1)):(this.changingSrc_=!1,this.setTimeout(function(){this.error({code:4,message:this.options_.notSupportedMessage})},0),void this.triggerReady());!function(e,t){e.forEach(e=>e.setTech&&e.setTech(t))}(s,this.tech_)}),i.length>1){let e=()=>{this.error(null),this.handleSrc_(i.slice(1),!0)},t=()=>{this.off("error",e)};this.one("error",e),this.one("playing",t),this.resetRetryOnError_=()=>{this.off("error",e),this.off("playing",t)}}}src(e){return this.handleSrc_(e,!1)}src_(e){let t=this.selectSource([e]);return!t||(tx(t.tech,this.techName_)?this.ready(function(){this.tech_.constructor.prototype.hasOwnProperty("setSource")?this.techCall_("setSource",e):this.techCall_("src",e.src),this.changingSrc_=!1},!0):(this.changingSrc_=!0,this.loadTech_(t.tech,t.source),this.tech_.ready(()=>{this.changingSrc_=!1})),!1)}addSourceElement(e,t){return!!this.tech_&&this.tech_.addSourceElement(e,t)}removeSourceElement(e){return!!this.tech_&&this.tech_.removeSourceElement(e)}load(){if(this.tech_&&this.tech_.vhs){this.src(this.currentSource());return}this.techCall_("load")}reset(){this.paused()?this.doReset_():tq(this.play().then(()=>this.doReset_()))}doReset_(){this.tech_&&this.tech_.clearTracks("text"),this.removeClass("vjs-playing"),this.addClass("vjs-paused"),this.resetCache_(),this.poster(""),this.loadTech_(this.options_.techOrder[0],null),this.techCall_("reset"),this.resetControlBarUI_(),this.error(null),this.titleBar&&this.titleBar.update({title:void 0,description:void 0}),tp(this)&&this.trigger("playerreset")}resetControlBarUI_(){this.resetProgressBar_(),this.resetPlaybackRate_(),this.resetVolumeBar_()}resetProgressBar_(){this.currentTime(0);let{currentTimeDisplay:e,durationDisplay:t,progressControl:i,remainingTimeDisplay:s}=this.controlBar||{},{seekBar:r}=i||{};e&&e.updateContent(),t&&t.updateContent(),s&&s.updateContent(),r&&(r.update(),r.loadProgressBar&&r.loadProgressBar.update())}resetPlaybackRate_(){this.playbackRate(this.defaultPlaybackRate()),this.handleTechRateChange_()}resetVolumeBar_(){this.volume(1),this.trigger("volumechange")}currentSources(){let e=this.currentSource(),t=[];return 0!==Object.keys(e).length&&t.push(e),this.cache_.sources||t}currentSource(){return this.cache_.source||{}}currentSrc(){return this.currentSource()&&this.currentSource().src||""}currentType(){return this.currentSource()&&this.currentSource().type||""}preload(e){if(void 0!==e){this.techCall_("setPreload",e),this.options_.preload=e;return}return this.techGet_("preload")}autoplay(e){let t;if(void 0===e)return this.options_.autoplay||!1;"string"==typeof e&&/(any|play|muted)/.test(e)||!0===e&&this.options_.normalizeAutoplay?(this.options_.autoplay=e,this.manualAutoplay_("string"==typeof e?e:"play"),t=!1):e?this.options_.autoplay=!0:this.options_.autoplay=!1,t=void 0===t?this.options_.autoplay:t,this.tech_&&this.techCall_("setAutoplay",t)}playsinline(e){return void 0!==e&&(this.techCall_("setPlaysinline",e),this.options_.playsinline=e),this.techGet_("playsinline")}loop(e){if(void 0!==e){this.techCall_("setLoop",e),this.options_.loop=e;return}return this.techGet_("loop")}poster(e){if(void 0===e)return this.poster_;e||(e=""),e!==this.poster_&&(this.poster_=e,this.techCall_("setPoster",e),this.isPosterFromTech_=!1,this.trigger("posterchange"))}handleTechPosterChange_(){if((!this.poster_||this.options_.techCanOverridePoster)&&this.tech_&&this.tech_.poster){let e=this.tech_.poster()||"";e!==this.poster_&&(this.poster_=e,this.isPosterFromTech_=!0,this.trigger("posterchange"))}}controls(e){if(void 0===e)return!!this.controls_;e=!!e,this.controls_!==e&&(this.controls_=e,this.usingNativeControls()&&this.techCall_("setControls",e),this.controls_?(this.removeClass("vjs-controls-disabled"),this.addClass("vjs-controls-enabled"),this.trigger("controlsenabled"),this.usingNativeControls()||this.addTechControlsListeners_()):(this.removeClass("vjs-controls-enabled"),this.addClass("vjs-controls-disabled"),this.trigger("controlsdisabled"),this.usingNativeControls()||this.removeTechControlsListeners_()))}usingNativeControls(e){if(void 0===e)return!!this.usingNativeControls_;e=!!e,this.usingNativeControls_!==e&&(this.usingNativeControls_=e,this.usingNativeControls_?(this.addClass("vjs-using-native-controls"),this.trigger("usingnativecontrols")):(this.removeClass("vjs-using-native-controls"),this.trigger("usingcustomcontrols")))}error(e){if(void 0===e)return this.error_||null;if(L("beforeerror").forEach(t=>{let i=t(this,e);if(!(V(i)&&!Array.isArray(i)||"string"==typeof i||"number"==typeof i||null===i)){this.log.error("please return a value that MediaError expects in beforeerror hooks");return}e=i}),this.options_.suppressNotSupportedError&&e&&4===e.code){let t=function(){this.error(e)};this.options_.suppressNotSupportedError=!1,this.any(["click","touchstart"],t),this.one("loadstart",function(){this.off(["click","touchstart"],t)});return}if(null===e){this.error_=null,this.removeClass("vjs-error"),this.errorDisplay&&this.errorDisplay.close();return}this.error_=new tF(e),this.addClass("vjs-error"),N.error(`(CODE:${this.error_.code} ${tF.errorTypes[this.error_.code]})`,this.error_.message,this.error_),this.trigger("error"),L("error").forEach(e=>e(this,this.error_))}reportUserActivity(e){this.userActivity_=!0}userActive(e){if(void 0===e)return this.userActive_;if((e=!!e)!==this.userActive_){if(this.userActive_=e,this.userActive_){this.userActivity_=!0,this.removeClass("vjs-user-inactive"),this.addClass("vjs-user-active"),this.trigger("useractive");return}this.tech_&&this.tech_.one("mousemove",function(e){e.stopPropagation(),e.preventDefault()}),this.userActivity_=!1,this.removeClass("vjs-user-active"),this.addClass("vjs-user-inactive"),this.trigger("userinactive")}}listenForUserActivity_(){let e,t,i,s;let r=to(this,this.reportUserActivity),n=function(t){r(),this.clearInterval(e)};this.on("mousedown",function(){r(),this.clearInterval(e),e=this.setInterval(r,250)}),this.on("mousemove",function(e){(e.screenX!==t||e.screenY!==i)&&(t=e.screenX,i=e.screenY,r())}),this.on("mouseup",n),this.on("mouseleave",n);let a=this.getChild("controlBar");!a||ef||J||(a.on("mouseenter",function(e){0!==this.player().options_.inactivityTimeout&&(this.player().cache_.inactivityTimeout=this.player().options_.inactivityTimeout),this.player().options_.inactivityTimeout=0}),a.on("mouseleave",function(e){this.player().options_.inactivityTimeout=this.player().cache_.inactivityTimeout})),this.on("keydown",r),this.on("keyup",r),this.setInterval(function(){if(!this.userActivity_)return;this.userActivity_=!1,this.userActive(!0),this.clearTimeout(s);let e=this.options_.inactivityTimeout;!(e<=0)&&(s=this.setTimeout(function(){this.userActivity_||this.userActive(!1)},e))},250)}playbackRate(e){if(void 0!==e){this.techCall_("setPlaybackRate",e);return}return this.tech_&&this.tech_.featuresPlaybackRate?this.cache_.lastPlaybackRate||this.techGet_("playbackRate"):1}defaultPlaybackRate(e){return void 0!==e?this.techCall_("setDefaultPlaybackRate",e):this.tech_&&this.tech_.featuresPlaybackRate?this.techGet_("defaultPlaybackRate"):1}isAudio(e){if(void 0!==e){this.isAudio_=!!e;return}return!!this.isAudio_}updatePlayerHeightOnAudioOnlyMode_(){let e=this.getChild("ControlBar");e&&this.audioOnlyCache_.controlBarHeight!==e.currentHeight()&&(this.audioOnlyCache_.controlBarHeight=e.currentHeight(),this.height(this.audioOnlyCache_.controlBarHeight))}enableAudioOnlyUI_(){this.addClass("vjs-audio-only-mode");let e=this.children(),t=this.getChild("ControlBar"),i=t&&t.currentHeight();e.forEach(e=>{e!==t&&e.el_&&!e.hasClass("vjs-hidden")&&(e.hide(),this.audioOnlyCache_.hiddenChildren.push(e))}),this.audioOnlyCache_.playerHeight=this.currentHeight(),this.audioOnlyCache_.controlBarHeight=i,this.on("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.height(i),this.trigger("audioonlymodechange")}disableAudioOnlyUI_(){this.removeClass("vjs-audio-only-mode"),this.off("playerresize",this.boundUpdatePlayerHeightOnAudioOnlyMode_),this.audioOnlyCache_.hiddenChildren.forEach(e=>e.show()),this.height(this.audioOnlyCache_.playerHeight),this.trigger("audioonlymodechange")}audioOnlyMode(e){if("boolean"!=typeof e||e===this.audioOnlyMode_)return this.audioOnlyMode_;if(this.audioOnlyMode_=e,e){let e=[];return this.isInPictureInPicture()&&e.push(this.exitPictureInPicture()),this.isFullscreen()&&e.push(this.exitFullscreen()),this.audioPosterMode()&&e.push(this.audioPosterMode(!1)),Promise.all(e).then(()=>this.enableAudioOnlyUI_())}return Promise.resolve().then(()=>this.disableAudioOnlyUI_())}enablePosterModeUI_(){(this.tech_&&this.tech_).hide(),this.addClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}disablePosterModeUI_(){(this.tech_&&this.tech_).show(),this.removeClass("vjs-audio-poster-mode"),this.trigger("audiopostermodechange")}audioPosterMode(e){return"boolean"!=typeof e||e===this.audioPosterMode_?this.audioPosterMode_:(this.audioPosterMode_=e,e)?this.audioOnlyMode()?this.audioOnlyMode(!1).then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.enablePosterModeUI_()}):Promise.resolve().then(()=>{this.disablePosterModeUI_()})}addTextTrack(e,t,i){if(this.tech_)return this.tech_.addTextTrack(e,t,i)}addRemoteTextTrack(e,t){if(this.tech_)return this.tech_.addRemoteTextTrack(e,t)}removeRemoteTextTrack(e={}){let{track:t}=e;if(t||(t=e),this.tech_)return this.tech_.removeRemoteTextTrack(t)}getVideoPlaybackQuality(){return this.techGet_("getVideoPlaybackQuality")}videoWidth(){return this.tech_&&this.tech_.videoWidth&&this.tech_.videoWidth()||0}videoHeight(){return this.tech_&&this.tech_.videoHeight&&this.tech_.videoHeight()||0}language(e){if(void 0===e)return this.language_;this.language_!==String(e).toLowerCase()&&(this.language_=String(e).toLowerCase(),tp(this)&&this.trigger("languagechange"))}languages(){return W(rh.prototype.options_.languages,this.languages_)}toJSON(){let e=W(this.options_),t=e.tracks;e.tracks=[];for(let i=0;i{this.removeChild(i)}),i.open(),i}updateCurrentBreakpoint_(){if(!this.responsive())return;let e=this.currentBreakpoint(),t=this.currentWidth();for(let i=0;ithis.addRemoteTextTrack(e,!1)),this.titleBar&&this.titleBar.update({title:h,description:n||s||""}),this.ready(t)}getMedia(){if(!this.cache_.media){let e=this.poster(),t={src:this.currentSources(),textTracks:Array.prototype.map.call(this.remoteTextTracks(),e=>({kind:e.kind,label:e.label,language:e.language,src:e.src}))};return e&&(t.poster=e,t.artwork=[{src:t.poster,type:iS(t.poster)}]),t}return W(this.cache_.media)}static getTagSettings(e){let t={sources:[],tracks:[]},i=eD(e),s=i["data-setup"];if(ex(e,"vjs-fill")&&(i.fill=!0),ex(e,"vjs-fluid")&&(i.fluid=!0),null!==s)try{Object.assign(i,JSON.parse(s||"{}"))}catch(e){N.error("data-setup",e)}if(Object.assign(t,i),e.hasChildNodes()){let i=e.childNodes;for(let e=0,s=i.length;e"number"==typeof e)&&(this.cache_.playbackRates=e,this.trigger("playbackrateschange"))}}id.names.forEach(function(e){let t=id[e];rh.prototype[t.getterName]=function(){return this.tech_?this.tech_[t.getterName]():(this[t.privateName]=this[t.privateName]||new t.ListClass,this[t.privateName])}}),rh.prototype.crossorigin=rh.prototype.crossOrigin,rh.players={};let rd=d().navigator;rh.prototype.options_={techOrder:iu.defaultTechOrder_,html5:{},enableSourceset:!0,inactivityTimeout:2e3,playbackRates:[],liveui:!1,children:["mediaLoader","posterImage","titleBar","textTrackDisplay","loadingSpinner","bigPlayButton","liveTracker","controlBar","errorDisplay","textTrackSettings","resizeManager"],language:rd&&(rd.languages&&rd.languages[0]||rd.userLanguage||rd.language)||"en",languages:{},notSupportedMessage:"No compatible source was found for this media.",normalizeAutoplay:!1,fullscreen:{options:{navigationUI:"hide"}},breakpoints:{},responsive:!1,audioOnlyMode:!1,audioPosterMode:!1,spatialNavigation:{enabled:!1,horizontalSeek:!1},enableSmoothSeeking:!1,disableSeekWhileScrubbingOnMobile:!1},rr.forEach(function(e){rh.prototype[`handleTech${tE(e)}_`]=function(){return this.trigger(e)}}),tP.registerComponent("Player",rh);let ru="plugin",rc="activePlugins_",rp={},rm=e=>rp.hasOwnProperty(e),rg=e=>rm(e)?rp[e]:void 0,rf=(e,t)=>{e[rc]=e[rc]||{},e[rc][t]=!0},r_=(e,t,i)=>{let s=(i?"before":"")+"pluginsetup";e.trigger(s,t),e.trigger(s+":"+t.name,t)},ry=function(e,t){let i=function(){r_(this,{name:e,plugin:t,instance:null},!0);let i=t.apply(this,arguments);return rf(this,e),r_(this,{name:e,plugin:t,instance:i}),i};return Object.keys(t).forEach(function(e){i[e]=t[e]}),i},rv=(e,t)=>(t.prototype.name=e,function(...i){r_(this,{name:e,plugin:t,instance:null},!0);let s=new t(...[this,...i]);return this[e]=()=>s,r_(this,s.getEventHash()),s});class rb{constructor(e){if(this.constructor===rb)throw Error("Plugin must be sub-classed; not directly instantiated.");this.player=e,this.log||(this.log=this.player.log.createLogger(this.name)),tS(this),delete this.trigger,tC(this,this.constructor.defaultState),rf(e,this.name),this.dispose=this.dispose.bind(this),e.on("dispose",this.dispose)}version(){return this.constructor.VERSION}getEventHash(e={}){return e.name=this.name,e.plugin=this.constructor,e.instance=this,e}trigger(e,t={}){return ts(this.eventBusEl_,e,this.getEventHash(t))}handleStateChanged(e){}dispose(){let{name:e,player:t}=this;this.trigger("dispose"),this.off(),t.off("dispose",this.dispose),t[rc][e]=!1,this.player=this.state=null,t[e]=rv(e,rp[e])}static isBasic(e){let t="string"==typeof e?rg(e):e;return"function"==typeof t&&!rb.prototype.isPrototypeOf(t.prototype)}static registerPlugin(e,t){if("string"!=typeof e)throw Error(`Illegal plugin name, "${e}", must be a string, was ${typeof e}.`);if(rm(e))N.warn(`A plugin named "${e}" already exists. You may want to avoid re-registering plugins!`);else if(rh.prototype.hasOwnProperty(e))throw Error(`Illegal plugin name, "${e}", cannot share a name with an existing player method!`);if("function"!=typeof t)throw Error(`Illegal plugin for "${e}", must be a function, was ${typeof t}.`);return rp[e]=t,e!==ru&&(rb.isBasic(t)?rh.prototype[e]=ry(e,t):rh.prototype[e]=rv(e,t)),t}static deregisterPlugin(e){if(e===ru)throw Error("Cannot de-register base plugin.");rm(e)&&(delete rp[e],delete rh.prototype[e])}static getPlugins(e=Object.keys(rp)){let t;return e.forEach(e=>{let i=rg(e);i&&((t=t||{})[e]=i)}),t}static getPluginVersion(e){let t=rg(e);return t&&t.VERSION||""}}function rT(e,t,i,s){var r;let n;return r=`${t} is deprecated and will be removed in ${e}.0; please use ${i} instead.`,n=!1,function(...e){return n||N.warn(r),n=!0,s.apply(this,e)}}rb.getPlugin=rg,rb.BASE_PLUGIN_NAME=ru,rb.registerPlugin(ru,rb),rh.prototype.usingPlugin=function(e){return!!this[rc]&&!0===this[rc][e]},rh.prototype.hasPlugin=function(e){return!!rm(e)};let rS=e=>0===e.indexOf("#")?e.slice(1):e;function rk(e,t,i){let s=rk.getPlayer(e);if(s)return t&&N.warn(`Player "${e}" is already initialised. Options will not be applied.`),i&&s.ready(i),s;let r="string"==typeof e?eG("#"+rS(e)):e;if(!eT(r))throw TypeError("The element or ID supplied is not valid. (videojs)");let n="getRootNode"in r&&r.getRootNode()instanceof d().ShadowRoot?r.getRootNode():r.ownerDocument.body;return r.ownerDocument.defaultView&&n.contains(r)||N.warn("The element supplied is not included in the DOM"),!0===(t=t||{}).restoreEl&&(t.restoreEl=(r.parentNode&&r.parentNode.hasAttribute&&r.parentNode.hasAttribute("data-vjs-player")?r.parentNode:r).cloneNode(!0)),L("beforesetup").forEach(e=>{let i=e(r,W(t));if(!V(i)||Array.isArray(i)){N.error("please return an object in beforesetup hooks");return}t=W(t,i)}),s=new(tP.getComponent("Player"))(r,t,i),L("setup").forEach(e=>e(s)),s}if(rk.hooks_=A,rk.hooks=L,rk.hook=function(e,t){L(e,t)},rk.hookOnce=function(e,t){L(e,[].concat(t).map(t=>{let i=(...s)=>(D(e,i),t(...s));return i}))},rk.removeHook=D,!0!==d().VIDEOJS_NO_DYNAMIC_STYLE&&eb()){let e=eG(".vjs-styles-defaults");if(!e){e=e2("vjs-styles-defaults");let t=eG("head");t&&t.insertBefore(e,t.firstChild),e4(e,` + .video-js { + width: 300px; + height: 150px; + } + + .vjs-fluid:not(.vjs-audio-only-mode) { + padding-top: 56.25% + } + `)}}e0(1,rk),rk.VERSION=P,rk.options=rh.prototype.options_,rk.getPlayers=()=>rh.players,rk.getPlayer=e=>{let t;let i=rh.players;if("string"==typeof e){let s=rS(e),r=i[s];if(r)return r;t=eG("#"+s)}else t=e;if(eT(t)){let{player:e,playerId:s}=t;if(e||i[s])return e||i[s]}},rk.getAllPlayers=()=>Object.keys(rh.players).map(e=>rh.players[e]).filter(Boolean),rk.players=rh.players,rk.getComponent=tP.getComponent,rk.registerComponent=(e,t)=>(iu.isTech(t)&&N.warn(`The ${e} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`),tP.registerComponent.call(tP,e,t)),rk.getTech=iu.getTech,rk.registerTech=iu.registerTech,rk.use=function(e,t){ic[e]=ic[e]||[],ic[e].push(t)},Object.defineProperty(rk,"middleware",{value:{},writeable:!1,enumerable:!0}),Object.defineProperty(rk.middleware,"TERMINATOR",{value:im,writeable:!1,enumerable:!0}),rk.browser=ey,rk.obj=Q,rk.mergeOptions=rT(9,"videojs.mergeOptions","videojs.obj.merge",W),rk.defineLazyProperty=rT(9,"videojs.defineLazyProperty","videojs.obj.defineLazyProperty",K),rk.bind=rT(9,"videojs.bind","native Function.prototype.bind",to),rk.registerPlugin=rb.registerPlugin,rk.deregisterPlugin=rb.deregisterPlugin,rk.plugin=(e,t)=>(N.warn("videojs.plugin() is deprecated; use videojs.registerPlugin() instead"),rb.registerPlugin(e,t)),rk.getPlugins=rb.getPlugins,rk.getPlugin=rb.getPlugin,rk.getPluginVersion=rb.getPluginVersion,rk.addLanguage=function(e,t){return e=(""+e).toLowerCase(),rk.options.languages=W(rk.options.languages,{[e]:t}),rk.options.languages[e]},rk.log=N,rk.createLogger=j,rk.time=tN,rk.createTimeRange=rT(9,"videojs.createTimeRange","videojs.time.createTimeRanges",tD),rk.createTimeRanges=rT(9,"videojs.createTimeRanges","videojs.time.createTimeRanges",tD),rk.formatTime=rT(9,"videojs.formatTime","videojs.time.formatTime",tB),rk.setFormatTime=rT(9,"videojs.setFormatTime","videojs.time.setFormatTime",tU),rk.resetFormatTime=rT(9,"videojs.resetFormatTime","videojs.time.resetFormatTime",tR),rk.parseUrl=rT(9,"videojs.parseUrl","videojs.url.parseUrl",t3),rk.isCrossOrigin=rT(9,"videojs.isCrossOrigin","videojs.url.isCrossOrigin",t9),rk.EventTarget=tu,rk.any=tn,rk.on=tt,rk.one=tr,rk.off=ti,rk.trigger=ts,rk.xhr=m(),rk.TextTrack=is,rk.AudioTrack=ir,rk.VideoTrack=ia,["isEl","isTextNode","createEl","hasClass","addClass","removeClass","toggleClass","setAttributes","getAttributes","emptyEl","appendContent","insertContent"].forEach(e=>{rk[e]=function(){return N.warn(`videojs.${e}() is deprecated; use videojs.dom.${e}() instead`),eX[e].apply(null,arguments)}}),rk.computedStyle=rT(9,"videojs.computedStyle","videojs.dom.computedStyle",eQ),rk.dom=eX,rk.fn=td,rk.num=iJ,rk.str=tI,rk.url=ie,rk.Error={NetworkBadStatus:"networkbadstatus",NetworkRequestFailed:"networkrequestfailed",NetworkRequestAborted:"networkrequestaborted",NetworkRequestTimeout:"networkrequesttimeout",NetworkBodyParserFailed:"networkbodyparserfailed",StreamingHlsPlaylistParserError:"streaminghlsplaylistparsererror",StreamingDashManifestParserError:"streamingdashmanifestparsererror",StreamingContentSteeringParserError:"streamingcontentsteeringparsererror",StreamingVttParserError:"streamingvttparsererror",StreamingFailedToSelectNextSegment:"streamingfailedtoselectnextsegment",StreamingFailedToDecryptSegment:"streamingfailedtodecryptsegment",StreamingFailedToTransmuxSegment:"streamingfailedtotransmuxsegment",StreamingFailedToAppendSegment:"streamingfailedtoappendsegment",StreamingCodecsChangeError:"streamingcodecschangeerror"};class rC{constructor(e){let t=this;return t.id=e.id,t.label=t.id,t.width=e.width,t.height=e.height,t.bitrate=e.bandwidth,t.frameRate=e.frameRate,t.enabled_=e.enabled,Object.defineProperty(t,"enabled",{get:()=>t.enabled_(),set(e){t.enabled_(e)}}),t}}class rw extends rk.EventTarget{constructor(){super();let e=this;return e.levels_=[],e.selectedIndex_=-1,Object.defineProperty(e,"selectedIndex",{get:()=>e.selectedIndex_}),Object.defineProperty(e,"length",{get:()=>e.levels_.length}),e[Symbol.iterator]=()=>e.levels_.values(),e}addQualityLevel(e){let t=this.getQualityLevelById(e.id);if(t)return t;let i=this.levels_.length;return t=new rC(e),""+i in this||Object.defineProperty(this,i,{get(){return this.levels_[i]}}),this.levels_.push(t),this.trigger({qualityLevel:t,type:"addqualitylevel"}),t}removeQualityLevel(e){let t=null;for(let i=0,s=this.length;ii&&this.selectedIndex_--;break}return t&&this.trigger({qualityLevel:e,type:"removequalitylevel"}),t}getQualityLevelById(e){for(let t=0,i=this.length;ts,e.qualityLevels.VERSION=rE,s},rI=function(e){return rx(this,rk.obj.merge({},e))};rk.registerPlugin("qualityLevels",rI),rI.VERSION=rE;let rP=y.A,rA=(e,t)=>t&&t.responseURL&&e!==t.responseURL?t.responseURL:e,rL=e=>rk.log.debug?rk.log.debug.bind(rk,"VHS:",`${e} >`):function(){};function rD(...e){let t=rk.obj||rk;return(t.merge||t.mergeOptions).apply(t,e)}function rO(...e){let t=rk.time||rk;return(t.createTimeRanges||t.createTimeRanges).apply(t,e)}let rM=1/30,rU=1/30*3,rR=function(e,t){let i;let s=[];if(e&&e.length)for(i=0;i=t})},rN=function(e,t){return rR(e,function(e){return e-rM>=t})},rj=function(e){if(e.length<2)return rO();let t=[];for(let i=1;i{let t=[];if(!e||!e.length)return"";for(let i=0;i "+e.end(i));return t.join(", ")},rq=e=>{let t=[];for(let i=0;in)){if(t>r&&t<=n){i+=n-t;continue}i+=n-r}}return i},rW=(e,t)=>{if(!t.preload)return t.duration;let i=0;return(t.parts||[]).forEach(function(e){i+=e.duration}),(t.preloadHints||[]).forEach(function(t){"PART"===t.type&&(i+=e.partTargetDuration)}),i},rG=e=>(e.segments||[]).reduce((e,t,i)=>(t.parts?t.parts.forEach(function(s,r){e.push({duration:s.duration,segmentIndex:i,partIndex:r,part:s,segment:t})}):e.push({duration:t.duration,segmentIndex:i,partIndex:null,segment:t,part:null}),e),[]),rK=e=>{let t=e.segments&&e.segments.length&&e.segments[e.segments.length-1];return t&&t.parts||[]},rQ=({preloadSegment:e})=>{if(!e)return;let{parts:t,preloadHints:i}=e,s=(i||[]).reduce((e,t)=>e+ +("PART"===t.type),0);return s+(t&&t.length?t.length:0)},rY=(e,t)=>{if(t.endList)return 0;if(e&&e.suggestedPresentationDelay)return e.suggestedPresentationDelay;let i=rK(t).length>0;return i&&t.serverControl&&t.serverControl.partHoldBack?t.serverControl.partHoldBack:i&&t.partTargetDuration?3*t.partTargetDuration:t.serverControl&&t.serverControl.holdBack?t.serverControl.holdBack:t.targetDuration?3*t.targetDuration:0},rX=function(e,t){let i=0,s=t-e.mediaSequence,r=e.segments[s];if(r){if(void 0!==r.start)return{result:r.start,precise:!0};if(void 0!==r.end)return{result:r.end-r.duration,precise:!0}}for(;s--;){if(void 0!==(r=e.segments[s]).end)return{result:i+r.end,precise:!0};if(i+=rW(e,r),void 0!==r.start)return{result:i+r.start,precise:!0}}return{result:i,precise:!1}},rJ=function(e,t){let i,s=0,r=t-e.mediaSequence;for(;rs&&([i,s]=[s,i]),i<0){for(let t=i;tDate.now()},r8=function(e){return e.excludeUntil&&e.excludeUntil===1/0},r5=function(e){let t=r4(e);return!e.disabled&&!t},r3=function(e,t){return t.attributes&&t.attributes[e]},r6=(e,t)=>{if(1===e.playlists.length)return!0;let i=t.attributes.BANDWIDTH||Number.MAX_VALUE;return 0===e.playlists.filter(e=>!!r5(e)&&(e.attributes.BANDWIDTH||0)(!!e||!!t)&&(!!e||!t)&&(!e||!!t)&&(e===t||!!e.id&&!!t.id&&e.id===t.id||!!e.resolvedUri&&!!t.resolvedUri&&e.resolvedUri===t.resolvedUri||!!e.uri&&!!t.uri&&e.uri===t.uri),r9=function(e,t){let i=e&&e.mediaGroups&&e.mediaGroups.AUDIO||{},s=!1;for(let e in i){for(let r in i[e])if(s=t(i[e][r]))break;if(s)break}return!!s},ne=e=>{if(!e||!e.playlists||!e.playlists.length)return r9(e,e=>e.playlists&&e.playlists.length||e.uri);for(let t=0;t(0,b.fz)(e))||r9(e,e=>r7(i,e))))return!1}return!0};var nt={liveEdgeDelay:rY,duration:r0,seekable:function(e,t,i){let s=t||0,r=r2(e,t,!0,i);return null===r?rO():(r0)for(let t=l-1;t>=0;t--){let i=o[t];if(a+=i.duration,n){if(a<0)continue}else if(a+rM<=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:r-r1({defaultDuration:e.targetDuration,durationList:o,startIndex:l,endIndex:t})}}return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:t}}if(l<0){for(let i=l;i<0;i++)if((a-=e.targetDuration)<0)return{partIndex:o[0]&&o[0].partIndex||null,segmentIndex:o[0]&&o[0].segmentIndex||0,startTime:t};l=0}for(let t=l;trM,h=0===a,d=s&&a+rM>=0;if(!h&&!d||t===o.length-1){if(n){if(a>0)continue}else if(a-rM>=0)continue;return{partIndex:i.partIndex,segmentIndex:i.segmentIndex,startTime:r+r1({defaultDuration:e.targetDuration,durationList:o,startIndex:l,endIndex:t})}}}return{segmentIndex:o[o.length-1].segmentIndex,partIndex:o[o.length-1].partIndex,startTime:t}},isEnabled:r5,isDisabled:function(e){return e.disabled},isExcluded:r4,isIncompatible:r8,playlistEnd:r2,isAes:function(e){for(let t=0;t`${e}-${t}`,nr=(e,t,i)=>`placeholder-uri-${e}-${t}-${i}`,nn=({onwarn:e,oninfo:t,manifestString:i,customTagParsers:s=[],customTagMappers:r=[],llhls:n})=>{let a=new v.iX;e&&a.on("warn",e),t&&a.on("info",t),s.forEach(e=>a.addParser(e)),r.forEach(e=>a.addTagMapper(e)),a.push(i),a.end();let o=a.manifest;if(!n&&(["preloadSegment","skip","serverControl","renditionReports","partInf","partTargetDuration"].forEach(function(e){o.hasOwnProperty(e)&&delete o[e]}),o.segments&&o.segments.forEach(function(e){["parts","preloadHints"].forEach(function(t){e.hasOwnProperty(t)&&delete e[t]})})),!o.targetDuration){let t=10;o.segments&&o.segments.length&&(t=o.segments.reduce((e,t)=>Math.max(e,t.duration),0)),e&&e({message:`manifest has no targetDuration defaulting to ${t}`}),o.targetDuration=t}let l=rK(o);if(l.length&&!o.partTargetDuration){let t=l.reduce((e,t)=>Math.max(e,t.duration),0);e&&(e({message:`manifest has no partTargetDuration defaulting to ${t}`}),ni.error("LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.")),o.partTargetDuration=t}return o},na=(e,t)=>{e.mediaGroups&&["AUDIO","SUBTITLES"].forEach(i=>{if(e.mediaGroups[i])for(let s in e.mediaGroups[i])for(let r in e.mediaGroups[i][s])t(e.mediaGroups[i][s][r],i,s,r)})},no=({playlist:e,uri:t,id:i})=>{e.id=i,e.playlistErrors_=0,t&&(e.uri=t),e.attributes=e.attributes||{}},nl=e=>{let t=e.playlists.length;for(;t--;){let i=e.playlists[t];no({playlist:i,id:ns(t,i.uri)}),i.resolvedUri=rP(e.uri,i.uri),e.playlists[i.id]=i,e.playlists[i.uri]=i,i.attributes.BANDWIDTH||ni.warn("Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.")}},nh=e=>{na(e,t=>{t.uri&&(t.resolvedUri=rP(e.uri,t.uri))})},nd=(e,t)=>{let i=ns(0,t),s={mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:d().location.href,resolvedUri:d().location.href,playlists:[{uri:t,id:i,resolvedUri:t,attributes:{}}]};return s.playlists[i]=s.playlists[0],s.playlists[t]=s.playlists[0],s},nu=(e,t,i=nr)=>{e.uri=t;for(let t=0;t{if(!t.playlists||!t.playlists.length){if(s&&"AUDIO"===r&&!t.uri)for(let t=0;t(e.set(t.id,t),e),new Map)}processDateRange(e){this.pendingDateRanges_.delete(e.id),this.processedDateRanges_.set(e.id,e)}getDateRangesToProcess(){if(null===this.offset_)return[];let e={},t=[];for(let i of(this.pendingDateRanges_.forEach((i,s)=>{if(!this.processedDateRanges_.has(s)){if(i.startTime=i.startDate.getTime()/1e3-this.offset_,i.processDateRange=()=>this.processDateRange(i),t.push(i),i.class){if(e[i.class]){let t=e[i.class].push(i);i.classListIndex=t-1}else e[i.class]=[i],i.classListIndex=0}}}),t)){let t=e[i.class]||[];i.endDate?i.endTime=i.endDate.getTime()/1e3-this.offset_:i.endOnNext&&t[i.classListIndex+1]?i.endTime=t[i.classListIndex+1].startTime:i.duration?i.endTime=i.startTime+i.duration:i.plannedDuration?i.endTime=i.startTime+i.plannedDuration:i.endTime=i.startTime}return t}trimProcessedDateRanges_(e){new Map(this.processedDateRanges_).forEach((t,i)=>{t.startDate.getTime(){let r=t.status<200||t.status>299,n=t.status>=400&&t.status<=499,a={uri:t.uri,requestType:e};if(i&&n)a.error=(0,_.A)({},i),a.errorType=rk.Error.NetworkRequestFailed;else if(t.aborted)a.errorType=rk.Error.NetworkRequestAborted;else if(t.timedout)a.erroType=rk.Error.NetworkRequestTimeout;else if(r&&!n||s){let e=s?rk.Error.NetworkBodyParserFailed:rk.Error.NetworkBadStatus;a.errorType=e,a.status=t.status,a.headers=t.headers}return a},{EventTarget:nm}=rk,ng=(e,t)=>{if(t.endList||!t.serverControl)return e;let i={};if(t.serverControl.canBlockReload){let{preloadSegment:e}=t,s=t.mediaSequence+t.segments.length;if(e){let r=e.parts||[],n=rQ(t)-1;n>-1&&n!==r.length-1&&(i._HLS_part=n),(n>-1||r.length)&&s--}i._HLS_msn=s}if(t.serverControl&&t.serverControl.canSkipUntil&&(i._HLS_skip=t.serverControl.canSkipDateranges?"v2":"YES"),Object.keys(i).length){let t=new(d()).URL(e);["_HLS_skip","_HLS_msn","_HLS_part"].forEach(function(e){i.hasOwnProperty(e)&&t.searchParams.set(e,i[e])}),e=t.toString()}return e},nf=(e,t)=>{if(!e)return t;let i=rD(e,t);if(e.preloadHints&&!t.preloadHints&&delete i.preloadHints,e.parts&&!t.parts)delete i.parts;else if(e.parts&&t.parts)for(let s=0;s{let s;let r=e.slice(),n=t.slice();i=i||0;let a=[];for(let e=0;e{!e.resolvedUri&&e.uri&&(e.resolvedUri=rP(t,e.uri)),e.key&&!e.key.resolvedUri&&(e.key.resolvedUri=rP(t,e.key.uri)),e.map&&!e.map.resolvedUri&&(e.map.resolvedUri=rP(t,e.map.uri)),e.map&&e.map.key&&!e.map.key.resolvedUri&&(e.map.key.resolvedUri=rP(t,e.map.key.uri)),e.parts&&e.parts.length&&e.parts.forEach(e=>{!e.resolvedUri&&(e.resolvedUri=rP(t,e.uri))}),e.preloadHints&&e.preloadHints.length&&e.preloadHints.forEach(e=>{!e.resolvedUri&&(e.resolvedUri=rP(t,e.uri))})},nv=function(e){let t=e.segments||[],i=e.preloadSegment;if(i&&i.parts&&i.parts.length){if(i.preloadHints){for(let e=0;ee===t||e.segments&&t.segments&&e.segments.length===t.segments.length&&e.endList===t.endList&&e.mediaSequence===t.mediaSequence&&e.preloadSegment===t.preloadSegment,nT=(e,t,i=nb)=>{let s=rD(e,{}),r=s.playlists[t.id];if(!r||i(r,t))return null;t.segments=nv(t);let n=rD(r,t);if(n.preloadSegment&&!t.preloadSegment&&delete n.preloadSegment,r.segments){if(t.skip){t.segments=t.segments||[];for(let e=0;e{ny(e,n.resolvedUri)});for(let e=0;e{if(e.playlists)for(let i=0;i{let i=e.segments||[],s=i[i.length-1],r=s&&s.parts&&s.parts[s.parts.length-1],n=r&&r.duration||s&&s.duration;return t&&n?1e3*n:500*(e.partTargetDuration||e.targetDuration||10)},nk=(e,t,i)=>{if(!e)return;let s=[];return e.forEach(e=>{if(!e.attributes)return;let{BANDWIDTH:t,RESOLUTION:i,CODECS:r}=e.attributes;s.push({id:e.id,bandwidth:t,resolution:i,codecs:r})}),{type:t,isLive:i,renditions:s}};class nC extends nm{constructor(e,t,i={}){if(super(),!e)throw Error("A non-empty playlist URL or object is required");this.logger_=rL("PlaylistLoader");let{withCredentials:s=!1}=i;this.src=e,this.vhs_=t,this.withCredentials=s,this.addDateRangesToTextTrack_=i.addDateRangesToTextTrack;let r=t.options_;this.customTagParsers=r&&r.customTagParsers||[],this.customTagMappers=r&&r.customTagMappers||[],this.llhls=r&&r.llhls,this.dateRangesStorage_=new nc,this.state="HAVE_NOTHING",this.handleMediaupdatetimeout_=this.handleMediaupdatetimeout_.bind(this),this.on("mediaupdatetimeout",this.handleMediaupdatetimeout_),this.on("loadedplaylist",this.handleLoadedPlaylist_.bind(this))}handleLoadedPlaylist_(){let e=this.media();if(!e)return;this.dateRangesStorage_.setOffset(e.segments),this.dateRangesStorage_.setPendingDateRanges(e.dateRanges);let t=this.dateRangesStorage_.getDateRangesToProcess();t.length&&this.addDateRangesToTextTrack_&&this.addDateRangesToTextTrack_(t)}handleMediaupdatetimeout_(){if("HAVE_METADATA"!==this.state)return;let e=this.media(),t=rP(this.main.uri,e.uri);this.llhls&&(t=ng(t,e)),this.state="HAVE_CURRENT_METADATA",this.request=this.vhs_.xhr({uri:t,withCredentials:this.withCredentials,requestType:"hls-playlist"},(e,t)=>{if(this.request){if(e)return this.playlistRequestError(this.request,this.media(),"HAVE_METADATA");this.haveMetadata({playlistString:this.request.responseText,url:this.media().uri,id:this.media().id})}})}playlistRequestError(e,t,i){let{uri:s,id:r}=t;this.request=null,i&&(this.state=i),this.error={playlist:this.main.playlists[r],status:e.status,message:`HLS playlist request error at URL: ${s}.`,responseText:e.responseText,code:e.status>=500?4:2,metadata:np({requestType:e.requestType,request:e,error:e.error})},this.trigger("error")}parseManifest_({url:e,manifestString:t}){try{return nn({onwarn:({message:t})=>this.logger_(`m3u8-parser warn for ${e}: ${t}`),oninfo:({message:t})=>this.logger_(`m3u8-parser info for ${e}: ${t}`),manifestString:t,customTagParsers:this.customTagParsers,customTagMappers:this.customTagMappers,llhls:this.llhls})}catch(e){this.error=e,this.error.metadata={errorType:rk.Error.StreamingHlsPlaylistParserError,error:e}}}haveMetadata({playlistString:e,playlistObject:t,url:i,id:s}){this.request=null,this.state="HAVE_METADATA";let r={playlistInfo:{type:"media",uri:i}};this.trigger({type:"playlistparsestart",metadata:r});let n=t||this.parseManifest_({url:i,manifestString:e});n.lastRequest=Date.now(),no({playlist:n,uri:i,id:s});let a=nT(this.main,n);this.targetDuration=n.partTargetDuration||n.targetDuration,this.pendingMedia_=null,a?(this.main=a,this.media_=this.main.playlists[s]):this.trigger("playlistunchanged"),this.updateMediaUpdateTimeout_(nS(this.media(),!!a)),r.parsedPlaylist=nk(this.main.playlists,r.playlistInfo.type,!this.media_.endList),this.trigger({type:"playlistparsecomplete",metadata:r}),this.trigger("loadedplaylist")}dispose(){this.trigger("dispose"),this.stopRequest(),d().clearTimeout(this.mediaUpdateTimeout),d().clearTimeout(this.finalRenditionTimeout),this.dateRangesStorage_=new nc,this.off()}stopRequest(){if(this.request){let e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e,t){if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw Error("Cannot switch media playlist from "+this.state);if("string"==typeof e){if(!this.main.playlists[e])throw Error("Unknown playlist URI: "+e);e=this.main.playlists[e]}if(d().clearTimeout(this.finalRenditionTimeout),t){let t=(e.partTargetDuration||e.targetDuration)/2*1e3||5e3;this.finalRenditionTimeout=d().setTimeout(this.media.bind(this,e,!1),t);return}let i=this.state,s=!this.media_||e.id!==this.media_.id,r=this.main.playlists[e.id];if(r&&r.endList||e.endList&&e.segments.length){this.request&&(this.request.onreadystatechange=null,this.request.abort(),this.request=null),this.state="HAVE_METADATA",this.media_=e,s&&(this.trigger("mediachanging"),"HAVE_MAIN_MANIFEST"===i?this.trigger("loadedmetadata"):this.trigger("mediachange"));return}if(this.updateMediaUpdateTimeout_(nS(e,!0)),!s)return;if(this.state="SWITCHING_MEDIA",this.request){if(e.resolvedUri===this.request.url)return;this.request.onreadystatechange=null,this.request.abort(),this.request=null}this.media_&&this.trigger("mediachanging"),this.pendingMedia_=e;let n={playlistInfo:{type:"media",uri:e.uri}};this.trigger({type:"playlistrequeststart",metadata:n}),this.request=this.vhs_.xhr({uri:e.resolvedUri,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,s)=>{if(this.request){if(e.lastRequest=Date.now(),e.resolvedUri=rA(e.resolvedUri,s),t)return this.playlistRequestError(this.request,e,i);this.trigger({type:"playlistrequestcomplete",metadata:n}),this.haveMetadata({playlistString:s.responseText,url:e.uri,id:e.id}),"HAVE_MAIN_MANIFEST"===i?this.trigger("loadedmetadata"):this.trigger("mediachange")}})}pause(){this.mediaUpdateTimeout&&(d().clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.stopRequest(),"HAVE_NOTHING"===this.state&&(this.started=!1),"SWITCHING_MEDIA"===this.state?this.media_?this.state="HAVE_METADATA":this.state="HAVE_MAIN_MANIFEST":"HAVE_CURRENT_METADATA"===this.state&&(this.state="HAVE_METADATA")}load(e){this.mediaUpdateTimeout&&(d().clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null);let t=this.media();if(e){let e=t?(t.partTargetDuration||t.targetDuration)/2*1e3:5e3;this.mediaUpdateTimeout=d().setTimeout(()=>{this.mediaUpdateTimeout=null,this.load()},e);return}if(!this.started){this.start();return}t&&!t.endList?this.trigger("mediaupdatetimeout"):this.trigger("loadedplaylist")}updateMediaUpdateTimeout_(e){this.mediaUpdateTimeout&&(d().clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null),this.media()&&!this.media().endList&&(this.mediaUpdateTimeout=d().setTimeout(()=>{this.mediaUpdateTimeout=null,this.trigger("mediaupdatetimeout"),this.updateMediaUpdateTimeout_(e)},e))}start(){if(this.started=!0,"object"==typeof this.src){this.src.uri||(this.src.uri=d().location.href),this.src.resolvedUri=this.src.uri,setTimeout(()=>{this.setupInitialPlaylist(this.src)},0);return}let e={playlistInfo:{type:"multivariant",uri:this.src}};this.trigger({type:"playlistrequeststart",metadata:e}),this.request=this.vhs_.xhr({uri:this.src,withCredentials:this.withCredentials,requestType:"hls-playlist"},(t,i)=>{if(!this.request)return;if(this.request=null,t)return this.error={status:i.status,message:`HLS playlist request error at URL: ${this.src}.`,responseText:i.responseText,code:2,metadata:np({requestType:i.requestType,request:i,error:t})},"HAVE_NOTHING"===this.state&&(this.started=!1),this.trigger("error");this.trigger({type:"playlistrequestcomplete",metadata:e}),this.src=rA(this.src,i),this.trigger({type:"playlistparsestart",metadata:e});let s=this.parseManifest_({manifestString:i.responseText,url:this.src});e.parsedPlaylist=nk(s.playlists,e.playlistInfo.type,!1),this.trigger({type:"playlistparsecomplete",metadata:e}),this.setupInitialPlaylist(s)})}srcUri(){return"string"==typeof this.src?this.src:this.src.uri}setupInitialPlaylist(e){if(this.state="HAVE_MAIN_MANIFEST",e.playlists){this.main=e,nu(this.main,this.srcUri()),e.playlists.forEach(e=>{e.segments=nv(e),e.segments.forEach(t=>{ny(t,e.resolvedUri)})}),this.trigger("loadedplaylist"),this.request||this.media(this.main.playlists[0]);return}let t=this.srcUri()||d().location.href;this.main=nd(e,t),this.haveMetadata({playlistObject:e,url:t,id:this.main.playlists[0].id}),this.trigger("loadedmetadata")}updateOrDeleteClone(e,t){let i=this.main,s=e.ID,r=i.playlists.length;for(;r--;){let n=i.playlists[r];if(n.attributes["PATHWAY-ID"]===s){let a=n.resolvedUri,o=n.id;if(t){let t=this.createCloneURI_(n.resolvedUri,e),a=ns(s,t),o=this.createCloneAttributes_(s,n.attributes),l=this.createClonePlaylist_(n,a,e,o);i.playlists[r]=l,i.playlists[a]=l,i.playlists[t]=l}else i.playlists.splice(r,1);delete i.playlists[o],delete i.playlists[a]}}this.updateOrDeleteCloneMedia(e,t)}updateOrDeleteCloneMedia(e,t){let i=this.main,s=e.ID;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{if(i.mediaGroups[e]&&i.mediaGroups[e][s]){for(let t in i.mediaGroups[e])if(t===s){for(let s in i.mediaGroups[e][t])i.mediaGroups[e][t][s].playlists.forEach((e,t)=>{let s=i.playlists[e.id],r=s.id,n=s.resolvedUri;delete i.playlists[r],delete i.playlists[n]});delete i.mediaGroups[e][t]}}}),t&&this.createClonedMediaGroups_(e)}addClonePathway(e,t={}){let i=this.main,s=i.playlists.length,r=this.createCloneURI_(t.resolvedUri,e),n=ns(e.ID,r),a=this.createCloneAttributes_(e.ID,t.attributes),o=this.createClonePlaylist_(t,n,e,a);i.playlists[s]=o,i.playlists[n]=o,i.playlists[r]=o,this.createClonedMediaGroups_(e)}createClonedMediaGroups_(e){let t=e.ID,i=e["BASE-ID"],s=this.main;["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(r=>{if(s.mediaGroups[r]&&!s.mediaGroups[r][t]){for(let n in s.mediaGroups[r])if(n===i)for(let i in s.mediaGroups[r][t]={},s.mediaGroups[r][n]){let a=s.mediaGroups[r][n][i];s.mediaGroups[r][t][i]=(0,_.A)({},a);let o=s.mediaGroups[r][t][i],l=this.createCloneURI_(a.resolvedUri,e);o.resolvedUri=l,o.uri=l,o.playlists=[],a.playlists.forEach((n,a)=>{let l=s.playlists[n.id],h=nr(r,t,i),d=ns(t,h);if(l&&!s.playlists[d]){let t=this.createClonePlaylist_(l,d,e),i=t.resolvedUri;s.playlists[d]=t,s.playlists[i]=t}o.playlists[a]=this.createClonePlaylist_(n,d,e)})}}})}createClonePlaylist_(e,t,i,s){let r=this.createCloneURI_(e.resolvedUri,i),n={resolvedUri:r,uri:r,id:t};return e.segments&&(n.segments=[]),s&&(n.attributes=s),rD(e,n)}createCloneURI_(e,t){let i=new URL(e);i.hostname=t["URI-REPLACEMENT"].HOST;let s=t["URI-REPLACEMENT"].PARAMS;for(let e of Object.keys(s))i.searchParams.set(e,s[e]);return i.href}createCloneAttributes_(e,t){let i={"PATHWAY-ID":e};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(s=>{t[s]&&(i[s]=e)}),i}getKeyIdSet(e){if(e.contentProtection){let t=new Set;for(let i in e.contentProtection){let s=e.contentProtection[i].attributes.keyId;s&&t.add(s.toLowerCase())}return t}}}let nw=function(e,t,i,s){let r="arraybuffer"===e.responseType?e.response:e.responseText;t||!r||(e.responseTime=Date.now(),e.roundTripTime=e.responseTime-e.requestTime,e.bytesReceived=r.byteLength||r.length,e.bandwidth||(e.bandwidth=Math.floor(e.bytesReceived/e.roundTripTime*8e3))),i.headers&&(e.responseHeaders=i.headers),t&&"ETIMEDOUT"===t.code&&(e.timedout=!0),t||e.aborted||200===i.statusCode||206===i.statusCode||0===i.statusCode||(t=Error("XHR Failed with a response of: "+(e&&(r||e.responseText)))),s(t,e)},nE=(e,t)=>{if(!e||!e.size)return;let i=t;return e.forEach(e=>{i=e(i)}),i},nx=(e,t,i,s)=>{e&&e.size&&e.forEach(e=>{e(t,i,s)})},nI=function(){let e=function e(t,i){t=rD({timeout:45e3},t);let s=e.beforeRequest||rk.Vhs.xhr.beforeRequest,r=e._requestCallbackSet||rk.Vhs.xhr._requestCallbackSet||new Set,n=e._responseCallbackSet||rk.Vhs.xhr._responseCallbackSet;s&&"function"==typeof s&&(rk.log.warn("beforeRequest is deprecated, use onRequest instead."),r.add(s));let a=!0===rk.Vhs.xhr.original?rk.xhr:rk.Vhs.xhr,o=nE(r,t);r.delete(s);let l=a(o||t,function(e,t){return nx(n,l,e,t),nw(l,e,t,i)}),h=l.abort;return l.abort=function(){return l.aborted=!0,h.apply(l,arguments)},l.uri=t.uri,l.requestType=t.requestType,l.requestTime=Date.now(),l};return e.original=!0,e},nP=function(e){let t;return"bytes="+e.offset+"-"+("bigint"==typeof e.offset||"bigint"==typeof e.length?d().BigInt(e.offset)+d().BigInt(e.length)-d().BigInt(1):e.offset+e.length-1)},nA=function(e){let t={};return e.byterange&&(t.Range=nP(e.byterange)),t},nL=function(e,t){let i=e.toString(16);return"00".substring(0,2-i.length)+i+(t%2?" ":"")},nD=function(e){return e>=32&&e<126?String.fromCharCode(e):"."},nO=function(e){let t={};return Object.keys(e).forEach(i=>{let s=e[i];(0,S.hc)(s)?t[i]={bytes:s.buffer,byteOffset:s.byteOffset,byteLength:s.byteLength}:t[i]=s}),t},nM=function(e){let t=e.byterange||{length:1/0,offset:0};return[t.length,t.offset,e.resolvedUri].join(",")},nU=function(e){return e.resolvedUri},nR=e=>{let t=Array.prototype.slice.call(e),i="";for(let e=0;enR(e),textRanges:e=>{let t,i="";for(t=0;t{if(!t.dateTimeObject)return null;let i=t.videoTimingInfo.transmuxerPrependedSeconds,s=t.videoTimingInfo.transmuxedPresentationStart;return new Date(t.dateTimeObject.getTime()+1e3*(e-(s+i)))},nj=e=>e.transmuxedPresentationEnd-e.transmuxedPresentationStart-e.transmuxerPrependedSeconds,nF=(e,t)=>{let i;try{i=new Date(e)}catch(e){return null}if(!t||!t.segments||0===t.segments.length)return null;let s=t.segments[0];if(inew Date(n.getTime()+1e3*a)?null:(i>new Date(n)&&(s=r),{segment:s,estimatedStart:s.videoTimingInfo?s.videoTimingInfo.transmuxedPresentationStart:nt.duration(t,t.mediaSequence+t.segments.indexOf(s)),type:s.videoTimingInfo?"accurate":"estimate"})},n$=(e,t)=>{let i;if(!t||!t.segments||0===t.segments.length)return null;let s=0;for(let r=0;rs){if(e>s+.25*r.duration)return null;i=r}return{segment:i,estimatedStart:i.videoTimingInfo?i.videoTimingInfo.transmuxedPresentationStart:s-i.duration,type:i.videoTimingInfo?"accurate":"estimate"}},nq=(e,t)=>{let i,s;try{i=new Date(e),s=new Date(t)}catch(e){}let r=i.getTime();return(s.getTime()-r)/1e3},nH=e=>{if(!e.segments||0===e.segments.length)return!1;for(let t=0;t{if(!i)throw Error("getProgramTime: callback must be provided");if(!e||void 0===t)return i({message:"getProgramTime: playlist and time must be provided"});let s=n$(t,e);if(!s)return i({message:"valid programTime was not found"});if("estimate"===s.type)return i({message:"Accurate programTime could not be determined. Please seek to e.seekTime and try again",seekTime:s.estimatedStart});let r={mediaSeconds:t},n=nN(t,s.segment);return n&&(r.programDateTime=n.toISOString()),i(null,r)},nz=({programTime:e,playlist:t,retryCount:i=2,seekTo:s,pauseAfterSeek:r=!0,tech:n,callback:a})=>{if(!a)throw Error("seekToProgramTime: callback must be provided");if(void 0===e||!t||!s)return a({message:"seekToProgramTime: programTime, seekTo and playlist must be provided"});if(!t.endList&&!n.hasStarted_)return a({message:"player must be playing a live stream to start buffering"});if(!nH(t))return a({message:"programDateTime tags must be provided in the manifest "+t.resolvedUri});let o=nF(e,t);if(!o)return a({message:`${e} was not found in the stream`});let l=o.segment,h=nq(l.dateTimeObject,e);if("estimate"===o.type)return 0===i?a({message:`${e} is not buffered yet. Try again`}):(s(o.estimatedStart+h),void n.one("seeked",()=>{nz({programTime:e,playlist:t,retryCount:i-1,seekTo:s,pauseAfterSeek:r,tech:n,callback:a})}));let d=l.start+h;n.one("seeked",()=>a(null,n.currentTime())),r&&n.pause(),s(d)},nW=(e,t)=>{if(4===e.readyState)return t()},nG=(e,t,i,s)=>{let r,n=[],a=!1,o=function(e,t,s,r){return t.abort(),a=!0,i(e,t,s,r)},l=function(e,t){if(a)return;if(e)return e.metadata=np({requestType:s,request:t,error:e}),o(e,t,"",n);let i=t.responseText.substring(n&&n.byteLength||0,t.responseText.length);if(n=(0,S.Bu)(n,(0,S.Af)(i,!0)),r=r||(0,E.A)(n),n.length<10||r&&n.lengtho(e,t,"",n));let l=(0,x.ne)(n);return"ts"===l&&n.length<188||!l&&n.length<376?nW(t,()=>o(e,t,"",n)):o(null,t,l,n)},h=t({uri:e,beforeSend(e){e.overrideMimeType("text/plain; charset=x-user-defined"),e.addEventListener("progress",function({total:t,loaded:i}){return nw(e,null,{statusCode:e.status},l)})}},function(e,t){return nw(h,e,t,l)});return h},{EventTarget:nK}=rk,nQ=function(e,t){if(!nb(e,t)||e.sidx&&t.sidx&&(e.sidx.offset!==t.sidx.offset||e.sidx.length!==t.sidx.length)||!e.sidx&&t.sidx||e.sidx&&!t.sidx||e.segments&&!t.segments||!e.segments&&t.segments)return!1;if(!e.segments&&!t.segments)return!0;for(let i=0;i{let r=s.attributes.NAME||i;return`placeholder-uri-${e}-${t}-${r}`},nX=({mainXml:e,srcUrl:t,clientOffset:i,sidxMapping:s,previousManifest:r})=>{let n=(0,k.qg)(e,{manifestUri:t,clientOffset:i,sidxMapping:s,previousManifest:r});return nu(n,t,nY),n},nJ=(e,t)=>{na(e,(i,s,r,n)=>{t.mediaGroups[s][r]&&n in t.mediaGroups[s][r]||delete e.mediaGroups[s][r][n]})},nZ=(e,t,i)=>{let s=!0,r=rD(e,{duration:t.duration,minimumUpdatePeriod:t.minimumUpdatePeriod,timelineStarts:t.timelineStarts});for(let e=0;e{if(e.playlists&&e.playlists.length){let a=e.playlists[0].id,o=nT(r,e.playlists[0],nQ);o&&(n in(r=o).mediaGroups[t][i]||(r.mediaGroups[t][i][n]=e),r.mediaGroups[t][i][n].playlists[0]=r.playlists[a],s=!1)}}),nJ(r,t),t.minimumUpdatePeriod!==e.minimumUpdatePeriod&&(s=!1),s)?null:r},n0=(e,t)=>(!!(!e.map&&!t.map)||!!(e.map&&t.map&&e.map.byterange.offset===t.map.byterange.offset&&e.map.byterange.length===t.map.byterange.length))&&e.uri===t.uri&&e.byterange.offset===t.byterange.offset&&e.byterange.length===t.byterange.length,n1=(e,t)=>{let i={};for(let s in e){let r=e[s].sidx;if(r){let e=(0,k.Ze)(r);if(!t[e])break;n0(t[e].sidxInfo,r)&&(i[e]=t[e])}}return i},n2=(e,t)=>{let i=n1(e.playlists,t);return na(e,(e,s,r,n)=>{if(e.playlists&&e.playlists.length){let s=e.playlists;i=rD(i,n1(s,t))}}),i};class n4 extends nK{constructor(e,t,i={},s){super(),this.isPaused_=!0,this.mainPlaylistLoader_=s||this,s||(this.isMain_=!0);let{withCredentials:r=!1}=i;if(this.vhs_=t,this.withCredentials=r,this.addMetadataToTextTrack=i.addMetadataToTextTrack,!e)throw Error("A non-empty playlist URL or object is required");this.on("minimumUpdatePeriod",()=>{this.refreshXml_()}),this.on("mediaupdatetimeout",()=>{this.refreshMedia_(this.media().id)}),this.state="HAVE_NOTHING",this.loadedPlaylists_={},this.logger_=rL("DashPlaylistLoader"),this.isMain_?(this.mainPlaylistLoader_.srcUrl=e,this.mainPlaylistLoader_.sidxMapping_={}):this.childPlaylist_=e}get isPaused(){return this.isPaused_}requestErrored_(e,t,i){return!this.request||((this.request=null,e)?(this.error="object"!=typeof e||e instanceof Error?{status:t.status,message:"DASH request error at URL: "+t.uri,response:t.response,code:2,metadata:e.metadata}:e,i&&(this.state=i),this.trigger("error"),!0):void 0)}addSidxSegments_(e,t,i){let s=e.sidx&&(0,k.Ze)(e.sidx);if(!e.sidx||!s||this.mainPlaylistLoader_.sidxMapping_[s]){d().clearTimeout(this.mediaRequest_),this.mediaRequest_=d().setTimeout(()=>i(!1),0);return}let r=rA(e.sidx.resolvedUri),n=(r,n)=>{let a;if(this.requestErrored_(r,n,t))return;let o=this.mainPlaylistLoader_.sidxMapping_,{requestType:l}=n;try{a=w()((0,S.W_)(n.response).subarray(8))}catch(e){e.metadata=np({requestType:l,request:n,parseFailure:!0}),this.requestErrored_(e,n,t);return}return o[s]={sidxInfo:e.sidx,sidx:a},(0,k.Tt)(e,a,e.sidx.resolvedUri),i(!0)};this.request=nG(r,this.vhs_.xhr,(t,i,s,a)=>{if(t)return n(t,i);if(!s||"mp4"!==s)return n({status:i.status,message:`Unsupported ${s||"unknown"} container type for sidx segment at URL: ${r}`,response:"",playlist:e,internal:!0,playlistExclusionDuration:1/0,code:2},i);let{offset:o,length:l}=e.sidx.byterange;if(a.length>=l+o)return n(t,{response:a.subarray(o,o+l),status:i.status,uri:i.uri});this.request=this.vhs_.xhr({uri:r,responseType:"arraybuffer",requestType:"dash-sidx",headers:nA({byterange:e.sidx.byterange})},n)},"dash-sidx")}dispose(){this.isPaused_=!0,this.trigger("dispose"),this.stopRequest(),this.loadedPlaylists_={},d().clearTimeout(this.minimumUpdatePeriodTimeout_),d().clearTimeout(this.mediaRequest_),d().clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.mediaRequest_=null,this.minimumUpdatePeriodTimeout_=null,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.off()}hasPendingRequest(){return this.request||this.mediaRequest_}stopRequest(){if(this.request){let e=this.request;this.request=null,e.onreadystatechange=null,e.abort()}}media(e){if(!e)return this.media_;if("HAVE_NOTHING"===this.state)throw Error("Cannot switch media playlist from "+this.state);let t=this.state;if("string"==typeof e){if(!this.mainPlaylistLoader_.main.playlists[e])throw Error("Unknown playlist URI: "+e);e=this.mainPlaylistLoader_.main.playlists[e]}let i=!this.media_||e.id!==this.media_.id;if(i&&this.loadedPlaylists_[e.id]&&this.loadedPlaylists_[e.id].endList){this.state="HAVE_METADATA",this.media_=e,i&&(this.trigger("mediachanging"),this.trigger("mediachange"));return}i&&(this.media_&&this.trigger("mediachanging"),this.addSidxSegments_(e,t,i=>{this.haveMetadata({startingState:t,playlist:e})}))}haveMetadata({startingState:e,playlist:t}){this.state="HAVE_METADATA",this.loadedPlaylists_[t.id]=t,d().clearTimeout(this.mediaRequest_),this.mediaRequest_=null,this.refreshMedia_(t.id),"HAVE_MAIN_MANIFEST"===e?this.trigger("loadedmetadata"):this.trigger("mediachange")}pause(){this.isPaused_=!0,this.mainPlaylistLoader_.createMupOnMedia_&&(this.off("loadedmetadata",this.mainPlaylistLoader_.createMupOnMedia_),this.mainPlaylistLoader_.createMupOnMedia_=null),this.stopRequest(),d().clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null,this.isMain_&&(d().clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_),this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_=null),"HAVE_NOTHING"===this.state&&(this.started=!1)}load(e){this.isPaused_=!1,d().clearTimeout(this.mediaUpdateTimeout),this.mediaUpdateTimeout=null;let t=this.media();if(e){let e=t?t.targetDuration/2*1e3:5e3;this.mediaUpdateTimeout=d().setTimeout(()=>this.load(),e);return}if(!this.started){this.start();return}t&&!t.endList?(this.isMain_&&!this.minimumUpdatePeriodTimeout_&&(this.trigger("minimumUpdatePeriod"),this.updateMinimumUpdatePeriodTimeout_()),this.trigger("mediaupdatetimeout")):this.trigger("loadedplaylist")}start(){if(this.started=!0,!this.isMain_){d().clearTimeout(this.mediaRequest_),this.mediaRequest_=d().setTimeout(()=>this.haveMain_(),0);return}this.requestMain_((e,t)=>{this.haveMain_(),this.hasPendingRequest()||this.media_||this.media(this.mainPlaylistLoader_.main.playlists[0])})}requestMain_(e){let t={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestrequeststart",metadata:t}),this.request=this.vhs_.xhr({uri:this.mainPlaylistLoader_.srcUrl,withCredentials:this.withCredentials,requestType:"dash-manifest"},(i,s)=>{if(i){let{requestType:e}=s;i.metadata=np({requestType:e,request:s,error:i})}if(this.requestErrored_(i,s)){"HAVE_NOTHING"===this.state&&(this.started=!1);return}this.trigger({type:"manifestrequestcomplete",metadata:t});let r=s.responseText!==this.mainPlaylistLoader_.mainXml_;if(this.mainPlaylistLoader_.mainXml_=s.responseText,s.responseHeaders&&s.responseHeaders.date?this.mainLoaded_=Date.parse(s.responseHeaders.date):this.mainLoaded_=Date.now(),this.mainPlaylistLoader_.srcUrl=rA(this.mainPlaylistLoader_.srcUrl,s),r){this.handleMain_(),this.syncClientServerClock_(()=>e(s,r));return}return e(s,r)})}syncClientServerClock_(e){let t=(0,k.i6)(this.mainPlaylistLoader_.mainXml_);return null===t?(this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()):"DIRECT"===t.method?(this.mainPlaylistLoader_.clientOffset_=t.value-Date.now(),e()):void(this.request=this.vhs_.xhr({uri:rP(this.mainPlaylistLoader_.srcUrl,t.value),method:t.method,withCredentials:this.withCredentials,requestType:"dash-clock-sync"},(i,s)=>{let r;if(this.request){if(i){let{requestType:t}=s;return this.error.metadata=np({requestType:t,request:s,error:i}),this.mainPlaylistLoader_.clientOffset_=this.mainLoaded_-Date.now(),e()}r="HEAD"===t.method?s.responseHeaders&&s.responseHeaders.date?Date.parse(s.responseHeaders.date):this.mainLoaded_:Date.parse(s.responseText),this.mainPlaylistLoader_.clientOffset_=r-Date.now(),e()}}))}haveMain_(){this.state="HAVE_MAIN_MANIFEST",this.isMain_?this.trigger("loadedplaylist"):this.media_||this.media(this.childPlaylist_)}handleMain_(){let e;d().clearTimeout(this.mediaRequest_),this.mediaRequest_=null;let t=this.mainPlaylistLoader_.main,i={manifestInfo:{uri:this.mainPlaylistLoader_.srcUrl}};this.trigger({type:"manifestparsestart",metadata:i});try{e=nX({mainXml:this.mainPlaylistLoader_.mainXml_,srcUrl:this.mainPlaylistLoader_.srcUrl,clientOffset:this.mainPlaylistLoader_.clientOffset_,sidxMapping:this.mainPlaylistLoader_.sidxMapping_,previousManifest:t})}catch(e){this.error=e,this.error.metadata={errorType:rk.Error.StreamingDashManifestParserError,error:e},this.trigger("error")}t&&(e=nZ(t,e,this.mainPlaylistLoader_.sidxMapping_)),this.mainPlaylistLoader_.main=e||t;let s=this.mainPlaylistLoader_.main.locations&&this.mainPlaylistLoader_.main.locations[0];if(s&&s!==this.mainPlaylistLoader_.srcUrl&&(this.mainPlaylistLoader_.srcUrl=s),(!t||e&&e.minimumUpdatePeriod!==t.minimumUpdatePeriod)&&this.updateMinimumUpdatePeriodTimeout_(),this.addEventStreamToMetadataTrack_(e),e){let{duration:t,endList:s}=e,r=[];e.playlists.forEach(e=>{r.push({id:e.id,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS})}),i.parsedManifest={duration:t,isLive:!s,renditions:r},this.trigger({type:"manifestparsecomplete",metadata:i})}return!!e}updateMinimumUpdatePeriodTimeout_(){let e=this.mainPlaylistLoader_;e.createMupOnMedia_&&(e.off("loadedmetadata",e.createMupOnMedia_),e.createMupOnMedia_=null),e.minimumUpdatePeriodTimeout_&&(d().clearTimeout(e.minimumUpdatePeriodTimeout_),e.minimumUpdatePeriodTimeout_=null);let t=e.main&&e.main.minimumUpdatePeriod;if(0===t&&(e.media()?t=1e3*e.media().targetDuration:(e.createMupOnMedia_=e.updateMinimumUpdatePeriodTimeout_,e.one("loadedmetadata",e.createMupOnMedia_))),"number"!=typeof t||t<=0){t<0&&this.logger_(`found invalid minimumUpdatePeriod of ${t}, not setting a timeout`);return}this.createMUPTimeout_(t)}createMUPTimeout_(e){let t=this.mainPlaylistLoader_;t.minimumUpdatePeriodTimeout_=d().setTimeout(()=>{t.minimumUpdatePeriodTimeout_=null,t.trigger("minimumUpdatePeriod"),t.createMUPTimeout_(e)},e)}refreshXml_(){this.requestMain_((e,t)=>{t&&(this.media_&&(this.media_=this.mainPlaylistLoader_.main.playlists[this.media_.id]),this.mainPlaylistLoader_.sidxMapping_=n2(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.sidxMapping_),this.addSidxSegments_(this.media(),this.state,e=>{this.refreshMedia_(this.media().id)}))})}refreshMedia_(e){if(!e)throw Error("refreshMedia_ must take a media id");this.media_&&this.isMain_&&this.handleMain_();let t=this.mainPlaylistLoader_.main.playlists,i=!this.media_||this.media_!==t[e];if(i?this.media_=t[e]:this.trigger("playlistunchanged"),!this.mediaUpdateTimeout){let e=()=>{!this.media().endList&&(this.mediaUpdateTimeout=d().setTimeout(()=>{this.trigger("mediaupdatetimeout"),e()},nS(this.media(),!!i)))};e()}this.trigger("loadedplaylist")}addEventStreamToMetadataTrack_(e){if(e&&this.mainPlaylistLoader_.main.eventStream){let e=this.mainPlaylistLoader_.main.eventStream.map(e=>({cueTime:e.start,frames:[{data:e.messageData}]}));this.addMetadataToTextTrack("EventStream",e,this.mainPlaylistLoader_.main.duration)}}getKeyIdSet(e){if(e.contentProtection){let t=new Set;for(let i in e.contentProtection){let s=e.contentProtection[i].attributes["cenc:default_KID"];s&&t.add(s.replace(/-/g,"").toLowerCase())}return t}}}var n8={GOAL_BUFFER_LENGTH:30,MAX_GOAL_BUFFER_LENGTH:60,BACK_BUFFER_LENGTH:30,GOAL_BUFFER_LENGTH_RATE:1,INITIAL_BANDWIDTH:4194304,BANDWIDTH_VARIANCE:1.2,BUFFER_LOW_WATER_LINE:0,MAX_BUFFER_LOW_WATER_LINE:30,EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:16,BUFFER_LOW_WATER_LINE_RATE:1,BUFFER_HIGH_WATER_LINE:30};let n5=e=>{let t=new Uint8Array(new ArrayBuffer(e.length));for(let i=0;i-1)},this.trigger=function(t){var i,s,r,n;if(i=e[t]){if(2==arguments.length)for(s=0,r=i.length;s>>1,e.samplingfrequencyindex<<7|e.channelcount<<3,6,1,2]))},eL=function(){return eI(eY.ftyp,eX,eJ,eX,eZ)},eH=function(e){return eI(eY.hdlr,e0[e])},eD=function(e){return eI(eY.mdat,e)},eq=function(e){var t=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,e.duration>>>24&255,e.duration>>>16&255,e.duration>>>8&255,255&e.duration,85,196,0,0]);return e.samplerate&&(t[12]=e.samplerate>>>24&255,t[13]=e.samplerate>>>16&255,t[14]=e.samplerate>>>8&255,t[15]=255&e.samplerate),eI(eY.mdhd,t)},e$=function(e){return eI(eY.mdia,eq(e),eH(e.type),eM(e))},eO=function(e){return eI(eY.mfhd,new Uint8Array([0,0,0,0,(0xff000000&e)>>24,(0xff0000&e)>>16,(65280&e)>>8,255&e]))},eM=function(e){return eI(eY.minf,"video"===e.type?eI(eY.vmhd,e1):eI(eY.smhd,e2),eP(),ez(e))},eU=function(e,t){for(var i=[],s=t.length;s--;)i[s]=eG(t[s]);return eI.apply(null,[eY.moof,eO(e)].concat(i))},eR=function(e){for(var t=e.length,i=[];t--;)i[t]=ej(e[t]);return eI.apply(null,[eY.moov,eN(0xffffffff)].concat(i).concat(eB(e)))},eB=function(e){for(var t=e.length,i=[];t--;)i[t]=eK(e[t]);return eI.apply(null,[eY.mvex].concat(i))},eN=function(e){var t=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(0xff000000&e)>>24,(0xff0000&e)>>16,(65280&e)>>8,255&e,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]);return eI(eY.mvhd,t)},eV=function(e){var t,i,s=e.samples||[],r=new Uint8Array(4+s.length);for(i=0;i>>8),n.push(255&s[t].byteLength),n=n.concat(Array.prototype.slice.call(s[t]));for(t=0;t>>8),a.push(255&r[t].byteLength),a=a.concat(Array.prototype.slice.call(r[t]));if(i=[eY.avc1,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,(65280&e.width)>>8,255&e.width,(65280&e.height)>>8,255&e.height,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),eI(eY.avcC,new Uint8Array([1,e.profileIdc,e.profileCompatibility,e.levelIdc,255].concat([s.length],n,[r.length],a))),eI(eY.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],e.sarRatio){var o=e.sarRatio[0],l=e.sarRatio[1];i.push(eI(eY.pasp,new Uint8Array([(0xff000000&o)>>24,(0xff0000&o)>>16,(65280&o)>>8,255&o,(0xff000000&l)>>24,(0xff0000&l)>>16,(65280&l)>>8,255&l])))}return eI.apply(null,i)},eC=function(e){return eI(eY.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(65280&e.channelcount)>>8,255&e.channelcount,(65280&e.samplesize)>>8,255&e.samplesize,0,0,0,0,(65280&e.samplerate)>>8,255&e.samplerate,0,0]),eA(e))},eF=function(e){var t=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(0xff000000&e.id)>>24,(0xff0000&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,0,(0xff000000&e.duration)>>24,(0xff0000&e.duration)>>16,(65280&e.duration)>>8,255&e.duration,0,0,0,0,0,0,0,0,0,0,0,0,1,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,(65280&e.width)>>8,255&e.width,0,0,(65280&e.height)>>8,255&e.height,0,0]);return eI(eY.tkhd,t)},eG=function(e){var t,i,s,r,n,a;return(t=eI(eY.tfhd,new Uint8Array([0,0,0,58,(0xff000000&e.id)>>24,(0xff0000&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),n=Math.floor(e.baseMediaDecodeTime/p),a=Math.floor(e.baseMediaDecodeTime%p),i=eI(eY.tfdt,new Uint8Array([1,0,0,0,n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a])),"audio"===e.type)?(s=eQ(e,92),eI(eY.traf,t,i,s)):(r=eV(e),s=eQ(e,r.length+92),eI(eY.traf,t,i,s,r))},ej=function(e){return e.duration=e.duration||0xffffffff,eI(eY.trak,eF(e),e$(e))},eK=function(e){var t=new Uint8Array([0,0,0,0,(0xff000000&e.id)>>24,(0xff0000&e.id)>>16,(65280&e.id)>>8,255&e.id,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return"video"!==e.type&&(t[t.length-1]=0),eI(eY.trex,t)},ex=function(e,t){var i=0,s=0,r=0,n=0;return e.length&&(void 0!==e[0].duration&&(i=1),void 0!==e[0].size&&(s=2),void 0!==e[0].flags&&(r=4),void 0!==e[0].compositionTimeOffset&&(n=8)),[0,0,i|s|r|n,1,(0xff000000&e.length)>>>24,(0xff0000&e.length)>>>16,(65280&e.length)>>>8,255&e.length,(0xff000000&t)>>>24,(0xff0000&t)>>>16,(65280&t)>>>8,255&t]},eE=function(e,t){var i,s,r,n,a,o;for(t+=20+16*(n=e.samples||[]).length,(s=new Uint8Array((r=ex(n,t)).length+16*n.length)).set(r),i=r.length,o=0;o>>24,s[i++]=(0xff0000&a.duration)>>>16,s[i++]=(65280&a.duration)>>>8,s[i++]=255&a.duration,s[i++]=(0xff000000&a.size)>>>24,s[i++]=(0xff0000&a.size)>>>16,s[i++]=(65280&a.size)>>>8,s[i++]=255&a.size,s[i++]=a.flags.isLeading<<2|a.flags.dependsOn,s[i++]=a.flags.isDependedOn<<6|a.flags.hasRedundancy<<4|a.flags.paddingValue<<1|a.flags.isNonSyncSample,s[i++]=61440&a.flags.degradationPriority,s[i++]=15&a.flags.degradationPriority,s[i++]=(0xff000000&a.compositionTimeOffset)>>>24,s[i++]=(0xff0000&a.compositionTimeOffset)>>>16,s[i++]=(65280&a.compositionTimeOffset)>>>8,s[i++]=255&a.compositionTimeOffset;return eI(eY.trun,s)},ew=function(e,t){var i,s,r,n,a,o;for(t+=20+8*(n=e.samples||[]).length,(i=new Uint8Array((r=ex(n,t)).length+8*n.length)).set(r),s=r.length,o=0;o>>24,i[s++]=(0xff0000&a.duration)>>>16,i[s++]=(65280&a.duration)>>>8,i[s++]=255&a.duration,i[s++]=(0xff000000&a.size)>>>24,i[s++]=(0xff0000&a.size)>>>16,i[s++]=(65280&a.size)>>>8,i[s++]=255&a.size;return eI(eY.trun,i)},eQ=function(e,t){return"audio"===e.type?ew(e,t):eE(e,t)};var m=function(e,t){var i={size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}};return i.dataOffset=t,i.compositionTimeOffset=e.pts-e.dts,i.duration=e.duration,i.size=4*e.length,i.size+=e.byteLength,e.keyFrame&&(i.flags.dependsOn=2,i.flags.isNonSyncSample=0),i},g=[33,16,5,32,164,27],f=[33,65,108,84,1,2,4,8,168,2,4,8,17,191,252],_=function(e){for(var t=[];e--;)t.push(0);return t};e9=function(e){return 9e4*e},te=function(e,t){return e*t},tt=function(e){return e/9e4},ti=function(e,t){return e/t},ts=function(e,t){return e9(ti(e,t))},tr=function(e,t){return te(tt(e),t)},tn=function(e,t,i){return tt(i?e:e-t)};var y={ONE_SECOND_IN_TS:9e4,secondsToVideoTs:e9,videoTsToSeconds:tt,audioTsToVideoTs:ts,videoTsToAudioTs:tr,metadataTsToSeconds:tn},v=function(){if(!e7){var e;e7=Object.keys(e={96e3:[g,[227,64],_(154),[56]],88200:[g,[231],_(170),[56]],64e3:[g,[248,192],_(240),[56]],48e3:[g,[255,192],_(268),[55,148,128],_(54),[112]],44100:[g,[255,192],_(268),[55,163,128],_(84),[112]],32e3:[g,[255,192],_(268),[55,234],_(226),[112]],24e3:[g,[255,192],_(268),[55,255,128],_(268),[111,112],_(126),[224]],16e3:[g,[255,192],_(268),[55,255,128],_(268),[111,255],_(269),[223,108],_(195),[1,192]],12e3:[f,_(268),[3,127,248],_(268),[6,255,240],_(268),[13,255,224],_(268),[27,253,128],_(259),[56]],11025:[f,_(268),[3,127,248],_(268),[6,255,240],_(268),[13,255,224],_(268),[27,255,192],_(268),[55,175,128],_(108),[112]],8e3:[f,_(268),[3,121,16],_(47),[7]]}).reduce(function(t,i){return t[i]=new Uint8Array(e[i].reduce(function(e,t){return e.concat(t)},[])),t},{})}return e7},b=function(e){var t,i=0;for(t=0;t=this.virtualRowCount&&"function"==typeof this.beforeRowOverflow&&this.beforeRowOverflow(e),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},x.prototype.isEmpty=function(){return 0===this.rows.length||1===this.rows.length&&""===this.rows[0]},x.prototype.addText=function(e){this.rows[this.rowIdx]+=e},x.prototype.backspace=function(){if(!this.isEmpty()){var e=this.rows[this.rowIdx];this.rows[this.rowIdx]=e.substr(0,e.length-1)}};var I=function(e,t,i){this.serviceNum=e,this.text="",this.currentWindow=new x(-1),this.windows=[],this.stream=i,"string"==typeof t&&this.createTextDecoder(t)};I.prototype.init=function(e,t){this.startPts=e;for(var i=0;i<8;i++)this.windows[i]=new x(i),"function"==typeof t&&(this.windows[i].beforeRowOverflow=t)},I.prototype.setCurrentWindow=function(e){this.currentWindow=this.windows[e]},I.prototype.createTextDecoder=function(e){if("undefined"==typeof TextDecoder)this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(e)}catch(t){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+e+" encoding. "+t})}};var P=function(e){e=e||{},P.prototype.init.call(this);var t,i=this,s=e.captionServices||{},r={};Object.keys(s).forEach(e=>{t=s[e],/^SERVICE/.test(e)&&(r[e]=t.encoding)}),this.serviceEncodings=r,this.current708Packet=null,this.services={},this.push=function(e){3===e.type?i.new708Packet():null===i.current708Packet&&i.new708Packet(),i.add708Bytes(e)}};P.prototype=new d,P.prototype.new708Packet=function(){null!==this.current708Packet&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},P.prototype.add708Bytes=function(e){var t=e.ccData;this.current708Packet.ptsVals.push(e.pts),this.current708Packet.data.push(t>>>8),this.current708Packet.data.push(255&t)},P.prototype.push708Packet=function(){var e=this.current708Packet,t=e.data,i=null,s=null,r=0,n=t[r++];for(e.seq=n>>6,e.sizeCode=63&n;r>5,s=31&n,7===i&&s>0&&(i=n=t[r++]),this.pushServiceBlock(i,r,s),s>0&&(r+=s-1)},P.prototype.pushServiceBlock=function(e,t,i){var s,r=t,n=this.current708Packet.data,a=this.services[e];for(a||(a=this.initService(e,r));r("0"+(255&e).toString(16)).slice(-2)).join(""),16)):w(4096*!!n|l),d.pendingNewLine&&!d.isEmpty()&&d.newLine(this.getPts(e)),d.pendingNewLine=!1,d.addText(s),e},P.prototype.multiByteCharacter=function(e,t){var i=this.current708Packet.data,s=i[e+1],r=i[e+2];return E(s)&&E(r)&&(e=this.handleText(++e,t,{isMultiByte:!0})),e},P.prototype.setCurrentWindow=function(e,t){var i=this.current708Packet.data[e];return t.setCurrentWindow(7&i),e},P.prototype.defineWindow=function(e,t){var i=this.current708Packet.data,s=i[e],r=7&s;t.setCurrentWindow(r);var n=t.currentWindow;return s=i[++e],n.visible=(32&s)>>5,n.rowLock=(16&s)>>4,n.columnLock=(8&s)>>3,n.priority=7&s,s=i[++e],n.relativePositioning=(128&s)>>7,n.anchorVertical=127&s,s=i[++e],n.anchorHorizontal=s,s=i[++e],n.anchorPoint=(240&s)>>4,n.rowCount=15&s,s=i[++e],n.columnCount=63&s,s=i[++e],n.windowStyle=(56&s)>>3,n.penStyle=7&s,n.virtualRowCount=n.rowCount+1,e},P.prototype.setWindowAttributes=function(e,t){var i=this.current708Packet.data,s=i[e],r=t.currentWindow.winAttr;return s=i[++e],r.fillOpacity=(192&s)>>6,r.fillRed=(48&s)>>4,r.fillGreen=(12&s)>>2,r.fillBlue=3&s,s=i[++e],r.borderType=(192&s)>>6,r.borderRed=(48&s)>>4,r.borderGreen=(12&s)>>2,r.borderBlue=3&s,s=i[++e],r.borderType+=(128&s)>>5,r.wordWrap=(64&s)>>6,r.printDirection=(48&s)>>4,r.scrollDirection=(12&s)>>2,r.justify=3&s,s=i[++e],r.effectSpeed=(240&s)>>4,r.effectDirection=(12&s)>>2,r.displayEffect=3&s,e},P.prototype.flushDisplayed=function(e,t){for(var i=[],s=0;s<8;s++)t.windows[s].visible&&!t.windows[s].isEmpty()&&i.push(t.windows[s].getText());t.endPts=e,t.text=i.join("\n\n"),this.pushCaption(t),t.startPts=e},P.prototype.pushCaption=function(e){""!==e.text&&(this.trigger("data",{startPts:e.startPts,endPts:e.endPts,text:e.text,stream:"cc708_"+e.serviceNum}),e.text="",e.startPts=e.endPts)},P.prototype.displayWindows=function(e,t){var i=this.current708Packet.data[++e],s=this.getPts(e);this.flushDisplayed(s,t);for(var r=0;r<8;r++)i&1<>4,r.offset=(12&s)>>2,r.penSize=3&s,s=i[++e],r.italics=(128&s)>>7,r.underline=(64&s)>>6,r.edgeType=(56&s)>>3,r.fontStyle=7&s,e},P.prototype.setPenColor=function(e,t){var i=this.current708Packet.data,s=i[e],r=t.currentWindow.penColor;return s=i[++e],r.fgOpacity=(192&s)>>6,r.fgRed=(48&s)>>4,r.fgGreen=(12&s)>>2,r.fgBlue=3&s,s=i[++e],r.bgOpacity=(192&s)>>6,r.bgRed=(48&s)>>4,r.bgGreen=(12&s)>>2,r.bgBlue=3&s,s=i[++e],r.edgeRed=(48&s)>>4,r.edgeGreen=(12&s)>>2,r.edgeBlue=3&s,e},P.prototype.setPenLocation=function(e,t){var i=this.current708Packet.data,s=i[e],r=t.currentWindow.penLoc;return t.currentWindow.pendingNewLine=!0,s=i[++e],r.row=15&s,s=i[++e],r.column=63&s,e},P.prototype.reset=function(e,t){var i=this.getPts(e);return this.flushDisplayed(i,t),this.initService(t.serviceNum,e)};var A={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},L=function(e){return null===e?"":String.fromCharCode(e=A[e]||e)},D=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],O=function(){for(var e=[],t=15;t--;)e.push({text:"",indent:0,offset:0});return e},M=function(e,t){M.prototype.init.call(this),this.field_=e||0,this.dataChannel_=t||0,this.name_="CC"+((this.field_<<1|this.dataChannel_)+1),this.setConstants(),this.reset(),this.push=function(e){var t,i,s,r,n;if((t=32639&e.ccData)===this.lastControlCode_){this.lastControlCode_=null;return}if((61440&t)==4096?this.lastControlCode_=t:t!==this.PADDING_&&(this.lastControlCode_=null),s=t>>>8,r=255&t,t!==this.PADDING_){if(t===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(t===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(e.pts),this.flushDisplayed(e.pts),i=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=i,this.startPts_=e.pts;else if(t===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(e.pts);else if(t===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(e.pts);else if(t===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(e.pts);else if(t===this.CARRIAGE_RETURN_)this.clearFormatting(e.pts),this.flushDisplayed(e.pts),this.shiftRowsUp_(),this.startPts_=e.pts;else if(t===this.BACKSPACE_)"popOn"===this.mode_?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(t===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(e.pts),this.displayed_=O();else if(t===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=O();else if(t===this.RESUME_DIRECT_CAPTIONING_)"paintOn"!==this.mode_&&(this.flushDisplayed(e.pts),this.displayed_=O()),this.mode_="paintOn",this.startPts_=e.pts;else if(this.isSpecialCharacter(s,r))n=L((s=(3&s)<<8)|r),this[this.mode_](e.pts,n),this.column_++;else if(this.isExtCharacter(s,r))"popOn"===this.mode_?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),n=L((s=(3&s)<<8)|r),this[this.mode_](e.pts,n),this.column_++;else if(this.isMidRowCode(s,r))this.clearFormatting(e.pts),this[this.mode_](e.pts," "),this.column_++,(14&r)==14&&this.addFormatting(e.pts,["i"]),(1&r)==1&&this.addFormatting(e.pts,["u"]);else if(this.isOffsetControlCode(s,r)){let e=3&r;this.nonDisplayed_[this.row_].offset=e,this.column_+=e}else if(this.isPAC(s,r)){var a=D.indexOf(7968&t);if("rollUp"===this.mode_&&(a-this.rollUpRows_+1<0&&(a=this.rollUpRows_-1),this.setRollUp(e.pts,a)),a!==this.row_&&a>=0&&a<=14&&(this.clearFormatting(e.pts),this.row_=a),1&r&&-1===this.formatting_.indexOf("u")&&this.addFormatting(e.pts,["u"]),(16&t)==16){let e=(14&t)>>1;this.column_=4*e,this.nonDisplayed_[this.row_].indent+=e}this.isColorPAC(r)&&(14&r)==14&&this.addFormatting(e.pts,["i"])}else this.isNormalChar(s)&&(0===r&&(r=null),n=L(s)+L(r),this[this.mode_](e.pts,n),this.column_+=n.length)}}};M.prototype=new d,M.prototype.flushDisplayed=function(e){let t=e=>{this.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+e+"."})},i=[];this.displayed_.forEach((e,s)=>{if(e&&e.text&&e.text.length){try{e.text=e.text.trim()}catch(e){t(s)}e.text.length&&i.push({text:e.text,line:s+1,position:10+Math.min(70,10*e.indent)+2.5*e.offset})}else null==e&&t(s)}),i.length&&this.trigger("data",{startPts:this.startPts_,endPts:e,content:i,stream:this.name_})},M.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=O(),this.nonDisplayed_=O(),this.lastControlCode_=null,this.column_=0,this.row_=14,this.rollUpRows_=2,this.formatting_=[]},M.prototype.setConstants=function(){0===this.dataChannel_?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):1===this.dataChannel_&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=32|this.CONTROL_,this.END_OF_CAPTION_=47|this.CONTROL_,this.ROLL_UP_2_ROWS_=37|this.CONTROL_,this.ROLL_UP_3_ROWS_=38|this.CONTROL_,this.ROLL_UP_4_ROWS_=39|this.CONTROL_,this.CARRIAGE_RETURN_=45|this.CONTROL_,this.RESUME_DIRECT_CAPTIONING_=41|this.CONTROL_,this.BACKSPACE_=33|this.CONTROL_,this.ERASE_DISPLAYED_MEMORY_=44|this.CONTROL_,this.ERASE_NON_DISPLAYED_MEMORY_=46|this.CONTROL_},M.prototype.isSpecialCharacter=function(e,t){return e===this.EXT_&&t>=48&&t<=63},M.prototype.isExtCharacter=function(e,t){return(e===this.EXT_+1||e===this.EXT_+2)&&t>=32&&t<=63},M.prototype.isMidRowCode=function(e,t){return e===this.EXT_&&t>=32&&t<=47},M.prototype.isOffsetControlCode=function(e,t){return e===this.OFFSET_&&t>=33&&t<=35},M.prototype.isPAC=function(e,t){return e>=this.BASE_&&e=64&&t<=127},M.prototype.isColorPAC=function(e){return e>=64&&e<=79||e>=96&&e<=127},M.prototype.isNormalChar=function(e){return e>=32&&e<=127},M.prototype.setRollUp=function(e,t){if("rollUp"!==this.mode_&&(this.row_=14,this.mode_="rollUp",this.flushDisplayed(e),this.nonDisplayed_=O(),this.displayed_=O()),void 0!==t&&t!==this.row_)for(var i=0;i"},"");this[this.mode_](e,i)},M.prototype.clearFormatting=function(e){if(this.formatting_.length){var t=this.formatting_.reverse().reduce(function(e,t){return e+""},"");this.formatting_=[],this[this.mode_](e,t)}},M.prototype.popOn=function(e,t){var i=this.nonDisplayed_[this.row_].text;i+=t,this.nonDisplayed_[this.row_].text=i},M.prototype.rollUp=function(e,t){var i=this.displayed_[this.row_].text;i+=t,this.displayed_[this.row_].text=i},M.prototype.shiftRowsUp_=function(){var e;for(e=0;et&&(i=-1);Math.abs(t-e)>0x100000000;)e+=0x200000000*i;return e},$=function(e){var t,i;$.prototype.init.call(this),this.type_=e||j,this.push=function(e){if("metadata"===e.type){this.trigger("data",e);return}(this.type_===j||e.type===this.type_)&&(void 0===i&&(i=e.dts),e.dts=F(e.dts,i),e.pts=F(e.pts,i),t=e.dts,this.trigger("data",e))},this.flush=function(){i=t,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){i=void 0,t=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};$.prototype=new d;var q=(e,t,i)=>{if(!e)return -1;for(var s=i;s>>2;d*=4,d+=3&h[7],o.timeStamp=d,void 0===t.pts&&void 0===t.dts&&(t.pts=o.timeStamp,t.dts=o.timeStamp),this.trigger("timestamp",o)}t.frames.push(o),i+=10,i+=a}while(i>>4>1&&(s+=t[s]+1),0===i.pid)i.type="pat",e(t.subarray(s),i),this.trigger("data",i);else if(i.pid===this.pmtPid)for(i.type="pmt",e(t.subarray(s),i),this.trigger("data",i);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else void 0===this.programMapTable?this.packetsWaitingForPmt.push([t,s,i]):this.processPes_(t,s,i)},this.processPes_=function(e,t,i){i.pid===this.programMapTable.video?i.streamType=N.H264_STREAM_TYPE:i.pid===this.programMapTable.audio?i.streamType=N.ADTS_STREAM_TYPE:i.streamType=this.programMapTable["timed-metadata"][i.pid],i.type="pes",i.data=e.subarray(t),this.trigger("data",i)}}).prototype=new d,tl.STREAM_TYPES={h264:27,adts:15},(th=function(){var e,t=this,i=!1,s={data:[],size:0},r={data:[],size:0},n={data:[],size:0},a=function(e,t){var i;let s=e[0]<<16|e[1]<<8|e[2];t.data=new Uint8Array,1===s&&(t.packetLength=6+(e[4]<<8|e[5]),t.dataAlignmentIndicator=(4&e[6])!=0,192&(i=e[7])&&(t.pts=(14&e[9])<<27|(255&e[10])<<20|(254&e[11])<<12|(255&e[12])<<5|(254&e[13])>>>3,t.pts*=4,t.pts+=(6&e[13])>>>1,t.dts=t.pts,64&i&&(t.dts=(14&e[14])<<27|(255&e[15])<<20|(254&e[16])<<12|(255&e[17])<<5|(254&e[18])>>>3,t.dts*=4,t.dts+=(6&e[18])>>>1)),t.data=e.subarray(9+e[8]))},o=function(e,i,s){var r,n=new Uint8Array(e.size),o={type:i},l=0,h=0,d=!1;if(e.data.length&&!(e.size<9)){for(l=0,o.trackId=e.data[0].pid;l>5,h=(l=((3&t[d+6])+1)*1024)*J/Z[(60&t[d+2])>>>2],t.byteLength-d>>6&3)+1,channelcount:(1&t[d+2])<<2|(192&t[d+3])>>>6,samplerate:Z[(60&t[d+2])>>>2],samplingfrequencyindex:(60&t[d+2])>>>2,samplesize:16,data:t.subarray(d+7+a,d+n)}),i++,d+=n}"number"==typeof r&&(this.skipWarn_(r,d),r=null),t=t.subarray(d)}},this.flush=function(){i=0,this.trigger("done")},this.reset=function(){t=void 0,this.trigger("reset")},this.endTimeline=function(){t=void 0,this.trigger("endedtimeline")}}).prototype=new d;var ee=td;tu=function(e){var t=e.byteLength,i=0,s=0;this.length=function(){return 8*t},this.bitsAvailable=function(){return 8*t+s},this.loadWord=function(){var r=e.byteLength-t,n=new Uint8Array(4),a=Math.min(4,t);if(0===a)throw Error("no bytes available");n.set(e.subarray(r,r+a)),i=new DataView(n.buffer).getUint32(0),s=8*a,t-=a},this.skipBits=function(e){var r;s>e||(e-=s,r=Math.floor(e/8),e-=8*r,t-=r,this.loadWord()),i<<=e,s-=e},this.readBits=function(e){var r=Math.min(s,e),n=i>>>32-r;return((s-=r)>0?i<<=r:t>0&&this.loadWord(),(r=e-r)>0)?n<>>e)!=0)return i<<=e,s-=e,e;return this.loadWord(),e+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var e=this.skipLeadingZeros();return this.readBits(e+1)-1},this.readExpGolomb=function(){var e=this.readUnsignedExpGolomb();return 1&e?1+e>>>1:-1*(e>>>1)},this.readBoolean=function(){return 1===this.readBits(1)},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()},(tp=function(){var e,t,i=0;tp.prototype.init.call(this),this.push=function(s){t?((r=new Uint8Array(t.byteLength+s.data.byteLength)).set(t),r.set(s.data,t.byteLength),t=r):t=s.data;for(var r,n=t.byteLength;i3&&this.trigger("data",t.subarray(i+3)),t=null,i=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}}).prototype=new d,tm={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},(tc=function(){var e,t,i,s,r,n,a,o=new tp;tc.prototype.init.call(this),e=this,this.push=function(e){"video"===e.type&&(t=e.trackId,i=e.pts,s=e.dts,o.push(e))},o.on("data",function(a){var o={trackId:t,pts:i,dts:s,data:a,nalUnitTypeCode:31&a[0]};switch(o.nalUnitTypeCode){case 5:o.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:o.nalUnitType="sei_rbsp",o.escapedRBSP=r(a.subarray(1));break;case 7:o.nalUnitType="seq_parameter_set_rbsp",o.escapedRBSP=r(a.subarray(1)),o.config=n(o.escapedRBSP);break;case 8:o.nalUnitType="pic_parameter_set_rbsp";break;case 9:o.nalUnitType="access_unit_delimiter_rbsp"}e.trigger("data",o)}),o.on("done",function(){e.trigger("done")}),o.on("partialdone",function(){e.trigger("partialdone")}),o.on("reset",function(){e.trigger("reset")}),o.on("endedtimeline",function(){e.trigger("endedtimeline")}),this.flush=function(){o.flush()},this.partialFlush=function(){o.partialFlush()},this.reset=function(){o.reset()},this.endTimeline=function(){o.endTimeline()},a=function(e,t){var i,s=8,r=8;for(i=0;i=0?i:0,(16&e[t+5])>>4)?i+20:i+10},er=function(e,t){return e.length-t<10||73!==e[t]||68!==e[t+1]||51!==e[t+2]?t:(t+=es(e,t),er(e,t))},en=function(e){return e[0]<<21|e[1]<<14|e[2]<<7|e[3]},ea=function(e,t,i){var s,r="";for(s=t;s=t+2&&(255&e[t])==255&&(240&e[t+1])==240&&(22&e[t+1])==16},parseId3TagSize:es,parseAdtsSize:function(e,t){var i=(224&e[t+5])>>5,s=e[t+4]<<3;return 6144&e[t+3]|s|i},parseType:function(e,t){return 73===e[t]&&68===e[t+1]&&51===e[t+2]?"timed-metadata":!0&e[t]&&(240&e[t+1])==240?"audio":null},parseSampleRate:function(e){for(var t=0;t+5>>2]}return null},parseAacTimestamp:function(e){var t,i,s;t=10,64&e[5]&&(t+=4,t+=en(e.subarray(10,14)));do{if((i=en(e.subarray(t+4,t+8)))<1)break;if("PRIV"===String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3])){s=e.subarray(t+10,t+i+10);for(var r=0;r>>2;return a*=4,a+=3&n[7]}break}}t+=10,t+=i}while(t=3;){if(73===e[o]&&68===e[o+1]&&51===e[o+2]){if(e.length-o<10||(a=eo.parseId3TagSize(e,o),o+a>e.length))break;s={type:"timed-metadata",data:e.subarray(o,o+a)},this.trigger("data",s),o+=a;continue}if((255&e[o])==255&&(240&e[o+1])==240){if(e.length-o<7||(a=eo.parseAdtsSize(e,o),o+a>e.length))break;r={type:"audio",data:e.subarray(o,o+a),pts:t,dts:t},this.trigger("data",r),o+=a;continue}o++}e=e.length-o>0?e.subarray(o):new Uint8Array},this.reset=function(){e=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){e=new Uint8Array,this.trigger("endedtimeline")}}).prototype=new d;var el=tg,eh={mdat:eD,moof:eU,initSegment:function(e){var t,i=eL(),s=eR(e);return(t=new Uint8Array(i.byteLength+s.byteLength)).set(i),t.set(s,i.byteLength),t}},ed={groupNalsIntoFrames:function(e){var t,i,s=[],r=[];for(t=0,r.byteLength=0,r.nalCount=0,r.duration=0,s.byteLength=0;t1&&(t=e.shift(),e.byteLength-=t.byteLength,e.nalCount-=t.nalCount,e[0][0].dts=t.dts,e[0][0].pts=t.pts,e[0][0].duration+=t.duration),e},generateSampleTable:function(e,t){var i,s,r,n,a=t||0,o=[];for(i=0;iy.ONE_SECOND_IN_TS/2)){for((n=v()[e.samplerate])||(n=t[0].data),a=0;a=f?m:(g.minSegmentDts=1/0,m.filter(function(e){return e.dts>=f&&(g.minSegmentDts=Math.min(g.minSegmentDts,e.dts),g.minSegmentPts=g.minSegmentDts,!0)})),e.baseMediaDecodeTime=em.calculateTrackBaseMediaDecodeTime(e,t.keepOriginalTimestamps),p=eu(e,o,n,a),e.samples=ec(o),h=eh.mdat(ep(o)),s=[],d=new Uint8Array((l=eh.moof(i,[e])).byteLength+h.byteLength),i++,d.set(l),d.set(h,l.byteLength),em.clearDtsInfo(e),u=Math.ceil(1024*ef/e.samplerate),o.length&&(c=o.length*u,this.trigger("segmentTimingInfo",eS(y.audioTsToVideoTs(e.baseMediaDecodeTime,e.samplerate),o[0].dts,o[0].pts,o[0].dts+c,o[0].pts+c,p||0)),this.trigger("timingInfo",{start:o[0].pts,end:o[0].pts+c})),this.trigger("data",{track:e,boxes:d}),this.trigger("done","AudioSegmentStream")},this.reset=function(){em.clearDtsInfo(e),s=[],this.trigger("reset")}}).prototype=new d,(tf=function(e,t){var i,s,r,n=[],a=[];i=(t=t||{}).firstSequenceNumber||0,tf.prototype.init.call(this),delete e.minPTS,this.gopCache_=[],this.push=function(t){em.collectDtsInfo(e,t),"seq_parameter_set_rbsp"!==t.nalUnitType||s||(s=t.config,e.sps=[t.data],ey.forEach(function(t){e[t]=s[t]},this)),"pic_parameter_set_rbsp"!==t.nalUnitType||r||(r=t.data,e.pps=[t.data]),n.push(t)},this.flush=function(){for(var s,r,o,l,h,d,u,c,p,m=0;n.length&&"access_unit_delimiter_rbsp"!==n[0].nalUnitType;)n.shift();if(0===n.length){this.resetStream_(),this.trigger("done","VideoSegmentStream");return}if(r=ed.groupNalsIntoFrames(n),(l=ed.groupFramesIntoGops(r))[0][0].keyFrame||((o=this.getGopForFusion_(n[0],e))?(m=o.duration,l.unshift(o),l.byteLength+=o.byteLength,l.nalCount+=o.nalCount,l.pts=o.pts,l.dts=o.dts,l.duration+=o.duration):l=ed.extendFirstKeyFrame(l)),a.length){if(!(s=t.alignGopsAtEnd?this.alignGopsAtEnd_(l):this.alignGopsAtStart_(l))){this.gopCache_.unshift({gop:l.pop(),pps:e.pps,sps:e.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),n=[],this.resetStream_(),this.trigger("done","VideoSegmentStream");return}em.clearDtsInfo(e),l=s}em.collectDtsInfo(e,l),e.samples=ed.generateSampleTable(l),d=eh.mdat(ed.concatenateNalData(l)),e.baseMediaDecodeTime=em.calculateTrackBaseMediaDecodeTime(e,t.keepOriginalTimestamps),this.trigger("processedGopsInfo",l.map(function(e){return{pts:e.pts,dts:e.dts,byteLength:e.byteLength}})),c=l[0],p=l[l.length-1],this.trigger("segmentTimingInfo",eS(e.baseMediaDecodeTime,c.dts,c.pts,p.dts+p.duration,p.pts+p.duration,m)),this.trigger("timingInfo",{start:l[0].pts,end:l[l.length-1].pts+l[l.length-1].duration}),this.gopCache_.unshift({gop:l.pop(),pps:e.pps,sps:e.sps}),this.gopCache_.length=Math.min(6,this.gopCache_.length),n=[],this.trigger("baseMediaDecodeTime",e.baseMediaDecodeTime),this.trigger("timelineStartInfo",e.timelineStartInfo),u=new Uint8Array((h=eh.moof(i,[e])).byteLength+d.byteLength),i++,u.set(h),u.set(d,h.byteLength),this.trigger("data",{track:e,boxes:u}),this.resetStream_(),this.trigger("done","VideoSegmentStream")},this.reset=function(){this.resetStream_(),n=[],this.gopCache_.length=0,a.length=0,this.trigger("reset")},this.resetStream_=function(){em.clearDtsInfo(e),s=void 0,r=void 0},this.getGopForFusion_=function(t){var i,s,r,n,a,o=1/0;for(a=0;a=-1e4&&i<=45e3&&(!s||o>i)&&(s=n,o=i);return s?s.gop:null},this.alignGopsAtStart_=function(e){var t,i,s,r,n,o,l,h;for(n=e.byteLength,o=e.nalCount,l=e.duration,t=i=0;ts.pts){t++;continue}i++,n-=r.byteLength,o-=r.nalCount,l-=r.duration}return 0===i?e:i===e.length?null:((h=e.slice(i)).byteLength=n,h.duration=l,h.nalCount=o,h.pts=h[0].pts,h.dts=h[0].dts,h)},this.alignGopsAtEnd_=function(e){for(t=a.length-1,i=e.length-1,n=null,o=!1;t>=0&&i>=0;){if(s=a[t],r=e[i],s.pts===r.pts){o=!0;break}if(s.pts>r.pts){t--;continue}t===a.length-1&&(n=i),i--}if(!o&&null===n)return null;if(0===(l=o?i:n))return e;var t,i,s,r,n,o,l,h=e.slice(l),d=h.reduce(function(e,t){return e.byteLength+=t.byteLength,e.duration+=t.duration,e.nalCount+=t.nalCount,e},{byteLength:0,duration:0,nalCount:0});return h.byteLength=d.byteLength,h.duration=d.duration,h.nalCount=d.nalCount,h.pts=h[0].pts,h.dts=h[0].dts,h},this.alignGopsWith=function(e){a=e}}).prototype=new d,(tv=function(e,t){this.numberOfTracks=0,this.metadataStream=t,void 0!==(e=e||{}).remux?this.remuxTracks=!!e.remux:this.remuxTracks=!0,"boolean"==typeof e.keepOriginalTimestamps?this.keepOriginalTimestamps=e.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,tv.prototype.init.call(this),this.push=function(e){return e.content||e.text?this.pendingCaptions.push(e):e.frames?this.pendingMetadata.push(e):void(this.pendingTracks.push(e.track),this.pendingBytes+=e.boxes.byteLength,"video"===e.track.type&&(this.videoTrack=e.track,this.pendingBoxes.push(e.boxes)),"audio"===e.track.type&&(this.audioTrack=e.track,this.pendingBoxes.unshift(e.boxes)))}}).prototype=new d,tv.prototype.flush=function(e){var t,i,s,r,n=0,a={captions:[],captionStreams:{},metadata:[],info:{}},o=0;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0);return}}if(this.videoTrack?(o=this.videoTrack.timelineStartInfo.pts,ey.forEach(function(e){a.info[e]=this.videoTrack[e]},this)):this.audioTrack&&(o=this.audioTrack.timelineStartInfo.pts,e_.forEach(function(e){a.info[e]=this.audioTrack[e]},this)),this.videoTrack||this.audioTrack){for(1===this.pendingTracks.length?a.type=this.pendingTracks[0].type:a.type="combined",this.emittedTracks+=this.pendingTracks.length,s=eh.initSegment(this.pendingTracks),a.initSegment=new Uint8Array(s.byteLength),a.initSegment.set(s),a.data=new Uint8Array(this.pendingBytes),r=0;r=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},tv.prototype.setRemux=function(e){this.remuxTracks=e},(ty=function(e){var t,i,s=this,r=!0;ty.prototype.init.call(this),e=e||{},this.baseMediaDecodeTime=e.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var r={};this.transmuxPipeline_=r,r.type="aac",r.metadataStream=new Y.MetadataStream,r.aacStream=new el,r.audioTimestampRolloverStream=new Y.TimestampRolloverStream("audio"),r.timedMetadataTimestampRolloverStream=new Y.TimestampRolloverStream("timed-metadata"),r.adtsStream=new ee,r.coalesceStream=new tv(e,r.metadataStream),r.headOfPipeline=r.aacStream,r.aacStream.pipe(r.audioTimestampRolloverStream).pipe(r.adtsStream),r.aacStream.pipe(r.timedMetadataTimestampRolloverStream).pipe(r.metadataStream).pipe(r.coalesceStream),r.metadataStream.on("timestamp",function(e){r.aacStream.setTimestamp(e.timeStamp)}),r.aacStream.on("data",function(n){("timed-metadata"===n.type||"audio"===n.type)&&!r.audioSegmentStream&&(i=i||{timelineStartInfo:{baseMediaDecodeTime:s.baseMediaDecodeTime},codec:"adts",type:"audio"},r.coalesceStream.numberOfTracks++,r.audioSegmentStream=new t_(i,e),r.audioSegmentStream.on("log",s.getLogTrigger_("audioSegmentStream")),r.audioSegmentStream.on("timingInfo",s.trigger.bind(s,"audioTimingInfo")),r.adtsStream.pipe(r.audioSegmentStream).pipe(r.coalesceStream),s.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t}))}),r.coalesceStream.on("data",this.trigger.bind(this,"data")),r.coalesceStream.on("done",this.trigger.bind(this,"done")),eb(this,r)},this.setupTsPipeline=function(){var r={};this.transmuxPipeline_=r,r.type="ts",r.metadataStream=new Y.MetadataStream,r.packetStream=new Y.TransportPacketStream,r.parseStream=new Y.TransportParseStream,r.elementaryStream=new Y.ElementaryStream,r.timestampRolloverStream=new Y.TimestampRolloverStream,r.adtsStream=new ee,r.h264Stream=new et,r.captionStream=new Y.CaptionStream(e),r.coalesceStream=new tv(e,r.metadataStream),r.headOfPipeline=r.packetStream,r.packetStream.pipe(r.parseStream).pipe(r.elementaryStream).pipe(r.timestampRolloverStream),r.timestampRolloverStream.pipe(r.h264Stream),r.timestampRolloverStream.pipe(r.adtsStream),r.timestampRolloverStream.pipe(r.metadataStream).pipe(r.coalesceStream),r.h264Stream.pipe(r.captionStream).pipe(r.coalesceStream),r.elementaryStream.on("data",function(n){var a;if("metadata"===n.type){for(a=n.tracks.length;a--;)t||"video"!==n.tracks[a].type?i||"audio"!==n.tracks[a].type||((i=n.tracks[a]).timelineStartInfo.baseMediaDecodeTime=s.baseMediaDecodeTime):(t=n.tracks[a]).timelineStartInfo.baseMediaDecodeTime=s.baseMediaDecodeTime;t&&!r.videoSegmentStream&&(r.coalesceStream.numberOfTracks++,r.videoSegmentStream=new tf(t,e),r.videoSegmentStream.on("log",s.getLogTrigger_("videoSegmentStream")),r.videoSegmentStream.on("timelineStartInfo",function(t){i&&!e.keepOriginalTimestamps&&(i.timelineStartInfo=t,r.audioSegmentStream.setEarliestDts(t.dts-s.baseMediaDecodeTime))}),r.videoSegmentStream.on("processedGopsInfo",s.trigger.bind(s,"gopInfo")),r.videoSegmentStream.on("segmentTimingInfo",s.trigger.bind(s,"videoSegmentTimingInfo")),r.videoSegmentStream.on("baseMediaDecodeTime",function(e){i&&r.audioSegmentStream.setVideoBaseMediaDecodeTime(e)}),r.videoSegmentStream.on("timingInfo",s.trigger.bind(s,"videoTimingInfo")),r.h264Stream.pipe(r.videoSegmentStream).pipe(r.coalesceStream)),i&&!r.audioSegmentStream&&(r.coalesceStream.numberOfTracks++,r.audioSegmentStream=new t_(i,e),r.audioSegmentStream.on("log",s.getLogTrigger_("audioSegmentStream")),r.audioSegmentStream.on("timingInfo",s.trigger.bind(s,"audioTimingInfo")),r.audioSegmentStream.on("segmentTimingInfo",s.trigger.bind(s,"audioSegmentTimingInfo")),r.adtsStream.pipe(r.audioSegmentStream).pipe(r.coalesceStream)),s.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!t})}}),r.coalesceStream.on("data",this.trigger.bind(this,"data")),r.coalesceStream.on("id3Frame",function(e){e.dispatchType=r.metadataStream.dispatchType,s.trigger("id3Frame",e)}),r.coalesceStream.on("caption",this.trigger.bind(this,"caption")),r.coalesceStream.on("done",this.trigger.bind(this,"done")),eb(this,r)},this.setBaseMediaDecodeTime=function(s){var r=this.transmuxPipeline_;e.keepOriginalTimestamps||(this.baseMediaDecodeTime=s),i&&(i.timelineStartInfo.dts=void 0,i.timelineStartInfo.pts=void 0,em.clearDtsInfo(i),r.audioTimestampRolloverStream&&r.audioTimestampRolloverStream.discontinuity()),t&&(r.videoSegmentStream&&(r.videoSegmentStream.gopCache_=[]),t.timelineStartInfo.dts=void 0,t.timelineStartInfo.pts=void 0,em.clearDtsInfo(t),r.captionStream.reset()),r.timestampRolloverStream&&r.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(e){i&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(e)},this.setRemux=function(t){var i=this.transmuxPipeline_;e.remux=t,i&&i.coalesceStream&&i.coalesceStream.setRemux(t)},this.alignGopsWith=function(e){t&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(e)},this.getLogTrigger_=function(e){var t=this;return function(i){i.stream=e,t.trigger("log",i)}},this.push=function(e){if(r){var t=eg(e);t&&"aac"!==this.transmuxPipeline_.type?this.setupAacPipeline():t||"ts"===this.transmuxPipeline_.type||this.setupTsPipeline(),r=!1}this.transmuxPipeline_.headOfPipeline.push(e)},this.flush=function(){r=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}}).prototype=new d;var ek,eC,ew,eE,ex,eI,eP,eA,eL,eD,eO,eM,eU,eR,eB,eN,ej,eF,e$,eq,eH,eV,ez,eW,eG,eK,eQ,eY,eX,eJ,eZ,e0,e1,e2,e4,e8,e5,e3,e6,e7,e9,te,tt,ti,ts,tr,tn,ta,to,tl,th,td,tu,tc,tp,tm,tg,tf,t_,ty,tv,tb,tT,tS=ty,tk=function(e){return e>>>0},tC=function(e){var t="";return t+=String.fromCharCode(e[0]),t+=String.fromCharCode(e[1]),t+=String.fromCharCode(e[2]),t+=String.fromCharCode(e[3])},tw=function(e,t){var i,s,r,n,a,o=[];if(!t.length)return null;for(i=0;i1?i+s:e.byteLength,r===t[0]&&(1===t.length?o.push(e.subarray(i+8,n)):(a=tw(e.subarray(i+8,n),t.slice(1))).length&&(o=o.concat(a))),i=n;return o},tE=function(e){var t={version:e[0],flags:new Uint8Array(e.subarray(1,4))};return 1===t.version?t.baseMediaDecodeTime=u(e.subarray(4)):t.baseMediaDecodeTime=tk(e[4]<<24|e[5]<<16|e[6]<<8|e[7]),t},tx=function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),s={version:e[0],flags:new Uint8Array(e.subarray(1,4)),trackId:i.getUint32(4)},r=1&s.flags[2],n=2&s.flags[2],a=8&s.flags[2],o=16&s.flags[2],l=32&s.flags[2],h=65536&s.flags[0],d=131072&s.flags[0];return t=8,r&&(t+=4,s.baseDataOffset=i.getUint32(12),t+=4),n&&(s.sampleDescriptionIndex=i.getUint32(t),t+=4),a&&(s.defaultSampleDuration=i.getUint32(t),t+=4),o&&(s.defaultSampleSize=i.getUint32(t),t+=4),l&&(s.defaultSampleFlags=i.getUint32(t)),h&&(s.durationIsEmpty=!0),!r&&d&&(s.baseDataOffsetIsMoof=!0),s},tI=u,tP=function(e){return{isLeading:(12&e[0])>>>2,dependsOn:3&e[0],isDependedOn:(192&e[1])>>>6,hasRedundancy:(48&e[1])>>>4,paddingValue:(14&e[1])>>>1,isNonSyncSample:1&e[1],degradationPriority:e[2]<<8|e[3]}},tA=function(e){var t,i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),samples:[]},s=new DataView(e.buffer,e.byteOffset,e.byteLength),r=1&i.flags[2],n=4&i.flags[2],a=1&i.flags[1],o=2&i.flags[1],l=4&i.flags[1],h=8&i.flags[1],d=s.getUint32(4),u=8;for(r&&(i.dataOffset=s.getInt32(u),u+=4),n&&d&&(t={flags:tP(e.subarray(u,u+4))},u+=4,a&&(t.duration=s.getUint32(u),u+=4),o&&(t.size=s.getUint32(u),u+=4),h&&(1===i.version?t.compositionTimeOffset=s.getInt32(u):t.compositionTimeOffset=s.getUint32(u),u+=4),i.samples.push(t),d--);d--;)t={},a&&(t.duration=s.getUint32(u),u+=4),o&&(t.size=s.getUint32(u),u+=4),l&&(t.flags=tP(e.subarray(u,u+4)),u+=4),h&&(1===i.version?t.compositionTimeOffset=s.getInt32(u):t.compositionTimeOffset=s.getUint32(u),u+=4),i.samples.push(t);return i},tL=u,tD=function(e){return new Date(1e3*e-20828448e5)},tO=function(e){var t,i,s=new DataView(e.buffer,e.byteOffset,e.byteLength),r=[];for(t=0;t+4MALFORMED DATA");continue}switch(31&e[t]){case 1:r.push("slice_layer_without_partitioning_rbsp");break;case 5:r.push("slice_layer_without_partitioning_rbsp_idr");break;case 6:r.push("sei_rbsp");break;case 7:r.push("seq_parameter_set_rbsp");break;case 8:r.push("pic_parameter_set_rbsp");break;case 9:r.push("access_unit_delimiter_rbsp");break;default:r.push("UNKNOWN NAL - "+e[t]&31)}}return r},tM={avc1:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{dataReferenceIndex:t.getUint16(6),width:t.getUint16(24),height:t.getUint16(26),horizresolution:t.getUint16(28)+t.getUint16(30)/16,vertresolution:t.getUint16(32)+t.getUint16(34)/16,frameCount:t.getUint16(40),depth:t.getUint16(74),config:tb(e.subarray(78,e.byteLength))}},avcC:function(e){var t,i,s,r,n=new DataView(e.buffer,e.byteOffset,e.byteLength),a={configurationVersion:e[0],avcProfileIndication:e[1],profileCompatibility:e[2],avcLevelIndication:e[3],lengthSizeMinusOne:3&e[4],sps:[],pps:[]},o=31&e[5];for(r=0,s=6;r>>2&63,bufferSize:e[13]<<16|e[14]<<8|e[15],maxBitrate:e[16]<<24|e[17]<<16|e[18]<<8|e[19],avgBitrate:e[20]<<24|e[21]<<16|e[22]<<8|e[23],decoderConfigDescriptor:{tag:e[24],length:e[25],audioObjectType:e[26]>>>3&31,samplingFrequencyIndex:(7&e[26])<<1|e[27]>>>7&1,channelConfiguration:e[27]>>>3&15}}}},ftyp:function(e){for(var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i={majorBrand:tC(e.subarray(0,4)),minorVersion:t.getUint32(4),compatibleBrands:[]},s=8;s>10)+96),r.language+=String.fromCharCode(((992&t)>>5)+96),r.language+=String.fromCharCode((31&t)+96),r},mdia:function(e){return{boxes:tb(e)}},mfhd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),sequenceNumber:e[4]<<24|e[5]<<16|e[6]<<8|e[7]}},minf:function(e){return{boxes:tb(e)}},mp4a:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i={dataReferenceIndex:t.getUint16(6),channelcount:t.getUint16(16),samplesize:t.getUint16(18),samplerate:t.getUint16(24)+t.getUint16(26)/65536};return e.byteLength>28&&(i.streamDescriptor=tb(e.subarray(28))[0]),i},moof:function(e){return{boxes:tb(e)}},moov:function(e){return{boxes:tb(e)}},mvex:function(e){return{boxes:tb(e)}},mvhd:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=4,s={version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4))};return 1===s.version?(i+=4,s.creationTime=tD(t.getUint32(i)),i+=8,s.modificationTime=tD(t.getUint32(i)),i+=4,s.timescale=t.getUint32(i),i+=8):(s.creationTime=tD(t.getUint32(i)),i+=4,s.modificationTime=tD(t.getUint32(i)),i+=4,s.timescale=t.getUint32(i),i+=4),s.duration=t.getUint32(i),i+=4,s.rate=t.getUint16(i)+t.getUint16(i+2)/16,i+=4,s.volume=t.getUint8(i)+t.getUint8(i+1)/8,i+=12,s.matrix=new Uint32Array(e.subarray(i,i+36)),i+=60,s.nextTrackId=t.getUint32(i),s},pdin:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{version:t.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),rate:t.getUint32(4),initialDelay:t.getUint32(8)}},sdtp:function(e){var t,i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),samples:[]};for(t=4;t>4,isDependedOn:(12&e[t])>>2,hasRedundancy:3&e[t]});return i},sidx:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i={version:e[0],flags:new Uint8Array(e.subarray(1,4)),references:[],referenceId:t.getUint32(4),timescale:t.getUint32(8)},s=12;0===i.version?(i.earliestPresentationTime=t.getUint32(s),i.firstOffset=t.getUint32(s+4),s+=8):(i.earliestPresentationTime=tI(e.subarray(s)),i.firstOffset=tI(e.subarray(s+8)),s+=16),s+=2;var r=t.getUint16(s);for(s+=2;r>0;s+=12,r--)i.references.push({referenceType:(128&e[s])>>>7,referencedSize:0x7fffffff&t.getUint32(s),subsegmentDuration:t.getUint32(s+4),startsWithSap:!!(128&e[s+8]),sapType:(112&e[s+8])>>>4,sapDeltaTime:0xfffffff&t.getUint32(s+8)});return i},smhd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),balance:e[4]+e[5]/256}},stbl:function(e){return{boxes:tb(e)}},ctts:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),s={version:i.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),compositionOffsets:[]},r=i.getUint32(4);for(t=8;r;t+=8,r--)s.compositionOffsets.push({sampleCount:i.getUint32(t),sampleOffset:i[0===s.version?"getUint32":"getInt32"](t+4)});return s},stss:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),s={version:i.getUint8(0),flags:new Uint8Array(e.subarray(1,4)),syncSamples:[]},r=i.getUint32(4);for(t=8;r;t+=4,r--)s.syncSamples.push(i.getUint32(t));return s},stco:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),s={version:e[0],flags:new Uint8Array(e.subarray(1,4)),chunkOffsets:[]},r=i.getUint32(4);for(t=8;r;t+=4,r--)s.chunkOffsets.push(i.getUint32(t));return s},stsc:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),s=i.getUint32(4),r={version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleToChunks:[]};for(t=8;s;t+=12,s--)r.sampleToChunks.push({firstChunk:i.getUint32(t),samplesPerChunk:i.getUint32(t+4),sampleDescriptionIndex:i.getUint32(t+8)});return r},stsd:function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleDescriptions:tb(e.subarray(8))}},stsz:function(e){var t,i=new DataView(e.buffer,e.byteOffset,e.byteLength),s={version:e[0],flags:new Uint8Array(e.subarray(1,4)),sampleSize:i.getUint32(4),entries:[]};for(t=12;t>6,sampleHasRedundancy:(48&e[21])>>4,samplePaddingValue:(14&e[21])>>1,sampleIsDifferenceSample:!!(1&e[21]),sampleDegradationPriority:t.getUint16(22)}},trun:tA,"url ":function(e){return{version:e[0],flags:new Uint8Array(e.subarray(1,4))}},vmhd:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{version:e[0],flags:new Uint8Array(e.subarray(1,4)),graphicsmode:t.getUint16(4),opcolor:new Uint16Array([t.getUint16(6),t.getUint16(8),t.getUint16(10)])}}},tU={inspect:tb=function(e){for(var t,i,s,r,n,a=0,o=[],l=new ArrayBuffer(e.length),h=new Uint8Array(l),d=0;d1?a+i:e.byteLength,(n=(tM[s]||function(e){return{data:e}})(e.subarray(a+8,r))).size=i,n.type=s,o.push(n),a=r;return o},textify:tT=function(e,t){var i;return i=Array(2*(t=t||0)+1).join(" "),e.map(function(e,s){return i+e.type+"\n"+Object.keys(e).filter(function(e){return"type"!==e&&"boxes"!==e}).map(function(t){var s=i+" "+t+": ",r=e[t];if(r instanceof Uint8Array||r instanceof Uint32Array){var n=Array.prototype.slice.call(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).map(function(e){return" "+("00"+e.toString(16)).slice(-2)}).join("").match(/.{1,24}/g);return n?1===n.length?s+"<"+n.join("").slice(1)+">":s+"<\n"+n.map(function(e){return i+" "+e}).join("\n")+"\n"+i+" >":s+"<>"}return s+JSON.stringify(r,null,2).split("\n").map(function(e,t){return 0===t?e:i+" "+e}).join("\n")}).join("\n")+(e.boxes?"\n"+tT(e.boxes,t+1):"")}).join("\n")},parseType:tC,findBox:tw,parseTraf:tM.traf,parseTfdt:tM.tfdt,parseHdlr:tM.hdlr,parseTfhd:tM.tfhd,parseTrun:tM.trun,parseSidx:tM.sidx},tR=function(e){for(var t=0,i=String.fromCharCode(e[0]),s="";"\0"!==i;)s+=i,i=String.fromCharCode(e[++t]);return s+i},tB=function(e,t){var i="\0"!==t.scheme_id_uri,s=0===e&&tN(t.presentation_time_delta)&&i,r=1===e&&tN(t.presentation_time)&&i;return!(e>1)&&s||r},tN=function(e){return void 0!==e||null!==e},tj="undefined"!=typeof window?window:void 0!==h?h:"undefined"!=typeof self?self:{},tF=function(e){return("00"+e.toString(16)).slice(-2)},t$=function(e){var t,i,s,r,n,a,o,l=4,h=e[0];if(0===h){t=tR(e.subarray(l)),l+=t.length,i=tR(e.subarray(l)),l+=i.length;var d=new DataView(e.buffer);s=d.getUint32(l),l+=4,n=d.getUint32(l),l+=4,a=d.getUint32(l),l+=4,o=d.getUint32(l),l+=4}else if(1===h){var d=new DataView(e.buffer);s=d.getUint32(l),l+=4,r=u(e.subarray(l)),l+=8,a=d.getUint32(l),l+=4,o=d.getUint32(l),l+=4,t=tR(e.subarray(l)),l+=t.length,i=tR(e.subarray(l)),l+=i.length}var c={scheme_id_uri:t,value:i,timescale:s||1,presentation_time:r,presentation_time_delta:n,event_duration:a,id:o,message_data:new Uint8Array(e.subarray(l,e.byteLength))};return tB(h,c)?c:void 0},tq=function(e,t,i,s){return e||0===e?e/t:s+i/t},tH=K.parseId3Frames;t=function(e){return tw(e,["moov","trak"]).reduce(function(e,t){var i,s,r,n,a;return(i=tw(t,["tkhd"])[0])&&(r=0===i[0]?12:20,n=tk(i[r]<<24|i[r+1]<<16|i[r+2]<<8|i[r+3]),a=tw(t,["mdia","mdhd"])[0])?(r=0===a[0]?12:20,e[n]=tk(a[r]<<24|a[r+1]<<16|a[r+2]<<8|a[r+3]),e):null},{})},s=function(e,t){var i=tw(t,["moof","traf"]).reduce(function(t,i){let s;var r,n=tw(i,["tfhd"])[0],a=e[tk(n[4]<<24|n[5]<<16|n[6]<<8|n[7])]||9e4,o=tw(i,["tfdt"])[0],l=new DataView(o.buffer,o.byteOffset,o.byteLength);return"bigint"==typeof(r=1===o[0]?u(o.subarray(4,12)):l.getUint32(4))?s=r/tj.BigInt(a):"number"!=typeof r||isNaN(r)||(s=r/a),s11?(t.codec+=".",t.codec+=tF(d[9]),t.codec+=tF(d[10]),t.codec+=tF(d[11])):t.codec="avc1.4d400d":/^mp4[a,v]$/i.test(t.codec)?"esds"===tC((d=p.subarray(28)).subarray(4,8))&&d.length>20&&0!==d[19]?(t.codec+="."+tF(d[19]),t.codec+="."+tF(d[20]>>>2&63).replace(/^0/,"")):t.codec="mp4a.40.2":t.codec=t.codec.toLowerCase())}var m=tw(e,["mdia","mdhd"])[0];m&&(t.timescale=o(m)),i.push(t)}),i},l=function(e,t=0){return tw(e,["emsg"]).map(e=>{var i=t$(new Uint8Array(e)),s=tH(i.message_data);return{cueTime:tq(i.presentation_time,i.timescale,i.presentation_time_delta,t),duration:tq(i.event_duration,i.timescale),frames:s}})};var tV={findBox:tw,parseType:tC,timescale:t,startTime:s,compositionStartTime:r,videoTrackIds:n,tracks:a,getTimescaleFromMediaHeader:o,getEmsgID3:l};let{parseTrun:tz}=tU,{findBox:tW}=tV;var tG={getMdatTrafPairs:function(e){var t=tW(e,["moof","traf"]),i=tW(e,["mdat"]),s=[];return i.forEach(function(e,i){var r=t[i];s.push({mdat:e,traf:r})}),s},parseSamples:function(e,t,i){var s=t,r=i.defaultSampleDuration||0,n=i.defaultSampleSize||0,a=i.trackId,o=[];return e.forEach(function(e){var t=tz(e).samples;t.forEach(function(e){void 0===e.duration&&(e.duration=r),void 0===e.size&&(e.size=n),e.trackId=a,e.dts=s,void 0===e.compositionTimeOffset&&(e.compositionTimeOffset=0),"bigint"==typeof s?(e.pts=s+tj.BigInt(e.compositionTimeOffset),s+=tj.BigInt(e.duration)):(e.pts=s+e.compositionTimeOffset,s+=e.duration)}),o=o.concat(t)}),o}},tK=S.discardEmulationPreventionBytes,{getMdatTrafPairs:tQ,parseSamples:tY}=tG,tX=function(e,t){for(var i=e,s=0;s0?tE(l[0]).baseMediaDecodeTime:0,d=tw(n,["trun"]);t===o&&d.length>0&&(s=tJ(r,tY(d,h,a),o),i[o]||(i[o]={seiNals:[],logs:[]}),i[o].seiNals=i[o].seiNals.concat(s.seiNals),i[o].logs=i[o].logs.concat(s.logs))}),i},t0=function(e,t,i){if(null===t)return null;var s=tZ(e,t)[t]||{};return{seiNals:s.seiNals,logs:s.logs,timescale:i}},t1=function(){var e,t,i,s,r,n,a=!1;this.isInitialized=function(){return a},this.init=function(t){e=new U,a=!0,n=!!t&&t.isPartial,e.on("data",function(e){e.startTime=e.startPts/s,e.endTime=e.endPts/s,r.captions.push(e),r.captionStreams[e.stream]=!0}),e.on("log",function(e){r.logs.push(e)})},this.isNewInit=function(e,t){return(!e||0!==e.length)&&(!t||"object"!=typeof t||0!==Object.keys(t).length)&&(i!==e[0]||s!==t[i])},this.parse=function(e,n,a){var o;if(!this.isInitialized()||!n||!a)return null;if(this.isNewInit(n,a))s=a[i=n[0]];else if(null===i||!s)return t.push(e),null;for(;t.length>0;){var l=t.shift();this.parse(l,n,a)}return((o=t0(e,i,s))&&o.logs&&(r.logs=r.logs.concat(o.logs)),null!==o&&o.seiNals)?(this.pushNals(o.seiNals),this.flushStream(),r):r.logs.length?{logs:r.logs,captions:[],captionStreams:[]}:null},this.pushNals=function(t){if(!this.isInitialized()||!t||0===t.length)return null;t.forEach(function(t){e.push(t)})},this.flushStream=function(){if(!this.isInitialized())return null;n?e.partialFlush():e.flush()},this.clearParsedCaptions=function(){r.captions=[],r.captionStreams={},r.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;e.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){t=[],i=null,s=null,r?this.clearParsedCaptions():r={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()};let{parseTfdt:t2}=tU,{getTimescaleFromMediaHeader:t4}=tV,{parseSamples:t8,getMdatTrafPairs:t5}=tG;var t3=function(){let e=9e4;this.init=function(t){let i=tw(t,["moov","trak","mdia","mdhd"])[0];i&&(e=t4(i))},this.parseSegment=function(t){let i=[],s=t5(t),r=0;return s.forEach(function(t){let s=t.mdat,n=t.traf,a=tw(n,["tfdt"])[0],o=tw(n,["tfhd"])[0],l=tw(n,["trun"]);if(a&&(r=t2(a).baseMediaDecodeTime),l.length&&o){let t=t8(l,r,o),n=0;t.forEach(function(t){let r=new TextDecoder("utf-8"),a=s.slice(n,n+t.size);if(tw(a,["vtte"])[0]){n+=t.size;return}tw(a,["vttc"]).forEach(function(s){let n,a;let o=tw(s,["payl"])[0],l=tw(s,["sttg"])[0],h=t.pts/e,d=(t.pts+t.duration)/e;if(o)try{n=r.decode(o)}catch(e){console.error(e)}if(l)try{a=r.decode(l)}catch(e){console.error(e)}t.duration&&n&&i.push({cueText:n,start:h,end:d,settings:a})}),n+=t.size})}}),i}},t6=function(e){var t=31&e[1];return t<<=8,t|=e[2]},t7=function(e){return!!(64&e[1])},t9=function(e){var t=0;return(48&e[3])>>>4>1&&(t+=e[4]+1),t},ie=function(e){switch(e){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},it={};it.ts={parseType:function(e,t){var i=t6(e);return 0===i?"pat":i===t?"pmt":t?"pes":null},parsePat:function(e){var t=t7(e),i=4+t9(e);return t&&(i+=e[i]+1),(31&e[i+10])<<8|e[i+11]},parsePmt:function(e){var t,i={},s=t7(e),r=4+t9(e);if(s&&(r+=e[r]+1),1&e[r+5]){t=3+((15&e[r+1])<<8|e[r+2])-4;for(var n=12+((15&e[r+10])<<8|e[r+11]);n=e.byteLength)return null;var s=null;return 192&(t=e[i+7])&&((s={}).pts=(14&e[i+9])<<27|(255&e[i+10])<<20|(254&e[i+11])<<12|(255&e[i+12])<<5|(254&e[i+13])>>>3,s.pts*=4,s.pts+=(6&e[i+13])>>>1,s.dts=s.pts,64&t&&(s.dts=(14&e[i+14])<<27|(255&e[i+15])<<20|(254&e[i+16])<<12|(255&e[i+17])<<5|(254&e[i+18])>>>3,s.dts*=4,s.dts+=(6&e[i+18])>>>1)),s},videoPacketContainsKeyFrame:function(e){for(var t,i=4+t9(e),s=e.subarray(i),r=0,n=0,a=!1;n3&&"slice_layer_without_partitioning_rbsp_idr"===ie(31&s[n+3])&&(a=!0),a}},it.aac=eo;var ii=y.ONE_SECOND_IN_TS,is=function(e,t){for(var i,s=0,r=188;r=0;){if(71===e[l]&&(71===e[h]||h===e.byteLength)){if(s=e.subarray(l,h),"pes"===it.ts.parseType(s,t.pid)&&(n=it.ts.parsePesType(s,t.table),a=it.ts.parsePayloadUnitStartIndicator(s),"audio"===n&&a&&(o=it.ts.parsePesTime(s))&&(o.type="audio",i.audio.push(o),d=!0)),d)break;l-=188,h-=188;continue}l--,h--}},ia=function(e,t,i){for(var s,r,n,a,o,l,h,d,u=0,c=188,p=!1,m={data:[],size:0};c=0;){if(71===e[u]&&71===e[c]){if(s=e.subarray(u,c),"pes"===it.ts.parseType(s,t.pid)&&(n=it.ts.parsePesType(s,t.table),a=it.ts.parsePayloadUnitStartIndicator(s),"video"===n&&a&&(o=it.ts.parsePesTime(s))&&(o.type="video",i.video.push(o),p=!0)),p)break;u-=188,c-=188;continue}u--,c--}},io=function(e,t){if(e.audio&&e.audio.length){var i=t;(void 0===i||isNaN(i))&&(i=e.audio[0].dts),e.audio.forEach(function(e){e.dts=F(e.dts,i),e.pts=F(e.pts,i),e.dtsTime=e.dts/ii,e.ptsTime=e.pts/ii})}if(e.video&&e.video.length){var s=t;if((void 0===s||isNaN(s))&&(s=e.video[0].dts),e.video.forEach(function(e){e.dts=F(e.dts,s),e.pts=F(e.pts,s),e.dtsTime=e.dts/ii,e.ptsTime=e.pts/ii}),e.firstKeyFrame){var r=e.firstKeyFrame;r.dts=F(r.dts,s),r.pts=F(r.pts,s),r.dtsTime=r.dts/ii,r.ptsTime=r.pts/ii}}},il=function(e){for(var t,i=!1,s=0,r=null,n=null,a=0,o=0;e.length-o>=3;){switch(it.aac.parseType(e,o)){case"timed-metadata":if(e.length-o<10||(a=it.aac.parseId3TagSize(e,o))>e.length){i=!0;break}null===n&&(t=e.subarray(o,o+a),n=it.aac.parseAacTimestamp(t)),o+=a;break;case"audio":if(e.length-o<7||(a=it.aac.parseAdtsSize(e,o))>e.length){i=!0;break}null===r&&(t=e.subarray(o,o+a),r=it.aac.parseSampleRate(t)),s++,o+=a;break;default:o++}if(i)return null}if(null===r||null===n)return null;var l=ii/r;return{audio:[{type:"audio",dts:n,pts:n},{type:"audio",dts:n+1024*s*l,pts:n+1024*s*l}]}},ih=function(e){var t={pid:null,table:null},i={};for(var s in is(e,t),t.table)if(t.table.hasOwnProperty(s))switch(t.table[s]){case N.H264_STREAM_TYPE:i.video=[],ia(e,t,i),0===i.video.length&&delete i.video;break;case N.ADTS_STREAM_TYPE:i.audio=[],ir(e,t,i),0===i.audio.length&&delete i.audio}return i},id=function(e,t){var i;return(i=it.aac.isLikelyAacData(e)?il(e):ih(e))&&(i.audio||i.video)?(io(i,t),i):null};let iu=function(e,t){t.on("data",function(t){let i=t.initSegment;t.initSegment={data:i.buffer,byteOffset:i.byteOffset,byteLength:i.byteLength};let s=t.data;t.data=s.buffer,e.postMessage({action:"data",segment:t,byteOffset:s.byteOffset,byteLength:s.byteLength},[t.data])}),t.on("done",function(t){e.postMessage({action:"done"})}),t.on("gopInfo",function(t){e.postMessage({action:"gopInfo",gopInfo:t})}),t.on("videoSegmentTimingInfo",function(t){let i={start:{decode:y.videoTsToSeconds(t.start.dts),presentation:y.videoTsToSeconds(t.start.pts)},end:{decode:y.videoTsToSeconds(t.end.dts),presentation:y.videoTsToSeconds(t.end.pts)},baseMediaDecodeTime:y.videoTsToSeconds(t.baseMediaDecodeTime)};t.prependedContentDuration&&(i.prependedContentDuration=y.videoTsToSeconds(t.prependedContentDuration)),e.postMessage({action:"videoSegmentTimingInfo",videoSegmentTimingInfo:i})}),t.on("audioSegmentTimingInfo",function(t){let i={start:{decode:y.videoTsToSeconds(t.start.dts),presentation:y.videoTsToSeconds(t.start.pts)},end:{decode:y.videoTsToSeconds(t.end.dts),presentation:y.videoTsToSeconds(t.end.pts)},baseMediaDecodeTime:y.videoTsToSeconds(t.baseMediaDecodeTime)};t.prependedContentDuration&&(i.prependedContentDuration=y.videoTsToSeconds(t.prependedContentDuration)),e.postMessage({action:"audioSegmentTimingInfo",audioSegmentTimingInfo:i})}),t.on("id3Frame",function(t){e.postMessage({action:"id3Frame",id3Frame:t})}),t.on("caption",function(t){e.postMessage({action:"caption",caption:t})}),t.on("trackinfo",function(t){e.postMessage({action:"trackinfo",trackInfo:t})}),t.on("audioTimingInfo",function(t){e.postMessage({action:"audioTimingInfo",audioTimingInfo:{start:y.videoTsToSeconds(t.start),end:y.videoTsToSeconds(t.end)}})}),t.on("videoTimingInfo",function(t){e.postMessage({action:"videoTimingInfo",videoTimingInfo:{start:y.videoTsToSeconds(t.start),end:y.videoTsToSeconds(t.end)}})}),t.on("log",function(t){e.postMessage({action:"log",log:t})})};class ic{constructor(e,t){this.options=t||{},this.self=e,this.init()}init(){this.transmuxer&&this.transmuxer.dispose(),this.transmuxer=new tS(this.options),iu(this.self,this.transmuxer)}pushMp4Captions(e){this.captionParser||(this.captionParser=new t1,this.captionParser.init());let t=new Uint8Array(e.data,e.byteOffset,e.byteLength),i=this.captionParser.parse(t,e.trackIds,e.timescales);this.self.postMessage({action:"mp4Captions",captions:i&&i.captions||[],logs:i&&i.logs||[],data:t.buffer},[t.buffer])}initMp4WebVttParser(e){this.webVttParser||(this.webVttParser=new t3);let t=new Uint8Array(e.data,e.byteOffset,e.byteLength);this.webVttParser.init(t)}getMp4WebVttText(e){this.webVttParser||(this.webVttParser=new t3);let t=new Uint8Array(e.data,e.byteOffset,e.byteLength),i=this.webVttParser.parseSegment(t);this.self.postMessage({action:"getMp4WebVttText",mp4VttCues:i||[],data:t.buffer},[t.buffer])}probeMp4StartTime({timescales:e,data:t}){let i=tV.startTime(e,t);this.self.postMessage({action:"probeMp4StartTime",startTime:i,data:t},[t.buffer])}probeMp4Tracks({data:e}){let t=tV.tracks(e);this.self.postMessage({action:"probeMp4Tracks",tracks:t,data:e},[e.buffer])}probeEmsgID3({data:e,offset:t}){let i=tV.getEmsgID3(e,t);this.self.postMessage({action:"probeEmsgID3",id3Frames:i,emsgData:e},[e.buffer])}probeTs({data:e,baseStartTime:t}){let i=id(e,"number"!=typeof t||isNaN(t)?void 0:t*y.ONE_SECOND_IN_TS),s=null;i&&((s={hasVideo:i.video&&2===i.video.length||!1,hasAudio:i.audio&&2===i.audio.length||!1}).hasVideo&&(s.videoStart=i.video[0].ptsTime),s.hasAudio&&(s.audioStart=i.audio[0].ptsTime)),this.self.postMessage({action:"probeTs",result:s,data:e},[e.buffer])}clearAllMp4Captions(){this.captionParser&&this.captionParser.clearAllCaptions()}clearParsedMp4Captions(){this.captionParser&&this.captionParser.clearParsedCaptions()}push(e){let t=new Uint8Array(e.data,e.byteOffset,e.byteLength);this.transmuxer.push(t)}reset(){this.transmuxer.reset()}setTimestampOffset(e){let t=e.timestampOffset||0;this.transmuxer.setBaseMediaDecodeTime(Math.round(y.secondsToVideoTs(t)))}setAudioAppendStart(e){this.transmuxer.setAudioAppendStart(Math.ceil(y.secondsToVideoTs(e.appendStart)))}setRemux(e){this.transmuxer.setRemux(e.remux)}flush(e){this.transmuxer.flush(),self.postMessage({action:"done",type:"transmuxed"})}endTimeline(){this.transmuxer.endTimeline(),self.postMessage({action:"endedtimeline",type:"transmuxed"})}alignGopsWith(e){this.transmuxer.alignGopsWith(e.gopsToAlignWith.slice())}}self.onmessage=function(e){if("init"===e.data.action&&e.data.options){this.messageHandlers=new ic(self,e.data.options);return}this.messageHandlers||(this.messageHandlers=new ic(self)),e.data&&e.data.action&&"init"!==e.data.action&&this.messageHandlers[e.data.action]&&this.messageHandlers[e.data.action](e.data)}})));let ai=(e,t,i)=>{let{type:s,initSegment:r,captions:n,captionStreams:a,metadata:o,videoFrameDtsTime:l,videoFramePtsTime:h}=e.data.segment;t.buffer.push({captions:n,captionStreams:a,metadata:o});let d=e.data.segment.boxes||{data:e.data.segment.data},u={type:s,data:new Uint8Array(d.data,d.data.byteOffset,d.data.byteLength),initSegment:new Uint8Array(r.data,r.byteOffset,r.byteLength)};void 0!==l&&(u.videoFrameDtsTime=l),void 0!==h&&(u.videoFramePtsTime=h),i(u)},as=({transmuxedData:e,callback:t})=>{e.buffer=[],t(e)},ar=(e,t)=>{t.gopInfo=e.data.gopInfo},an=e=>{let{transmuxer:t,bytes:i,audioAppendStart:s,gopsToAlignWith:r,remux:n,onData:a,onTrackInfo:o,onAudioTimingInfo:l,onVideoTimingInfo:h,onVideoSegmentTimingInfo:d,onAudioSegmentTimingInfo:u,onId3:c,onCaptions:p,onDone:m,onEndedTimeline:g,onTransmuxerLog:f,isEndOfTimeline:_,segment:y,triggerSegmentEventFn:v}=e,b={buffer:[]},T=_;if(t.onmessage=i=>{if(t.currentTransmux===e)"data"===i.data.action&&ai(i,b,a),"trackinfo"===i.data.action&&o(i.data.trackInfo),"gopInfo"===i.data.action&&ar(i,b),"audioTimingInfo"===i.data.action&&l(i.data.audioTimingInfo),"videoTimingInfo"===i.data.action&&h(i.data.videoTimingInfo),"videoSegmentTimingInfo"===i.data.action&&d(i.data.videoSegmentTimingInfo),"audioSegmentTimingInfo"===i.data.action&&u(i.data.audioSegmentTimingInfo),"id3Frame"===i.data.action&&c([i.data.id3Frame],i.data.id3Frame.dispatchType),"caption"===i.data.action&&p(i.data.caption),"endedtimeline"===i.data.action&&(T=!1,g()),"log"===i.data.action&&f(i.data.log),"transmuxed"===i.data.type&&!T&&(t.onmessage=null,as({transmuxedData:b,callback:m}),aa(t))},t.onerror=()=>{m(null,{message:"Received an error message from the transmuxer worker",metadata:{errorType:rk.Error.StreamingFailedToTransmuxSegment,segmentInfo:om({segment:y})}})},s&&t.postMessage({action:"setAudioAppendStart",appendStart:s}),Array.isArray(r)&&t.postMessage({action:"alignGopsWith",gopsToAlignWith:r}),void 0!==n&&t.postMessage({action:"setRemux",remux:n}),i.byteLength){let e=i instanceof ArrayBuffer?i:i.buffer,s=i instanceof ArrayBuffer?0:i.byteOffset;v({type:"segmenttransmuxingstart",segment:y}),t.postMessage({action:"push",data:e,byteOffset:s,byteLength:i.byteLength},[e])}_&&t.postMessage({action:"endTimeline"}),t.postMessage({action:"flush"})},aa=e=>{e.currentTransmux=null,e.transmuxQueue.length&&(e.currentTransmux=e.transmuxQueue.shift(),"function"==typeof e.currentTransmux?e.currentTransmux():an(e.currentTransmux))},ao=(e,t)=>{e.postMessage({action:t}),aa(e)},al=(e,t)=>{if(!t.currentTransmux){t.currentTransmux=e,ao(t,e);return}t.transmuxQueue.push(ao.bind(null,t,e))},ah=e=>{if(!e.transmuxer.currentTransmux){e.transmuxer.currentTransmux=e,an(e);return}e.transmuxer.transmuxQueue.push(e)};var ad={reset:e=>{al("reset",e)},createTransmuxer:e=>{let t=new at;t.currentTransmux=null,t.transmuxQueue=[];let i=t.terminate;return t.terminate=()=>(t.currentTransmux=null,t.transmuxQueue.length=0,i.call(t)),t.postMessage({action:"init",options:e}),t}};let au=function(e){let t=e.transmuxer,i=e.endAction||e.action,s=e.callback,r=(0,_.A)({},e,{endAction:null,transmuxer:null,callback:null}),n=r=>{r.data.action===i&&(t.removeEventListener("message",n),r.data.data&&(r.data.data=new Uint8Array(r.data.data,e.byteOffset||0,e.byteLength||r.data.data.byteLength),e.data&&(e.data=r.data.data)),s(r.data))};if(t.addEventListener("message",n),e.data){let i=e.data instanceof ArrayBuffer;r.byteOffset=i?0:e.data.byteOffset,r.byteLength=e.data.byteLength;let s=[i?e.data:e.data.buffer];t.postMessage(r,s)}else t.postMessage(r)},ac={FAILURE:2,TIMEOUT:-101,ABORTED:-102},ap="wvtt",am=e=>{e.forEach(e=>{e.abort()})},ag=e=>({bandwidth:e.bandwidth,bytesReceived:e.bytesReceived||0,roundTripTime:e.roundTripTime||0}),af=e=>{let t=e.target,i={bandwidth:1/0,bytesReceived:0,roundTripTime:Date.now()-t.requestTime||0};return i.bytesReceived=e.loaded,i.bandwidth=Math.floor(i.bytesReceived/i.roundTripTime*8e3),i},a_=(e,t)=>{let{requestType:i}=t,s=np({requestType:i,request:t,error:e});return t.timedout?{status:t.status,message:"HLS request timed-out at URL: "+t.uri,code:ac.TIMEOUT,xhr:t,metadata:s}:t.aborted?{status:t.status,message:"HLS request aborted at URL: "+t.uri,code:ac.ABORTED,xhr:t,metadata:s}:e?{status:t.status,message:"HLS request errored at URL: "+t.uri,code:ac.FAILURE,xhr:t,metadata:s}:"arraybuffer"===t.responseType&&0===t.response.byteLength?{status:t.status,message:"Empty HLS response at URL: "+t.uri,code:ac.FAILURE,xhr:t,metadata:s}:null},ay=(e,t,i,s)=>(r,n)=>{let a=n.response,o=a_(r,n);if(o)return i(o,e);if(16!==a.byteLength)return i({status:n.status,message:"Invalid HLS key at URL: "+n.uri,code:ac.FAILURE,xhr:n},e);let l=new DataView(a),h=new Uint32Array([l.getUint32(0),l.getUint32(4),l.getUint32(8),l.getUint32(12)]);for(let e=0;e{t===ap&&e.transmuxer.postMessage({action:"initMp4WebVttParser",data:e.map.bytes})},ab=(e,t,i)=>{t===ap&&au({action:"getMp4WebVttText",data:e.bytes,transmuxer:e.transmuxer,callback:({data:t,mp4VttCues:s})=>{e.bytes=t,i(null,e,{mp4VttCues:s})}})},aT=(e,t)=>{let i=(0,x.ne)(e.map.bytes);if("mp4"!==i){let s=e.map.resolvedUri||e.map.uri,r=i||"unknown";return t({internal:!0,message:`Found unsupported ${r} container for initialization segment at URL: ${s}`,code:ac.FAILURE,metadata:{mediaType:r}})}au({action:"probeMp4Tracks",data:e.map.bytes,transmuxer:e.transmuxer,callback:({tracks:i,data:s})=>(e.map.bytes=s,i.forEach(function(t){e.map.tracks=e.map.tracks||{},!e.map.tracks[t.type]&&(e.map.tracks[t.type]=t,"number"==typeof t.id&&t.timescale&&(e.map.timescales=e.map.timescales||{},e.map.timescales[t.id]=t.timescale),"text"===t.type&&av(e,t.codec))}),t(null))})},aS=({segment:e,finishProcessingFn:t,triggerSegmentEventFn:i})=>(s,r)=>{let n=a_(s,r);if(n)return t(n,e);let a=new Uint8Array(r.response);if(i({type:"segmentloaded",segment:e}),e.map.key)return e.map.encryptedBytes=a,t(null,e);e.map.bytes=a,aT(e,function(i){if(i)return i.xhr=r,i.status=r.status,t(i,e);t(null,e)})},ak=({segment:e,finishProcessingFn:t,responseType:i,triggerSegmentEventFn:s})=>(r,n)=>{let a=a_(r,n);if(a)return t(a,e);s({type:"segmentloaded",segment:e});let o="arraybuffer"!==i&&n.responseText?n5(n.responseText.substring(e.lastReachedChar||0)):n.response;return e.stats=ag(n),e.key?e.encryptedBytes=new Uint8Array(o):e.bytes=new Uint8Array(o),t(null,e)},aC=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d,doneFn:u,onTransmuxerLog:c,triggerSegmentEventFn:p})=>{let m=e.map&&e.map.tracks||{},g=!!(m.audio&&m.video),f=s.bind(null,e,"audio","start"),_=s.bind(null,e,"audio","end"),y=s.bind(null,e,"video","start"),v=s.bind(null,e,"video","end"),b=()=>ah({bytes:t,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,remux:g,onData:t=>{t.type="combined"===t.type?"video":t.type,d(e,t)},onTrackInfo:t=>{i&&(g&&(t.isMuxed=!0),i(e,t))},onAudioTimingInfo:e=>{f&&void 0!==e.start&&(f(e.start),f=null),_&&void 0!==e.end&&_(e.end)},onVideoTimingInfo:e=>{y&&void 0!==e.start&&(y(e.start),y=null),v&&void 0!==e.end&&v(e.end)},onVideoSegmentTimingInfo:t=>{p({type:"segmenttransmuxingtiminginfoavailable",segment:e,timingInfo:{pts:{start:t.start.presentation,end:t.end.presentation},dts:{start:t.start.decode,end:t.end.decode}}}),r(t)},onAudioSegmentTimingInfo:t=>{p({type:"segmenttransmuxingtiminginfoavailable",segment:e,timingInfo:{pts:{start:t.start.pts,end:t.end.pts},dts:{start:t.start.dts,end:t.end.dts}}}),n(t)},onId3:(t,i)=>{a(e,t,i)},onCaptions:t=>{o(e,[t])},isEndOfTimeline:l,onEndedTimeline:()=>{h()},onTransmuxerLog:c,onDone:(t,i)=>{u&&(t.type="combined"===t.type?"video":t.type,p({type:"segmenttransmuxingcomplete",segment:e}),u(i,e,t))},segment:e,triggerSegmentEventFn:p});au({action:"probeTs",transmuxer:e.transmuxer,data:t,baseStartTime:e.baseStartTime,callback:s=>{e.bytes=t=s.data;let r=s.result;r&&(i(e,{hasAudio:r.hasAudio,hasVideo:r.hasVideo,isMuxed:g}),i=null),b()}})},aw=({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d,doneFn:u,onTransmuxerLog:c,triggerSegmentEventFn:p})=>{let m=new Uint8Array(t);if((0,x.J2)(m)){e.isFmp4=!0;let{tracks:r}=e.map;if(r.text&&(!r.audio||!r.video)){d(e,{data:m,type:"text"}),ab(e,r.text.codec,u);return}let n={isFmp4:!0,hasVideo:!!r.video,hasAudio:!!r.audio};r.audio&&r.audio.codec&&"enca"!==r.audio.codec&&(n.audioCodec=r.audio.codec),r.video&&r.video.codec&&"encv"!==r.video.codec&&(n.videoCodec=r.video.codec),r.video&&r.audio&&(n.isMuxed=!0),i(e,n);let l=(t,i)=>{d(e,{data:m,type:n.hasAudio&&!n.isMuxed?"audio":"video"}),i&&i.length&&a(e,i),t&&t.length&&o(e,t),u(null,e,{})};au({action:"probeMp4StartTime",timescales:e.map.timescales,data:m,transmuxer:e.transmuxer,callback:({data:i,startTime:a})=>{t=i.buffer,e.bytes=m=i,n.hasAudio&&!n.isMuxed&&s(e,"audio","start",a),n.hasVideo&&s(e,"video","start",a),au({action:"probeEmsgID3",data:m,transmuxer:e.transmuxer,offset:a,callback:({emsgData:i,id3Frames:s})=>{if(t=i.buffer,e.bytes=m=i,!r.video||!i.byteLength||!e.transmuxer){l(void 0,s);return}au({action:"pushMp4Captions",endAction:"mp4Captions",transmuxer:e.transmuxer,data:m,timescales:e.map.timescales,trackIds:[r.video.id],callback:i=>{t=i.data.buffer,e.bytes=m=i.data,i.logs.forEach(function(e){c(rD(e,{stream:"mp4CaptionParser"}))}),l(i.captions,s)}})}})}});return}if(!e.transmuxer){u(null,e,{});return}if(void 0===e.container&&(e.container=(0,x.ne)(m)),"ts"!==e.container&&"aac"!==e.container){i(e,{hasAudio:!1,hasVideo:!1}),u(null,e,{});return}aC({segment:e,bytes:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d,doneFn:u,onTransmuxerLog:c,triggerSegmentEventFn:p})},aE=function({id:e,key:t,encryptedBytes:i,decryptionWorker:s,segment:r,doneFn:n},a){let o;let l=t=>{if(t.data.source===e){s.removeEventListener("message",l);let e=t.data.decrypted;a(new Uint8Array(e.bytes,e.byteOffset,e.byteLength))}};s.onerror=()=>{let e="An error occurred in the decryption worker",t=om({segment:r});n({message:e,metadata:{error:Error(e),errorType:rk.Error.StreamingFailedToDecryptSegment,segmentInfo:t,keyInfo:{uri:r.key.resolvedUri||r.map.key.resolvedUri}}},r)},s.addEventListener("message",l),o=t.bytes.slice?t.bytes.slice():new Uint32Array(Array.prototype.slice.call(t.bytes)),s.postMessage(nO({source:e,encrypted:i,key:o,iv:t.iv}),[i.buffer,o.buffer])},ax=({decryptionWorker:e,segment:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d,doneFn:u,onTransmuxerLog:c,triggerSegmentEventFn:p})=>{p({type:"segmentdecryptionstart"}),aE({id:t.requestId,key:t.key,encryptedBytes:t.encryptedBytes,decryptionWorker:e,segment:t,doneFn:u},e=>{t.bytes=e,p({type:"segmentdecryptioncomplete",segment:t}),aw({segment:t,bytes:t.bytes,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d,doneFn:u,onTransmuxerLog:c,triggerSegmentEventFn:p})})},aI=({activeXhrs:e,decryptionWorker:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d,doneFn:u,onTransmuxerLog:c,triggerSegmentEventFn:p})=>{let m=0,g=!1;return(f,_)=>{if(!g){if(f)return g=!0,am(e),u(f,_);if((m+=1)===e.length){let m=function(){if(_.encryptedBytes)return ax({decryptionWorker:t,segment:_,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d,doneFn:u,onTransmuxerLog:c,triggerSegmentEventFn:p});aw({segment:_,bytes:_.bytes,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d,doneFn:u,onTransmuxerLog:c,triggerSegmentEventFn:p})};if(_.endOfAllRequests=Date.now(),_.map&&_.map.encryptedBytes&&!_.map.bytes)return p({type:"segmentdecryptionstart",segment:_}),aE({decryptionWorker:t,id:_.requestId+"-init",encryptedBytes:_.map.encryptedBytes,key:_.map.key,segment:_,doneFn:u},t=>{_.map.bytes=t,p({type:"segmentdecryptioncomplete",segment:_}),aT(_,t=>{if(t)return am(e),u(t,_);m()})});m()}}}},aP=({loadendState:e,abortFn:t})=>i=>{i.target.aborted&&t&&!e.calledAbortFn&&(t(),e.calledAbortFn=!0)},aA=({segment:e,progressFn:t,trackInfoFn:i,timingInfoFn:s,videoSegmentTimingInfoFn:r,audioSegmentTimingInfoFn:n,id3Fn:a,captionsFn:o,isEndOfTimeline:l,endedTimelineFn:h,dataFn:d})=>i=>{if(!i.target.aborted)return e.stats=rD(e.stats,af(i)),!e.stats.firstBytesReceivedAt&&e.stats.bytesReceived&&(e.stats.firstBytesReceivedAt=Date.now()),t(i,e)},aL=({xhr:e,xhrOptions:t,decryptionWorker:i,segment:s,abortFn:r,progressFn:n,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:h,id3Fn:d,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m,doneFn:g,onTransmuxerLog:f,triggerSegmentEventFn:_})=>{let y=[],v=aI({activeXhrs:y,decryptionWorker:i,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:h,id3Fn:d,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m,doneFn:g,onTransmuxerLog:f,triggerSegmentEventFn:_});if(s.key&&!s.key.bytes){let i=[s.key];s.map&&!s.map.bytes&&s.map.key&&s.map.key.resolvedUri===s.key.resolvedUri&&i.push(s.map.key);let r=rD(t,{uri:s.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),n=ay(s,i,v,_),a={uri:s.key.resolvedUri};_({type:"segmentkeyloadstart",segment:s,keyInfo:a});let o=e(r,n);y.push(o)}if(s.map&&!s.map.bytes){if(s.map.key&&(!s.key||s.key.resolvedUri!==s.map.key.resolvedUri)){let i=rD(t,{uri:s.map.key.resolvedUri,responseType:"arraybuffer",requestType:"segment-key"}),r=ay(s,[s.map.key],v,_),n={uri:s.map.key.resolvedUri};_({type:"segmentkeyloadstart",segment:s,keyInfo:n});let a=e(i,r);y.push(a)}let i=rD(t,{uri:s.map.resolvedUri,responseType:"arraybuffer",headers:nA(s.map),requestType:"segment-media-initialization"}),r=aS({segment:s,finishProcessingFn:v,triggerSegmentEventFn:_});_({type:"segmentloadstart",segment:s});let n=e(i,r);y.push(n)}let b=rD(t,{uri:s.part&&s.part.resolvedUri||s.resolvedUri,responseType:"arraybuffer",headers:nA(s),requestType:"segment"}),T=ak({segment:s,finishProcessingFn:v,responseType:b.responseType,triggerSegmentEventFn:_});_({type:"segmentloadstart",segment:s});let S=e(b,T);S.addEventListener("progress",aA({segment:s,progressFn:n,trackInfoFn:a,timingInfoFn:o,videoSegmentTimingInfoFn:l,audioSegmentTimingInfoFn:h,id3Fn:d,captionsFn:u,isEndOfTimeline:c,endedTimelineFn:p,dataFn:m})),y.push(S);let k={};return y.forEach(e=>{e.addEventListener("loadend",aP({loadendState:k,abortFn:r}))}),()=>am(y)},aD=rL("CodecUtils"),aO=function(e){let t=e.attributes||{};if(t.CODECS)return(0,b.tB)(t.CODECS)},aM=(e,t)=>{let i=t.attributes||{};return e&&e.mediaGroups&&e.mediaGroups.AUDIO&&i.AUDIO&&e.mediaGroups.AUDIO[i.AUDIO]},aU=(e,t)=>{if(!aM(e,t))return!0;let i=t.attributes||{},s=e.mediaGroups.AUDIO[i.AUDIO];for(let e in s)if(!s[e].uri&&!s[e].playlists)return!0;return!1},aR=function(e){let t={};return e.forEach(({mediaType:e,type:i,details:s})=>{t[e]=t[e]||[],t[e].push((0,b.Et)(`${i}${s}`))}),Object.keys(t).forEach(function(e){if(t[e].length>1){aD(`multiple ${e} codecs found as attributes: ${t[e].join(", ")}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`),t[e]=null;return}t[e]=t[e][0]}),t},aB=function(e){let t=0;return e.audio&&t++,e.video&&t++,t},aN=function(e,t){let i=t.attributes||{},s=aR(aO(t)||[]);if(aM(e,t)&&!s.audio&&!aU(e,t)){let t=aR((0,b.BX)(e,i.AUDIO)||[]);t.audio&&(s.audio=t.audio)}return s},aj=rL("PlaylistSelector"),aF=function(e){if(!e||!e.playlist)return;let t=e.playlist;return JSON.stringify({id:t.id,bandwidth:e.bandwidth,width:e.width,height:e.height,codecs:t.attributes&&t.attributes.CODECS||""})},a$=function(e,t){if(!e)return"";let i=d().getComputedStyle(e);return i?i[t]:""},aq=function(e,t){let i=e.slice();e.sort(function(e,s){let r=t(e,s);return 0===r?i.indexOf(e)-i.indexOf(s):r})},aH=function(e,t){let i,s;return e.attributes.BANDWIDTH&&(i=e.attributes.BANDWIDTH),i=i||d().Number.MAX_VALUE,t.attributes.BANDWIDTH&&(s=t.attributes.BANDWIDTH),i-(s=s||d().Number.MAX_VALUE)},aV=function(e,t,i,s,r,n){let a,o,l,h;if(!e)return;let u={bandwidth:t,width:i,height:s,limitRenditionByPlayerDimensions:r},c=e.playlists;nt.isAudioOnly(e)&&(c=n.getAudioTrackPlaylists_(),u.audioOnly=!0);let p=c.map(e=>{let t;let i=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width,s=e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height;return{bandwidth:e.attributes&&e.attributes.BANDWIDTH||d().Number.MAX_VALUE,width:i,height:s,playlist:e}});aq(p,(e,t)=>e.bandwidth-t.bandwidth);let m=(p=p.filter(e=>!nt.isIncompatible(e.playlist))).filter(e=>nt.isEnabled(e.playlist));m.length||(m=p.filter(e=>!nt.isDisabled(e.playlist)));let g=m.filter(e=>e.bandwidth*n8.BANDWIDTH_VARIANCEe.bandwidth===f.bandwidth)[0];if(!1===r){let e=_||m[0]||p[0];if(e&&e.playlist){let t="sortedPlaylistReps";return _&&(t="bandwidthBestRep"),m[0]&&(t="enabledPlaylistReps"),aj(`choosing ${aF(e)} using ${t} with options`,u),e.playlist}return aj("could not choose a playlist with options",u),null}let y=g.filter(e=>e.width&&e.height);aq(y,(e,t)=>e.width-t.width);let v=y.filter(e=>e.width===i&&e.height===s);f=v[v.length-1];let b=v.filter(e=>e.bandwidth===f.bandwidth)[0];if(b||(f=(o=(a=y.filter(e=>e.width>i||e.height>s)).filter(e=>e.width===a[0].width&&e.height===a[0].height))[o.length-1],l=o.filter(e=>e.bandwidth===f.bandwidth)[0]),n.leastPixelDiffSelector){let e=y.map(e=>(e.pixelDiff=Math.abs(e.width-i)+Math.abs(e.height-s),e));aq(e,(e,t)=>e.pixelDiff===t.pixelDiff?t.bandwidth-e.bandwidth:e.pixelDiff-t.pixelDiff),h=e[0]}let T=h||l||b||_||m[0]||p[0];if(T&&T.playlist){let e="sortedPlaylistReps";return h?e="leastPixelDiffRep":l?e="resolutionPlusOneRep":b?e="resolutionBestRep":_?e="bandwidthBestRep":m[0]&&(e="enabledPlaylistReps"),aj(`choosing ${aF(T)} using ${e} with options`,u),T.playlist}return aj("could not choose a playlist with options",u),null},az=function(){let e=this.useDevicePixelRatio&&d().devicePixelRatio||1;return isNaN(this.customPixelRatio)||(e=this.customPixelRatio),aV(this.playlists.main,this.systemBandwidth,parseInt(a$(this.tech_.el(),"width"),10)*e,parseInt(a$(this.tech_.el(),"height"),10)*e,this.limitRenditionByPlayerDimensions,this.playlistController_)},aW=function(e){let{main:t,currentTime:i,bandwidth:s,duration:r,segmentDuration:n,timeUntilRebuffer:a,currentTimeline:o,syncController:l}=e,h=t.playlists.filter(e=>!nt.isIncompatible(e)),d=h.filter(nt.isEnabled);d.length||(d=h.filter(e=>!nt.isDisabled(e)));let u=d.filter(nt.hasAttribute.bind(null,"BANDWIDTH")).map(e=>{let t=l.getSyncPoint(e,r,o,i),h=nt.estimateSegmentRequestTime(n,s,e);return{playlist:e,rebufferingImpact:h*(t?1:2)-a}}),c=u.filter(e=>e.rebufferingImpact<=0);return(aq(c,(e,t)=>aH(t.playlist,e.playlist)),c.length)?c[0]:(aq(u,(e,t)=>e.rebufferingImpact-t.rebufferingImpact),u[0]||null)},aG=e=>{let t,i=0;return e.bytes&&(t=new Uint8Array(e.bytes),e.segments.forEach(e=>{t.set(e,i),i+=e.byteLength})),t};function aK(e){try{return new URL(e).pathname.split("/").slice(-2).join("/")}catch(e){return""}}let aQ=function(e,t,i){if(!e[i]){t.trigger({type:"usage",name:"vhs-608"});let s=i;/^cc708_/.test(i)&&(s="SERVICE"+i.split("_")[1]);let r=t.textTracks().getTrackById(s);if(r)e[i]=r;else{let r=t.options_.vhs&&t.options_.vhs.captionServices||{},n=i,a=i,o=!1,l=r[s];l&&(n=l.label,a=l.language,o=l.default),e[i]=t.addRemoteTextTrack({kind:"captions",id:s,default:o,label:n,language:a},!1).track}}},aY=function({inbandTextTracks:e,captionArray:t,timestampOffset:i}){if(!t)return;let s=d().WebKitDataCue||d().VTTCue;t.forEach(t=>{let r=t.stream;t.content?t.content.forEach(n=>{let a=new s(t.startTime+i,t.endTime+i,n.text);a.line=n.line,a.align="left",a.position=n.position,a.positionAlign="line-left",e[r].addCue(a)}):e[r].addCue(new s(t.startTime+i,t.endTime+i,t.text))})},aX=function(e){Object.defineProperties(e.frame,{id:{get:()=>(rk.log.warn("cue.frame.id is deprecated. Use cue.value.key instead."),e.value.key)},value:{get:()=>(rk.log.warn("cue.frame.value is deprecated. Use cue.value.data instead."),e.value.data)},privateData:{get:()=>(rk.log.warn("cue.frame.privateData is deprecated. Use cue.value.data instead."),e.value.data)}})},aJ=({inbandTextTracks:e,metadataArray:t,timestampOffset:i,videoDuration:s})=>{if(!t)return;let r=d().WebKitDataCue||d().VTTCue,n=e.metadataTrack_;if(!n||(t.forEach(e=>{let t=e.cueTime+i;!("number"!=typeof t||d().isNaN(t))&&!(t<0)&&t<1/0&&e.frames&&e.frames.length&&e.frames.forEach(e=>{let i=new r(t,t,e.value||e.url||e.data||"");i.frame=e,i.value=e,aX(i),n.addCue(i)})}),!n.cues||!n.cues.length))return;let a=n.cues,o=[];for(let e=0;e{let i=e[t.startTime]||[];return i.push(t),e[t.startTime]=i,e},{}),h=Object.keys(l).sort((e,t)=>Number(e)-Number(t));h.forEach((e,t)=>{let i=l[e],r=isFinite(s)?s:e,n=Number(h[t+1])||r;i.forEach(e=>{e.endTime=n})})},aZ={id:"ID",class:"CLASS",startDate:"START-DATE",duration:"DURATION",endDate:"END-DATE",endOnNext:"END-ON-NEXT",plannedDuration:"PLANNED-DURATION",scte35Out:"SCTE35-OUT",scte35In:"SCTE35-IN"},a0=new Set(["id","class","startDate","duration","endDate","endOnNext","startTime","endTime","processDateRange"]),a1=({inbandTextTracks:e,dateRanges:t})=>{let i=e.metadataTrack_;if(!i)return;let s=d().WebKitDataCue||d().VTTCue;t.forEach(e=>{for(let t of Object.keys(e)){if(a0.has(t))continue;let r=new s(e.startTime,e.endTime,"");r.id=e.id,r.type="com.apple.quicktime.HLS",r.value={key:aZ[t],data:e[t]},("scte35Out"===t||"scte35In"===t)&&(r.value.data=new Uint8Array(r.value.data.match(/[\da-f]{2}/gi)).buffer),i.addCue(r)}e.processDateRange()})},a2=(e,t,i)=>{!e.metadataTrack_&&(e.metadataTrack_=i.addRemoteTextTrack({kind:"metadata",label:"Timed Metadata"},!1).track,rk.browser.IS_ANY_SAFARI||(e.metadataTrack_.inBandMetadataTrackDispatchType=t))},a4=function(e,t,i){let s,r;if(i&&i.cues)for(s=i.cues.length;s--;)(r=i.cues[s]).startTime>=e&&r.endTime<=t&&i.removeCue(r)},a8=function(e){let t=e.cues;if(!t)return;let i={};for(let s=t.length-1;s>=0;s--){let r=t[s],n=`${r.startTime}-${r.endTime}-${r.text}`;i[n]?e.removeCue(r):i[n]=r}},a5=(e,t,i)=>{let s;if(null==t||!e.length)return[];let r=Math.ceil((t-i+3)*I.ONE_SECOND_IN_TS);for(s=0;sr);s++);return e.slice(s)},a3=(e,t,i)=>{if(!t.length)return e;if(i)return t.slice();let s=t[0].pts,r=0;for(;r=s);r++);return e.slice(0,r).concat(t)},a6=(e,t,i,s)=>{let r=Math.ceil((t-s)*I.ONE_SECOND_IN_TS),n=Math.ceil((i-s)*I.ONE_SECOND_IN_TS),a=e.slice(),o=e.length;for(;o--&&!(e[o].pts<=n););if(-1===o)return a;let l=o+1;for(;l--&&!(e[l].pts<=r););return l=Math.max(l,0),a.splice(l,o-l+1),a},a7=function(e,t){if(!e&&!t||!e&&t||e&&!t)return!1;if(e===t)return!0;let i=Object.keys(e).sort(),s=Object.keys(t).sort();if(i.length!==s.length)return!1;for(let r=0;ri))return n}return 0===s.length?0:s[s.length-1]},oe=e=>"number"==typeof e&&isFinite(e),ot=1/60,oi=(e,t,i)=>"main"===e&&t&&i?i.hasAudio||i.hasVideo?t.hasVideo&&!i.hasVideo?"Only audio found in segment when we expected video. We can't switch to audio only from a stream that had video. To get rid of this message, please add codec information to the manifest.":!t.hasVideo&&i.hasVideo?"Video found in segment when we expected only audio. We can't switch to a stream with video from an audio only stream. To get rid of this message, please add codec information to the manifest.":null:"Neither audio nor video found in segment.":null,os=(e,t,i)=>{let s=t-n8.BACK_BUFFER_LENGTH;return e.length&&(s=Math.max(s,e.start(0))),Math.min(t-i,s)},or=e=>{let{startOfSegment:t,duration:i,segment:s,part:r,playlist:{mediaSequence:n,id:a,segments:o=[]},mediaIndex:l,partIndex:h,timeline:d}=e,u=o.length-1,c="mediaIndex/partIndex increment";e.getMediaInfoForTime?c=`getMediaInfoForTime (${e.getMediaInfoForTime})`:e.isSyncRequest&&(c="getSyncSegmentCandidate (isSyncRequest)"),e.independent&&(c+=` with independent ${e.independent}`);let p="number"==typeof h,m=e.segment.uri?"segment":"pre-segment",g=p?rQ({preloadSegment:s})-1:0;return`${m} [${n+l}/${n+u}]`+(p?` part [${h}/${g}]`:"")+` segment start/end [${s.start} => ${s.end}]`+(p?` part start/end [${r.start} => ${r.end}]`:"")+` startOfSegment [${t}]`+` duration [${i}]`+` timeline [${d}]`+` selected by [${c}]`+` playlist [${a}]`},on=e=>`${e}TimingInfo`,oa=({segmentTimeline:e,currentTimeline:t,startOfSegment:i,buffered:s,overrideCheck:r})=>r||e!==t?e{if(t===i)return!1;if("audio"===s){let t=e.lastTimelineChange({type:"main"});return!t||t.to!==i}if("main"===s&&r){let t=e.pendingTimelineChange({type:"audio"});return!t||t.to!==i}return!1},ol=e=>{if(!e)return!1;let t=e.pendingTimelineChange({type:"audio"}),i=e.pendingTimelineChange({type:"main"}),s=t&&i,r=s&&t.to!==i.to;return!!s&&-1!==t.from&&-1!==i.from&&!!r},oh=e=>{let t=e.timelineChangeController_.pendingTimelineChange({type:"audio"}),i=e.timelineChangeController_.pendingTimelineChange({type:"main"});return t&&i&&t.to{let t=e.pendingSegment_;if(t&&oo({timelineChangeController:e.timelineChangeController_,currentTimeline:e.currentTimeline_,segmentTimeline:t.timeline,loaderType:e.loaderType_,audioDisabled:e.audioDisabled_})&&ol(e.timelineChangeController_)){if(oh(e)){e.timelineChangeController_.trigger("audioTimelineBehind");return}e.timelineChangeController_.trigger("fixBadTimelineChange")}},ou=e=>{let t=0;return["video","audio"].forEach(function(i){let s;let r=e[`${i}TimingInfo`];if(!r)return;let{start:n,end:a}=r;"bigint"==typeof n||"bigint"==typeof a?s=d().BigInt(a)-d().BigInt(n):"number"==typeof n&&"number"==typeof a&&(s=a-n),void 0!==s&&s>t&&(t=s)}),"bigint"==typeof t&&t!!e&&Math.round(e)>t+rM,op=(e,t)=>{if("hls"!==t)return null;let i=ou({audioTimingInfo:e.audioTimingInfo,videoTimingInfo:e.videoTimingInfo});if(!i)return null;let s=e.playlist.targetDuration,r=oc({segmentDuration:i,maxDuration:2*s}),n=oc({segmentDuration:i,maxDuration:s}),a=`Segment with index ${e.mediaIndex} from playlist ${e.playlist.id} has a duration of ${i} when the reported duration is ${e.duration} and the target duration is ${s}. For HLS content, a duration in excess of the target duration may result in playback issues. See the HLS specification section on EXT-X-TARGETDURATION for more details: https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1`;return r||n?{severity:r?"warn":"info",message:a}:null},om=({type:e,segment:t})=>{if(!t)return;let i=!!(t.key||t.map&&t.map.ke),s=!!(t.map&&!t.map.bytes),r=void 0===t.startOfSegment?t.start:t.startOfSegment;return{type:e||t.type,uri:t.resolvedUri||t.uri,start:r,duration:t.duration,isEncrypted:i,isMediaInitialization:s}};class og extends rk.EventTarget{constructor(e,t={}){if(super(),!e)throw TypeError("Initialization settings are required");if("function"!=typeof e.currentTime)throw TypeError("No currentTime getter specified");if(!e.mediaSource)throw TypeError("No MediaSource specified");this.bandwidth=e.bandwidth,this.throughput={rate:0,count:0},this.roundTrip=NaN,this.resetStats_(),this.mediaIndex=null,this.partIndex=null,this.hasPlayed_=e.hasPlayed,this.currentTime_=e.currentTime,this.seekable_=e.seekable,this.seeking_=e.seeking,this.duration_=e.duration,this.mediaSource_=e.mediaSource,this.vhs_=e.vhs,this.loaderType_=e.loaderType,this.currentMediaInfo_=void 0,this.startingMediaInfo_=void 0,this.segmentMetadataTrack_=e.segmentMetadataTrack,this.goalBufferLength_=e.goalBufferLength,this.sourceType_=e.sourceType,this.sourceUpdater_=e.sourceUpdater,this.inbandTextTracks_=e.inbandTextTracks,this.state_="INIT",this.timelineChangeController_=e.timelineChangeController,this.shouldSaveSegmentTimingInfo_=!0,this.parse708captions_=e.parse708captions,this.useDtsForTimestampOffset_=e.useDtsForTimestampOffset,this.captionServices_=e.captionServices,this.exactManifestTimings=e.exactManifestTimings,this.addMetadataToTextTrack=e.addMetadataToTextTrack,this.checkBufferTimeout_=null,this.error_=void 0,this.currentTimeline_=-1,this.shouldForceTimestampOffsetAfterResync_=!1,this.pendingSegment_=null,this.xhrOptions_=null,this.pendingSegments_=[],this.audioDisabled_=!1,this.isPendingTimestampOffset_=!1,this.gopBuffer_=[],this.timeMapping_=0,this.safeAppend_=!1,this.appendInitSegment_={audio:!0,video:!0},this.playlistOfLastInitSegment_={audio:null,video:null},this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_={id3:[],caption:[]},this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=null,this.activeInitSegmentId_=null,this.initSegments_={},this.cacheEncryptionKeys_=e.cacheEncryptionKeys,this.keyCache_={},this.decrypter_=e.decrypter,this.syncController_=e.syncController,this.syncPoint_={segmentIndex:0,time:0},this.transmuxer_=this.createTransmuxer_(),this.triggerSyncInfoUpdate_=()=>this.trigger("syncinfoupdate"),this.syncController_.on("syncinfoupdate",this.triggerSyncInfoUpdate_),this.mediaSource_.addEventListener("sourceopen",()=>{this.isEndOfStream_()||(this.ended_=!1)}),this.fetchAtBuffer_=!1,this.logger_=rL(`SegmentLoader[${this.loaderType_}]`),Object.defineProperty(this,"state",{get(){return this.state_},set(e){e!==this.state_&&(this.logger_(`${this.state_} -> ${e}`),this.state_=e,this.trigger("statechange"))}}),this.sourceUpdater_.on("ready",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():od(this)}),this.sourceUpdater_.on("codecschange",e=>{this.trigger((0,_.A)({type:"codecschange"},e))}),"main"===this.loaderType_&&this.timelineChangeController_.on("pendingtimelinechange",()=>{this.hasEnoughInfoToAppend_()?this.processCallQueue_():od(this)}),"audio"===this.loaderType_&&this.timelineChangeController_.on("timelinechange",e=>{this.trigger((0,_.A)({type:"timelinechange"},e)),this.hasEnoughInfoToLoad_()?this.processLoadQueue_():od(this),this.hasEnoughInfoToAppend_()?this.processCallQueue_():od(this)})}get mediaSequenceSync_(){return this.syncController_.getMediaSequenceSync(this.loaderType_)}createTransmuxer_(){return ad.createTransmuxer({remux:!1,alignGopsAtEnd:this.safeAppend_,keepOriginalTimestamps:!0,parse708captions:this.parse708captions_,captionServices:this.captionServices_})}resetStats_(){this.mediaBytesTransferred=0,this.mediaRequests=0,this.mediaRequestsAborted=0,this.mediaRequestsTimedout=0,this.mediaRequestsErrored=0,this.mediaTransferDuration=0,this.mediaSecondsLoaded=0,this.mediaAppends=0}dispose(){this.trigger("dispose"),this.state="DISPOSED",this.pause(),this.abort_(),this.transmuxer_&&this.transmuxer_.terminate(),this.resetStats_(),this.checkBufferTimeout_&&d().clearTimeout(this.checkBufferTimeout_),this.syncController_&&this.triggerSyncInfoUpdate_&&this.syncController_.off("syncinfoupdate",this.triggerSyncInfoUpdate_),this.off()}setAudio(e){this.audioDisabled_=!e,e?this.appendInitSegment_.audio=!0:this.sourceUpdater_.removeAudio(0,this.duration_())}abort(){if("WAITING"!==this.state){this.pendingSegment_&&(this.pendingSegment_=null),this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);return}this.abort_(),this.state="READY",this.paused()||this.monitorBuffer_()}abort_(){this.pendingSegment_&&this.pendingSegment_.abortRequests&&this.pendingSegment_.abortRequests(),this.pendingSegment_=null,this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_),this.waitingOnRemove_=!1,d().clearTimeout(this.quotaExceededErrorRetryTimeout_),this.quotaExceededErrorRetryTimeout_=null}checkForAbort_(e){return"APPENDING"!==this.state||this.pendingSegment_?!this.pendingSegment_||this.pendingSegment_.requestId!==e:(this.state="READY",!0)}error(e){return void 0!==e&&(this.logger_("error occurred:",e),this.error_=e),this.pendingSegment_=null,this.error_}endOfStream(){this.ended_=!0,this.transmuxer_&&ad.reset(this.transmuxer_),this.gopBuffer_.length=0,this.pause(),this.trigger("ended")}buffered_(){let e=this.getMediaInfo_();if(!this.sourceUpdater_||!e)return rO();if("main"===this.loaderType_){let{hasAudio:t,hasVideo:i,isMuxed:s}=e;if(i&&t&&!this.audioDisabled_&&!s)return this.sourceUpdater_.buffered();if(i)return this.sourceUpdater_.videoBuffered()}return this.sourceUpdater_.audioBuffered()}initSegmentForMap(e,t=!1){if(!e)return null;let i=nM(e),s=this.initSegments_[i];return t&&!s&&e.bytes&&(this.initSegments_[i]=s={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:e.bytes,tracks:e.tracks,timescales:e.timescales}),s||e}segmentKey(e,t=!1){if(!e)return null;let i=nU(e),s=this.keyCache_[i];this.cacheEncryptionKeys_&&t&&!s&&e.bytes&&(this.keyCache_[i]=s={resolvedUri:e.resolvedUri,bytes:e.bytes});let r={resolvedUri:(s||e).resolvedUri};return s&&(r.bytes=s.bytes),r}couldBeginLoading_(){return this.playlist_&&!this.paused()}load(){if(this.monitorBuffer_(),this.playlist_){if("INIT"===this.state&&this.couldBeginLoading_())return this.init_();this.couldBeginLoading_()&&("READY"===this.state||"INIT"===this.state)&&(this.state="READY")}}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}playlist(e,t={}){if(!e||this.playlist_&&this.playlist_.endList&&e.endList&&this.playlist_.uri===e.uri)return;let i=this.playlist_,s=this.pendingSegment_;this.playlist_=e,this.xhrOptions_=t,"INIT"===this.state&&(e.syncInfo={mediaSequence:e.mediaSequence,time:0},"main"===this.loaderType_&&this.syncController_.setDateTimeMappingForStart(e));let r=null;if(i&&(i.id?r=i.id:i.uri&&(r=i.uri)),this.logger_(`playlist update [${r} => ${e.id||e.uri}]`),this.mediaSequenceSync_&&(this.mediaSequenceSync_.update(e,this.currentTime_()),this.logger_(`Playlist update: +currentTime: ${this.currentTime_()} +bufferedEnd: ${rV(this.buffered_())} +`,this.mediaSequenceSync_.diagnostics)),this.trigger("syncinfoupdate"),"INIT"===this.state&&this.couldBeginLoading_())return this.init_();if(!i||i.uri!==e.uri){null!==this.mediaIndex&&(e.endList||"number"!=typeof e.partTargetDuration?this.resyncLoader():this.resetLoader()),this.currentMediaInfo_=void 0,this.trigger("playlistupdate");return}let n=e.mediaSequence-i.mediaSequence;if(this.logger_(`live window shift [${n}]`),null!==this.mediaIndex){if(this.mediaIndex-=n,this.mediaIndex<0)this.mediaIndex=null,this.partIndex=null;else{let e=this.playlist_.segments[this.mediaIndex];if(this.partIndex&&(!e.parts||!e.parts.length||!e.parts[this.partIndex])){let e=this.mediaIndex;this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`),this.resetLoader(),this.mediaIndex=e}}}s&&(s.mediaIndex-=n,s.mediaIndex<0?(s.mediaIndex=null,s.partIndex=null):(s.mediaIndex>=0&&(s.segment=e.segments[s.mediaIndex]),s.partIndex>=0&&s.segment.parts&&(s.part=s.segment.parts[s.partIndex]))),this.syncController_.saveExpiredSegmentInfo(i,e)}pause(){this.checkBufferTimeout_&&(d().clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=null)}paused(){return null===this.checkBufferTimeout_}resetEverything(e){this.ended_=!1,this.activeInitSegmentId_=null,this.appendInitSegment_={audio:!0,video:!0},this.resetLoader(),this.remove(0,1/0,e),this.transmuxer_&&(this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),this.transmuxer_.postMessage({action:"reset"}))}resetLoader(){this.fetchAtBuffer_=!1,this.mediaSequenceSync_&&this.mediaSequenceSync_.resetAppendedStatus(),this.resyncLoader()}resyncLoader(){this.transmuxer_&&ad.reset(this.transmuxer_),this.mediaIndex=null,this.partIndex=null,this.syncPoint_=null,this.isPendingTimestampOffset_=!1;let e=this.currentMediaInfo_&&this.currentMediaInfo_.isFmp4;"hls"!==this.sourceType_||e||(this.shouldForceTimestampOffsetAfterResync_=!0),this.callQueue_=[],this.loadQueue_=[],this.metadataQueue_.id3=[],this.metadataQueue_.caption=[],this.abort(),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}remove(e,t,i=()=>{},s=!1){if(t===1/0&&(t=this.duration_()),t<=e){this.logger_("skipping remove because end ${end} is <= start ${start}");return}if(!this.sourceUpdater_||!this.getMediaInfo_()){this.logger_("skipping remove because no source updater or starting media info");return}let r=1,n=()=>{0==--r&&i()};for(let i in(s||!this.audioDisabled_)&&(r++,this.sourceUpdater_.removeAudio(e,t,n)),(s||"main"===this.loaderType_)&&(this.gopBuffer_=a6(this.gopBuffer_,e,t,this.timeMapping_),r++,this.sourceUpdater_.removeVideo(e,t,n)),this.inbandTextTracks_)a4(e,t,this.inbandTextTracks_[i]);a4(e,t,this.segmentMetadataTrack_),n()}monitorBuffer_(){this.checkBufferTimeout_&&d().clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=d().setTimeout(this.monitorBufferTick_.bind(this),1)}monitorBufferTick_(){"READY"===this.state&&this.fillBuffer_(),this.checkBufferTimeout_&&d().clearTimeout(this.checkBufferTimeout_),this.checkBufferTimeout_=d().setTimeout(this.monitorBufferTick_.bind(this),500)}fillBuffer_(){if(this.sourceUpdater_.updating())return;let e=this.chooseNextRequest_();if(!e)return;let t={segmentInfo:om({type:this.loaderType_,segment:e})};this.trigger({type:"segmentselected",metadata:t}),"number"==typeof e.timestampOffset&&(this.isPendingTimestampOffset_=!1,this.timelineChangeController_.pendingTimelineChange({type:this.loaderType_,from:this.currentTimeline_,to:e.timeline})),this.loadSegment_(e)}isEndOfStream_(e=this.mediaIndex,t=this.playlist_,i=this.partIndex){if(!t||!this.mediaSource_)return!1;let s="number"==typeof e&&t.segments[e],r=e+1===t.segments.length,n=!s||!s.parts||i+1===s.parts.length;return t.endList&&"open"===this.mediaSource_.readyState&&r&&n}chooseNextRequest_(){let e=this.buffered_(),t=rV(e)||0,i=rz(e,this.currentTime_()),s=!this.hasPlayed_()&&i>=1,r=i>=this.goalBufferLength_(),n=this.playlist_.segments;if(!n.length||s||r)return null;this.syncPoint_=this.syncPoint_||this.syncController_.getSyncPoint(this.playlist_,this.duration_(),this.currentTimeline_,this.currentTime_(),this.loaderType_);let a={partIndex:null,mediaIndex:null,startOfSegment:null,playlist:this.playlist_,isSyncRequest:!this.syncPoint_};if(a.isSyncRequest)a.mediaIndex=a9(this.currentTimeline_,n,t),this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${a.mediaIndex}`);else if(null!==this.mediaIndex){let e=n[this.mediaIndex],i="number"==typeof this.partIndex?this.partIndex:-1;a.startOfSegment=e.end?e.end:t,e.parts&&e.parts[i+1]?(a.mediaIndex=this.mediaIndex,a.partIndex=i+1):a.mediaIndex=this.mediaIndex+1}else{let e,i,s;let r=this.fetchAtBuffer_?t:this.currentTime_();if(this.mediaSequenceSync_&&this.logger_(`chooseNextRequest_ request after Quality Switch: +For TargetTime: ${r}. +CurrentTime: ${this.currentTime_()} +BufferedEnd: ${t} +Fetch At Buffer: ${this.fetchAtBuffer_} +`,this.mediaSequenceSync_.diagnostics),this.mediaSequenceSync_&&this.mediaSequenceSync_.isReliable){let t=this.getSyncInfoFromMediaSequenceSync_(r);if(!t){let e="No sync info found while using media sequence sync";return this.error({message:e,metadata:{errorType:rk.Error.StreamingFailedToSelectNextSegment,error:Error(e)}}),this.logger_("chooseNextRequest_ - no sync info found using media sequence sync"),null}this.logger_(`chooseNextRequest_ mediaSequence syncInfo (${t.start} --> ${t.end})`),e=t.segmentIndex,i=t.partIndex,s=t.start}else{this.logger_("chooseNextRequest_ - fallback to a regular segment selection algorithm, based on a syncPoint.");let t=nt.getMediaInfoForTime({exactManifestTimings:this.exactManifestTimings,playlist:this.playlist_,currentTime:r,startingPartIndex:this.syncPoint_.partIndex,startingSegmentIndex:this.syncPoint_.segmentIndex,startTime:this.syncPoint_.time});e=t.segmentIndex,i=t.partIndex,s=t.startTime}a.getMediaInfoForTime=this.fetchAtBuffer_?`bufferedEnd ${r}`:`currentTime ${r}`,a.mediaIndex=e,a.startOfSegment=s,a.partIndex=i,this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${a.mediaIndex} `)}let o=n[a.mediaIndex],l=o&&"number"==typeof a.partIndex&&o.parts&&o.parts[a.partIndex];if(!o||"number"==typeof a.partIndex&&!l)return null;"number"!=typeof a.partIndex&&o.parts&&(a.partIndex=0,l=o.parts[0]);let h=this.vhs_.playlists&&this.vhs_.playlists.main&&this.vhs_.playlists.main.independentSegments||this.playlist_.independentSegments;if(!i&&l&&!h&&!l.independent){if(0===a.partIndex){let e=n[a.mediaIndex-1],t=e.parts&&e.parts.length&&e.parts[e.parts.length-1];t&&t.independent&&(a.mediaIndex-=1,a.partIndex=e.parts.length-1,a.independent="previous segment")}else o.parts[a.partIndex-1].independent&&(a.partIndex-=1,a.independent="previous part")}let d=this.mediaSource_&&"ended"===this.mediaSource_.readyState;return a.mediaIndex>=n.length-1&&d&&!this.seeking_()?null:(this.shouldForceTimestampOffsetAfterResync_&&(this.shouldForceTimestampOffsetAfterResync_=!1,a.forceTimestampOffset=!0,this.logger_("choose next request. Force timestamp offset after loader resync")),this.generateSegmentInfo_(a))}getSyncInfoFromMediaSequenceSync_(e){if(!this.mediaSequenceSync_)return null;let t=Math.max(e,this.mediaSequenceSync_.start);e!==t&&this.logger_(`getSyncInfoFromMediaSequenceSync_. Pulled target time from ${e} to ${t}`);let i=this.mediaSequenceSync_.getSyncInfoForTime(t);if(!i)return null;if(!i.isAppended)return i;let s=this.mediaSequenceSync_.getSyncInfoForTime(i.end);return s?(s.isAppended&&this.logger_("getSyncInfoFromMediaSequenceSync_: We encounter unexpected scenario where next media sequence sync info is also appended!"),s):null}generateSegmentInfo_(e){let{independent:t,playlist:i,mediaIndex:s,startOfSegment:r,isSyncRequest:n,partIndex:a,forceTimestampOffset:o,getMediaInfoForTime:l}=e,h=i.segments[s],d="number"==typeof a&&h.parts[a],u={requestId:"segment-loader-"+Math.random(),uri:d&&d.resolvedUri||h.resolvedUri,mediaIndex:s,partIndex:d?a:null,isSyncRequest:n,startOfSegment:r,playlist:i,bytes:null,encryptedBytes:null,timestampOffset:null,timeline:h.timeline,duration:d&&d.duration||h.duration,segment:h,part:d,byteLength:0,transmuxer:this.transmuxer_,getMediaInfoForTime:l,independent:t},c=void 0!==o?o:this.isPendingTimestampOffset_;u.timestampOffset=this.timestampOffsetForSegment_({segmentTimeline:h.timeline,currentTimeline:this.currentTimeline_,startOfSegment:r,buffered:this.buffered_(),overrideCheck:c});let p=rV(this.sourceUpdater_.audioBuffered());return"number"==typeof p&&(u.audioAppendStart=p-this.sourceUpdater_.audioTimestampOffset()),this.sourceUpdater_.videoBuffered().length&&(u.gopsToAlignWith=a5(this.gopBuffer_,this.currentTime_()-this.sourceUpdater_.videoTimestampOffset(),this.timeMapping_)),u}timestampOffsetForSegment_(e){return oa(e)}earlyAbortWhenNeeded_(e){if(this.vhs_.tech_.paused()||!this.xhrOptions_.timeout||!this.playlist_.attributes.BANDWIDTH||Date.now()-(e.firstBytesReceivedAt||Date.now())<1e3)return;let t=this.currentTime_(),i=e.bandwidth,s=this.pendingSegment_.duration,r=nt.estimateSegmentRequestTime(s,i,this.playlist_,e.bytesReceived),n=function(e,t,i=1){return((e.length?e.end(e.length-1):0)-t)/i}(this.buffered_(),t,this.vhs_.tech_.playbackRate())-1;if(r<=n)return;let a=aW({main:this.vhs_.playlists.main,currentTime:t,bandwidth:i,duration:this.duration_(),segmentDuration:s,timeUntilRebuffer:n,currentTimeline:this.currentTimeline_,syncController:this.syncController_});if(!a)return;let o=r-n-a.rebufferingImpact,l=.5;n<=rM&&(l=1),a.playlist&&a.playlist.uri!==this.playlist_.uri&&!(o{s[e.stream]=s[e.stream]||{startTime:1/0,captions:[],endTime:0};let t=s[e.stream];t.startTime=Math.min(t.startTime,e.startTime+i),t.endTime=Math.max(t.endTime,e.endTime+i),t.captions.push(e)}),Object.keys(s).forEach(e=>{let{startTime:t,endTime:r,captions:n}=s[e],a=this.inbandTextTracks_;this.logger_(`adding cues from ${t} -> ${r} for ${e}`),aQ(a,this.vhs_.tech_,e),a4(t,r,a[e]),aY({captionArray:n,inbandTextTracks:a,timestampOffset:i})}),this.transmuxer_&&this.transmuxer_.postMessage({action:"clearParsedMp4Captions"})}handleId3_(e,t,i){if(this.earlyAbortWhenNeeded_(e.stats),!this.checkForAbort_(e.requestId)){if(!this.pendingSegment_.hasAppendedData_){this.metadataQueue_.id3.push(this.handleId3_.bind(this,e,t,i));return}this.addMetadataToTextTrack(i,t,this.duration_())}}processMetadataQueue_(){this.metadataQueue_.id3.forEach(e=>e()),this.metadataQueue_.caption.forEach(e=>e()),this.metadataQueue_.id3=[],this.metadataQueue_.caption=[]}processCallQueue_(){let e=this.callQueue_;this.callQueue_=[],e.forEach(e=>e())}processLoadQueue_(){let e=this.loadQueue_;this.loadQueue_=[],e.forEach(e=>e())}hasEnoughInfoToLoad_(){if("audio"!==this.loaderType_)return!0;let e=this.pendingSegment_;return!!e&&(!this.getCurrentMediaInfo_()||!oo({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}getCurrentMediaInfo_(e=this.pendingSegment_){return e&&e.trackInfo||this.currentMediaInfo_}getMediaInfo_(e=this.pendingSegment_){return this.getCurrentMediaInfo_(e)||this.startingMediaInfo_}getPendingSegmentPlaylist(){return this.pendingSegment_?this.pendingSegment_.playlist:null}hasEnoughInfoToAppend_(){if(!this.sourceUpdater_.ready()||this.waitingOnRemove_||this.quotaExceededErrorRetryTimeout_)return!1;let e=this.pendingSegment_,t=this.getCurrentMediaInfo_();if(!e||!t)return!1;let{hasAudio:i,hasVideo:s,isMuxed:r}=t;return!(s&&!e.videoTimingInfo||i&&!this.audioDisabled_&&!r&&!e.audioTimingInfo||oo({timelineChangeController:this.timelineChangeController_,currentTimeline:this.currentTimeline_,segmentTimeline:e.timeline,loaderType:this.loaderType_,audioDisabled:this.audioDisabled_}))}handleData_(e,t){if(this.earlyAbortWhenNeeded_(e.stats),this.checkForAbort_(e.requestId))return;if(this.callQueue_.length||!this.hasEnoughInfoToAppend_()){od(this),this.callQueue_.push(this.handleData_.bind(this,e,t));return}let i=this.pendingSegment_;if(this.setTimeMapping_(i.timeline),this.updateMediaSecondsLoaded_(i.part||i.segment),"closed"!==this.mediaSource_.readyState){if(e.map&&(e.map=this.initSegmentForMap(e.map,!0),i.segment.map=e.map),e.key&&this.segmentKey(e.key,!0),i.isFmp4=e.isFmp4,i.timingInfo=i.timingInfo||{},i.isFmp4)this.trigger("fmp4"),i.timingInfo.start=i[on(t.type)].start;else{let e;let t=this.getCurrentMediaInfo_(),s="main"===this.loaderType_&&t&&t.hasVideo;s&&(e=i.videoTimingInfo.start),i.timingInfo.start=this.trueSegmentStart_({currentStart:i.timingInfo.start,playlist:i.playlist,mediaIndex:i.mediaIndex,currentVideoTimestampOffset:this.sourceUpdater_.videoTimestampOffset(),useVideoTimingInfo:s,firstVideoFrameTimeForData:e,videoTimingInfo:i.videoTimingInfo,audioTimingInfo:i.audioTimingInfo})}if(this.updateAppendInitSegmentStatus(i,t.type),this.updateSourceBufferTimestampOffset_(i),i.isSyncRequest){this.updateTimingInfoEnd_(i),this.syncController_.saveSegmentTimingInfo({segmentInfo:i,shouldSaveTimelineMapping:"main"===this.loaderType_});let e=this.chooseNextRequest_();if(e.mediaIndex!==i.mediaIndex||e.partIndex!==i.partIndex){this.logger_("sync segment was incorrect, not appending");return}this.logger_("sync segment was correct, appending")}i.hasAppendedData_=!0,this.processMetadataQueue_(),this.appendData_(i,t)}}updateAppendInitSegmentStatus(e,t){"main"!==this.loaderType_||"number"!=typeof e.timestampOffset||e.changedTimestampOffset||(this.appendInitSegment_={audio:!0,video:!0}),this.playlistOfLastInitSegment_[t]!==e.playlist&&(this.appendInitSegment_[t]=!0)}getInitSegmentAndUpdateState_({type:e,initSegment:t,map:i,playlist:s}){if(i){let e=nM(i);if(this.activeInitSegmentId_===e)return null;t=this.initSegmentForMap(i,!0).bytes,this.activeInitSegmentId_=e}return t&&this.appendInitSegment_[e]?(this.playlistOfLastInitSegment_[e]=s,this.appendInitSegment_[e]=!1,this.activeInitSegmentId_=null,t):null}handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i},s){let r=this.sourceUpdater_.audioBuffered(),n=this.sourceUpdater_.videoBuffered();r.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: "+rq(r).join(", ")),n.length>1&&this.logger_("On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: "+rq(n).join(", "));let a=r.length?r.start(0):0,o=r.length?r.end(r.length-1):0,l=n.length?n.start(0):0,h=n.length?n.end(n.length-1):0;if(o-a<=1&&h-l<=1){this.logger_(`On QUOTA_EXCEEDED_ERR, single segment too large to append to buffer, triggering an error. Appended byte length: ${i.byteLength}, audio buffer: ${rq(r).join(", ")}, video buffer: ${rq(n).join(", ")}, `),this.error({message:"Quota exceeded error with append of a single segment of content",excludeUntil:1/0}),this.trigger("error");return}this.waitingOnRemove_=!0,this.callQueue_.push(this.appendToSourceBuffer_.bind(this,{segmentInfo:e,type:t,bytes:i}));let u=this.currentTime_()-1;this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${u}`),this.remove(0,u,()=>{this.logger_("On QUOTA_EXCEEDED_ERR, retrying append in 1s"),this.waitingOnRemove_=!1,this.quotaExceededErrorRetryTimeout_=d().setTimeout(()=>{this.logger_("On QUOTA_EXCEEDED_ERR, re-processing call queue"),this.quotaExceededErrorRetryTimeout_=null,this.processCallQueue_()},1e3)},!0)}handleAppendError_({segmentInfo:e,type:t,bytes:i},s){if(s){if(22===s.code){this.handleQuotaExceededError_({segmentInfo:e,type:t,bytes:i});return}this.logger_("Received non QUOTA_EXCEEDED_ERR on append",s),this.error({message:`${t} append of ${i.length}b failed for segment #${e.mediaIndex} in playlist ${e.playlist.id}`,metadata:{errorType:rk.Error.StreamingFailedToAppendSegment}}),this.trigger("appenderror")}}appendToSourceBuffer_({segmentInfo:e,type:t,initSegment:i,data:s,bytes:r}){if(!r){let e=[s],t=s.byteLength;i&&(e.unshift(i),t+=i.byteLength),r=aG({bytes:t,segments:e})}let n={segmentInfo:om({type:this.loaderType_,segment:e})};this.trigger({type:"segmentappendstart",metadata:n}),this.sourceUpdater_.appendBuffer({segmentInfo:e,type:t,bytes:r},this.handleAppendError_.bind(this,{segmentInfo:e,type:t,bytes:r}))}handleSegmentTimingInfo_(e,t,i){if(!this.pendingSegment_||t!==this.pendingSegment_.requestId)return;let s=this.pendingSegment_.segment,r=`${e}TimingInfo`;s[r]||(s[r]={}),s[r].transmuxerPrependedSeconds=i.prependedContentDuration||0,s[r].transmuxedPresentationStart=i.start.presentation,s[r].transmuxedDecodeStart=i.start.decode,s[r].transmuxedPresentationEnd=i.end.presentation,s[r].transmuxedDecodeEnd=i.end.decode,s[r].baseMediaDecodeTime=i.baseMediaDecodeTime}appendData_(e,t){let{type:i,data:s}=t;if(!s||!s.byteLength||"audio"===i&&this.audioDisabled_)return;let r=this.getInitSegmentAndUpdateState_({type:i,initSegment:t.initSegment,playlist:e.playlist,map:e.isFmp4?e.segment.map:null});this.appendToSourceBuffer_({segmentInfo:e,type:i,initSegment:r,data:s})}loadSegment_(e){if(this.state="WAITING",this.pendingSegment_=e,this.trimBackBuffer_(e),"number"==typeof e.timestampOffset&&this.transmuxer_&&this.transmuxer_.postMessage({action:"clearAllMp4Captions"}),!this.hasEnoughInfoToLoad_()){od(this),this.loadQueue_.push(()=>{let t=(0,_.A)({},e,{forceTimestampOffset:!0});(0,_.A)(e,this.generateSegmentInfo_(t)),this.isPendingTimestampOffset_=!1,this.updateTransmuxerAndRequestSegment_(e)});return}this.updateTransmuxerAndRequestSegment_(e)}updateTransmuxerAndRequestSegment_(e){this.shouldUpdateTransmuxerTimestampOffset_(e.timestampOffset)&&(this.gopBuffer_.length=0,e.gopsToAlignWith=[],this.timeMapping_=0,this.transmuxer_.postMessage({action:"reset"}),this.transmuxer_.postMessage({action:"setTimestampOffset",timestampOffset:e.timestampOffset}));let t=this.createSimplifiedSegmentObj_(e),i=this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex),s=null!==this.mediaIndex,r=e.timeline!==this.currentTimeline_&&e.timeline>0;this.logger_(`Requesting +${aK(e.uri)} +${or(e)}`),t.map&&!t.map.bytes&&(this.logger_("going to request init segment."),this.appendInitSegment_={video:!0,audio:!0}),e.abortRequests=aL({xhr:this.vhs_.xhr,xhrOptions:this.xhrOptions_,decryptionWorker:this.decrypter_,segment:t,abortFn:this.handleAbort_.bind(this,e),progressFn:this.handleProgress_.bind(this),trackInfoFn:this.handleTrackInfo_.bind(this),timingInfoFn:this.handleTimingInfo_.bind(this),videoSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"video",e.requestId),audioSegmentTimingInfoFn:this.handleSegmentTimingInfo_.bind(this,"audio",e.requestId),captionsFn:this.handleCaptions_.bind(this),isEndOfTimeline:i||s&&r,endedTimelineFn:()=>{this.logger_("received endedtimeline callback")},id3Fn:this.handleId3_.bind(this),dataFn:this.handleData_.bind(this),doneFn:this.segmentRequestFinished_.bind(this),onTransmuxerLog:({message:t,level:i,stream:s})=>{this.logger_(`${or(e)} logged from transmuxer stream ${s} as a ${i}: ${t}`)},triggerSegmentEventFn:({type:e,segment:t,keyInfo:i,trackInfo:s,timingInfo:r})=>{let n={segmentInfo:om({segment:t})};i&&(n.keyInfo=i),s&&(n.trackInfo=s),r&&(n.timingInfo=r),this.trigger({type:e,metadata:n})}})}trimBackBuffer_(e){let t=os(this.seekable_(),this.currentTime_(),this.playlist_.targetDuration||10);t>0&&this.remove(0,t)}createSimplifiedSegmentObj_(e){let t=e.segment,i=e.part,s=e.segment.key||e.segment.map&&e.segment.map.key,r=e.segment.map&&!e.segment.map.bytes,n={resolvedUri:i?i.resolvedUri:t.resolvedUri,byterange:i?i.byterange:t.byterange,requestId:e.requestId,transmuxer:e.transmuxer,audioAppendStart:e.audioAppendStart,gopsToAlignWith:e.gopsToAlignWith,part:e.part,type:this.loaderType_,start:e.startOfSegment,duration:e.duration,isEncrypted:s,isMediaInitialization:r},a=e.playlist.segments[e.mediaIndex-1];if(a&&a.timeline===t.timeline&&(a.videoTimingInfo?n.baseStartTime=a.videoTimingInfo.transmuxedDecodeEnd:a.audioTimingInfo&&(n.baseStartTime=a.audioTimingInfo.transmuxedDecodeEnd)),t.key){let i=t.key.iv||new Uint32Array([0,0,0,e.mediaIndex+e.playlist.mediaSequence]);n.key=this.segmentKey(t.key),n.key.iv=i}return t.map&&(n.map=this.initSegmentForMap(t.map)),n}saveTransferStats_(e){this.mediaRequests+=1,e&&(this.mediaBytesTransferred+=e.bytesReceived,this.mediaTransferDuration+=e.roundTripTime)}saveBandwidthRelatedStats_(e,t){if(this.pendingSegment_.byteLength=t.bytesReceived,e3*e.playlist.targetDuration,n=s&&s.end&&this.currentTime_()-s.end>3*e.playlist.partTargetDuration;if(r||n){this.logger_(`bad ${r?"segment":"part"} ${or(e)}`),this.resetEverything();return}null!==this.mediaIndex&&this.trigger("bandwidthupdate"),this.trigger("progress"),this.mediaIndex=e.mediaIndex,this.partIndex=e.partIndex,this.isEndOfStream_(e.mediaIndex,e.playlist,e.partIndex)&&this.endOfStream(),this.trigger("appended"),e.hasAppendedData_&&this.mediaAppends++,this.paused()||this.monitorBuffer_()}recordThroughput_(e){if(e.duratione.toUpperCase())},oy=["video","audio"],ov=(e,t)=>{let i=t[`${e}Buffer`];return i&&i.updating||t.queuePending[e]},ob=(e,t)=>{for(let i=0;i{if(0===t.queue.length)return;let i=0,s=t.queue[i];if("mediaSource"===s.type){t.updating()||"closed"===t.mediaSource.readyState||(t.queue.shift(),s.action(t),s.doneFn&&s.doneFn(),oT("audio",t),oT("video",t));return}if(!("mediaSource"===e||!t.ready()||"closed"===t.mediaSource.readyState||ov(e,t))){if(s.type!==e){if(null===(i=ob(e,t.queue)))return;s=t.queue[i]}if(t.queue.splice(i,1),t.queuePending[e]=s,s.action(e,t),!s.doneFn){t.queuePending[e]=null,oT(e,t);return}}},oS=(e,t)=>{let i=t[`${e}Buffer`],s=o_(e);i&&(i.removeEventListener("updateend",t[`on${s}UpdateEnd_`]),i.removeEventListener("error",t[`on${s}Error_`]),t.codecs[e]=null,t[`${e}Buffer`]=null)},ok=(e,t)=>e&&t&&-1!==Array.prototype.indexOf.call(e.sourceBuffers,t),oC={appendBuffer:(e,t,i)=>(s,r)=>{let n=r[`${s}Buffer`];if(ok(r.mediaSource,n)){r.logger_(`Appending segment ${t.mediaIndex}'s ${e.length} bytes to ${s}Buffer`);try{n.appendBuffer(e)}catch(e){r.logger_(`Error with code ${e.code} `+(22===e.code?"(QUOTA_EXCEEDED_ERR) ":"")+`when appending segment ${t.mediaIndex} to ${s}Buffer`),r.queuePending[s]=null,i(e)}}},remove:(e,t)=>(i,s)=>{let r=s[`${i}Buffer`];if(ok(s.mediaSource,r)){s.logger_(`Removing ${e} to ${t} from ${i}Buffer`);try{r.remove(e,t)}catch(r){s.logger_(`Remove ${e} to ${t} from ${i}Buffer failed`)}}},timestampOffset:e=>(t,i)=>{let s=i[`${t}Buffer`];ok(i.mediaSource,s)&&(i.logger_(`Setting ${t}timestampOffset to ${e}`),s.timestampOffset=e)},callback:e=>(t,i)=>{e()},endOfStream:e=>t=>{if("open"===t.mediaSource.readyState){t.logger_(`Calling mediaSource endOfStream(${e||""})`);try{t.mediaSource.endOfStream(e)}catch(e){rk.log.warn("Failed to call media source endOfStream",e)}}},duration:e=>t=>{t.logger_(`Setting mediaSource duration to ${e}`);try{t.mediaSource.duration=e}catch(e){rk.log.warn("Failed to set media source duration",e)}},abort:()=>(e,t)=>{if("open"!==t.mediaSource.readyState)return;let i=t[`${e}Buffer`];if(ok(t.mediaSource,i)){t.logger_(`calling abort on ${e}Buffer`);try{i.abort()}catch(t){rk.log.warn(`Failed to abort on ${e}Buffer`,t)}}},addSourceBuffer:(e,t)=>i=>{let s=o_(e),r=(0,b.UD)(t);i.logger_(`Adding ${e}Buffer with codec ${t} to mediaSource`);let n=i.mediaSource.addSourceBuffer(r);n.addEventListener("updateend",i[`on${s}UpdateEnd_`]),n.addEventListener("error",i[`on${s}Error_`]),i.codecs[e]=t,i[`${e}Buffer`]=n},removeSourceBuffer:e=>t=>{let i=t[`${e}Buffer`];if(oS(e,t),ok(t.mediaSource,i)){t.logger_(`Removing ${e}Buffer with codec ${t.codecs[e]} from mediaSource`);try{t.mediaSource.removeSourceBuffer(i)}catch(t){rk.log.warn(`Failed to removeSourceBuffer ${e}Buffer`,t)}}},changeType:e=>(t,i)=>{let s=i[`${t}Buffer`],r=(0,b.UD)(e);if(!ok(i.mediaSource,s))return;let n=e.substring(0,e.indexOf(".")),a=i.codecs[t];if(a.substring(0,a.indexOf("."))===n)return;let o={codecsChangeInfo:{from:a,to:e}};i.trigger({type:"codecschange",metadata:o}),i.logger_(`changing ${t}Buffer codec from ${a} to ${e}`);try{s.changeType(r),i.codecs[t]=e}catch(e){o.errorType=rk.Error.StreamingCodecsChangeError,o.error=e,e.metadata=o,i.error_=e,i.trigger("error"),rk.log.warn(`Failed to changeType on ${t}Buffer`,e)}}},ow=({type:e,sourceUpdater:t,action:i,doneFn:s,name:r})=>{t.queue.push({type:e,action:i,doneFn:s,name:r}),oT(e,t)},oE=(e,t)=>i=>{let s=function(e){if(0===e.length)return"Buffered Ranges are empty";let t="Buffered Ranges: \n";for(let i=0;i ${r}. Duration (${r-s}) +`}return t}(t[`${e}Buffered`]());if(t.logger_(`received "updateend" event for ${e} Source Buffer: `,s),t.queuePending[e]){let i=t.queuePending[e].doneFn;t.queuePending[e]=null,i&&i(t[`${e}Error_`])}oT(e,t)};class ox extends rk.EventTarget{constructor(e){super(),this.mediaSource=e,this.sourceopenListener_=()=>oT("mediaSource",this),this.mediaSource.addEventListener("sourceopen",this.sourceopenListener_),this.logger_=rL("SourceUpdater"),this.audioTimestampOffset_=0,this.videoTimestampOffset_=0,this.queue=[],this.queuePending={audio:null,video:null},this.delayedAudioAppendQueue_=[],this.videoAppendQueued_=!1,this.codecs={},this.onVideoUpdateEnd_=oE("video",this),this.onAudioUpdateEnd_=oE("audio",this),this.onVideoError_=e=>{this.videoError_=e},this.onAudioError_=e=>{this.audioError_=e},this.createdSourceBuffers_=!1,this.initializedEme_=!1,this.triggeredReady_=!1}initializedEme(){this.initializedEme_=!0,this.triggerReady()}hasCreatedSourceBuffers(){return this.createdSourceBuffers_}hasInitializedAnyEme(){return this.initializedEme_}ready(){return this.hasCreatedSourceBuffers()&&this.hasInitializedAnyEme()}createSourceBuffers(e){!this.hasCreatedSourceBuffers()&&(this.addOrChangeSourceBuffers(e),this.createdSourceBuffers_=!0,this.trigger("createdsourcebuffers"),this.triggerReady())}triggerReady(){this.ready()&&!this.triggeredReady_&&(this.triggeredReady_=!0,this.trigger("ready"))}addSourceBuffer(e,t){ow({type:"mediaSource",sourceUpdater:this,action:oC.addSourceBuffer(e,t),name:"addSourceBuffer"})}abort(e){ow({type:e,sourceUpdater:this,action:oC.abort(e),name:"abort"})}removeSourceBuffer(e){if(!this.canRemoveSourceBuffer()){rk.log.error("removeSourceBuffer is not supported!");return}ow({type:"mediaSource",sourceUpdater:this,action:oC.removeSourceBuffer(e),name:"removeSourceBuffer"})}canRemoveSourceBuffer(){return!rk.browser.IS_FIREFOX&&d().MediaSource&&d().MediaSource.prototype&&"function"==typeof d().MediaSource.prototype.removeSourceBuffer}static canChangeType(){return d().SourceBuffer&&d().SourceBuffer.prototype&&"function"==typeof d().SourceBuffer.prototype.changeType}canChangeType(){return this.constructor.canChangeType()}changeType(e,t){if(!this.canChangeType()){rk.log.error("changeType is not supported!");return}ow({type:e,sourceUpdater:this,action:oC.changeType(t),name:"changeType"})}addOrChangeSourceBuffers(e){if(!e||"object"!=typeof e||0===Object.keys(e).length)throw Error("Cannot addOrChangeSourceBuffers to undefined codecs");Object.keys(e).forEach(t=>{let i=e[t];if(!this.hasCreatedSourceBuffers())return this.addSourceBuffer(t,i);this.canChangeType()&&this.changeType(t,i)})}appendBuffer(e,t){let{segmentInfo:i,type:s,bytes:r}=e;if(this.processedAppend_=!0,"audio"===s&&this.videoBuffer&&!this.videoAppendQueued_){this.delayedAudioAppendQueue_.push([e,t]),this.logger_(`delayed audio append of ${r.length} until video append`);return}if(ow({type:s,sourceUpdater:this,action:oC.appendBuffer(r,i||{mediaIndex:-1},t),doneFn:t,name:"appendBuffer"}),"video"===s){if(this.videoAppendQueued_=!0,!this.delayedAudioAppendQueue_.length)return;let e=this.delayedAudioAppendQueue_.slice();this.logger_(`queuing delayed audio ${e.length} appendBuffers`),this.delayedAudioAppendQueue_.length=0,e.forEach(e=>{this.appendBuffer.apply(this,e)})}}audioBuffered(){return ok(this.mediaSource,this.audioBuffer)&&this.audioBuffer.buffered?this.audioBuffer.buffered:rO()}videoBuffered(){return ok(this.mediaSource,this.videoBuffer)&&this.videoBuffer.buffered?this.videoBuffer.buffered:rO()}buffered(){let e=ok(this.mediaSource,this.videoBuffer)?this.videoBuffer:null,t=ok(this.mediaSource,this.audioBuffer)?this.audioBuffer:null;return t&&!e?this.audioBuffered():e&&!t?this.videoBuffered():rF(this.audioBuffered(),this.videoBuffered())}setDuration(e,t=of){ow({type:"mediaSource",sourceUpdater:this,action:oC.duration(e),name:"duration",doneFn:t})}endOfStream(e=null,t=of){"string"!=typeof e&&(e=void 0),ow({type:"mediaSource",sourceUpdater:this,action:oC.endOfStream(e),name:"endOfStream",doneFn:t})}removeAudio(e,t,i=of){if(!this.audioBuffered().length||0===this.audioBuffered().end(0)){i();return}ow({type:"audio",sourceUpdater:this,action:oC.remove(e,t),doneFn:i,name:"remove"})}removeVideo(e,t,i=of){if(!this.videoBuffered().length||0===this.videoBuffered().end(0)){i();return}ow({type:"video",sourceUpdater:this,action:oC.remove(e,t),doneFn:i,name:"remove"})}updating(){return!!(ov("audio",this)||ov("video",this))}audioTimestampOffset(e){return void 0!==e&&this.audioBuffer&&this.audioTimestampOffset_!==e&&(ow({type:"audio",sourceUpdater:this,action:oC.timestampOffset(e),name:"timestampOffset"}),this.audioTimestampOffset_=e),this.audioTimestampOffset_}videoTimestampOffset(e){return void 0!==e&&this.videoBuffer&&this.videoTimestampOffset_!==e&&(ow({type:"video",sourceUpdater:this,action:oC.timestampOffset(e),name:"timestampOffset"}),this.videoTimestampOffset_=e),this.videoTimestampOffset_}audioQueueCallback(e){this.audioBuffer&&ow({type:"audio",sourceUpdater:this,action:oC.callback(e),name:"callback"})}videoQueueCallback(e){this.videoBuffer&&ow({type:"video",sourceUpdater:this,action:oC.callback(e),name:"callback"})}dispose(){this.trigger("dispose"),oy.forEach(e=>{this.abort(e),this.canRemoveSourceBuffer()?this.removeSourceBuffer(e):this[`${e}QueueCallback`](()=>oS(e,this))}),this.videoAppendQueued_=!1,this.delayedAudioAppendQueue_.length=0,this.sourceopenListener_&&this.mediaSource.removeEventListener("sourceopen",this.sourceopenListener_),this.off()}}let oI=e=>decodeURIComponent(escape(String.fromCharCode.apply(null,e))),oP=e=>Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join(""),oA=new Uint8Array("\n\n".split("").map(e=>e.charCodeAt(0)));class oL extends Error{constructor(){super("Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.")}}class oD extends og{constructor(e,t={}){super(e,t),this.mediaSource_=null,this.subtitlesTrack_=null,this.featuresNativeTextTracks_=e.featuresNativeTextTracks,this.loadVttJs=e.loadVttJs,this.shouldSaveSegmentTimingInfo_=!1}buffered_(){if(!this.subtitlesTrack_||!this.subtitlesTrack_.cues||!this.subtitlesTrack_.cues.length)return rO();let e=this.subtitlesTrack_.cues;return rO([[e[0].startTime,e[e.length-1].startTime]])}initSegmentForMap(e,t=!1){if(!e)return null;let i=nM(e),s=this.initSegments_[i];if(t&&!s&&e.bytes){let t=new Uint8Array(oA.byteLength+e.bytes.byteLength);t.set(e.bytes),t.set(oA,e.bytes.byteLength),this.initSegments_[i]=s={resolvedUri:e.resolvedUri,byterange:e.byterange,bytes:t}}return s||e}couldBeginLoading_(){return this.playlist_&&this.subtitlesTrack_&&!this.paused()}init_(){return this.state="READY",this.resetEverything(),this.monitorBuffer_()}track(e){return void 0===e||(this.subtitlesTrack_=e,"INIT"===this.state&&this.couldBeginLoading_()&&this.init_()),this.subtitlesTrack_}remove(e,t){a4(e,t,this.subtitlesTrack_)}fillBuffer_(){let e=this.chooseNextRequest_();if(e){if(null===this.syncController_.timestampOffsetForTimeline(e.timeline)){this.syncController_.one("timestampoffset",()=>{this.state="READY",this.paused()||this.monitorBuffer_()}),this.state="WAITING_ON_TIMELINE";return}this.loadSegment_(e)}}timestampOffsetForSegment_(){return null}chooseNextRequest_(){return this.skipEmptySegments_(super.chooseNextRequest_())}skipEmptySegments_(e){for(;e&&e.segment.empty;){if(e.mediaIndex+1>=e.playlist.segments.length){e=null;break}e=this.generateSegmentInfo_({playlist:e.playlist,mediaIndex:e.mediaIndex+1,startOfSegment:e.startOfSegment+e.duration,isSyncRequest:e.isSyncRequest})}return e}stopForError(e){this.error(e),this.state="READY",this.pause(),this.trigger("error")}segmentRequestFinished_(e,t,i){if(!this.subtitlesTrack_){this.state="READY";return}if(this.saveTransferStats_(t.stats),!this.pendingSegment_){this.state="READY",this.mediaRequestsAborted+=1;return}if(e){e.code===ac.TIMEOUT&&this.handleTimeout_(),e.code===ac.ABORTED?this.mediaRequestsAborted+=1:this.mediaRequestsErrored+=1,this.stopForError(e);return}let s=this.pendingSegment_,r=i.mp4VttCues&&i.mp4VttCues.length;r&&(s.mp4VttCues=i.mp4VttCues),this.saveBandwidthRelatedStats_(s.duration,t.stats),t.key&&this.segmentKey(t.key,!0),this.state="APPENDING",this.trigger("appending");let n=s.segment;if(n.map&&(n.map.bytes=t.map.bytes),s.bytes=t.bytes,"function"!=typeof d().WebVTT&&"function"==typeof this.loadVttJs){this.state="WAITING_ON_VTTJS",this.loadVttJs().then(()=>this.segmentRequestFinished_(e,t,i),()=>this.stopForError({message:"Error loading vtt.js"}));return}n.requested=!0;try{this.parseVTTCues_(s)}catch(e){this.stopForError({message:e.message,metadata:{errorType:rk.Error.StreamingVttParserError,error:e}});return}if(r||this.updateTimeMapping_(s,this.syncController_.timelines[s.timeline],this.playlist_),s.cues.length?s.timingInfo={start:s.cues[0].startTime,end:s.cues[s.cues.length-1].endTime}:s.timingInfo={start:s.startOfSegment,end:s.startOfSegment+s.duration},s.isSyncRequest){this.trigger("syncinfoupdate"),this.pendingSegment_=null,this.state="READY";return}s.byteLength=s.bytes.byteLength,this.mediaSecondsLoaded+=n.duration,s.cues.forEach(e=>{this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_?new(d()).VTTCue(e.startTime,e.endTime,e.text):e)}),a8(this.subtitlesTrack_),this.handleAppendsDone_()}handleData_(e,t){let i=e&&"vtt"===e.type,s=t&&"text"===t.type;i&&s&&super.handleData_(e,t)}updateTimingInfoEnd_(){}parseMp4VttCues_(e){let t=null===this.sourceUpdater_.videoTimestampOffset()?this.sourceUpdater_.audioTimestampOffset():this.sourceUpdater_.videoTimestampOffset();e.mp4VttCues.forEach(i=>{let s=i.start+t,r=i.end+t,n=new(d()).VTTCue(s,r,i.cueText);i.settings&&i.settings.split(" ").forEach(e=>{let t=e.split(":"),i=t[0],s=t[1];n[i]=isNaN(s)?s:Number(s)}),e.cues.push(n)})}parseVTTCues_(e){let t;let i=!1;if("function"!=typeof d().WebVTT)throw new oL;if(e.cues=[],e.timestampmap={MPEGTS:0,LOCAL:0},e.mp4VttCues){this.parseMp4VttCues_(e);return}"function"==typeof d().TextDecoder?t=new(d()).TextDecoder("utf8"):(t=d().WebVTT.StringDecoder(),i=!0);let s=new(d()).WebVTT.Parser(d(),d().vttjs,t);if(s.oncue=e.cues.push.bind(e.cues),s.ontimestampmap=t=>{e.timestampmap=t},s.onparsingerror=e=>{rk.log.warn("Error encountered when parsing cues: "+e.message)},e.segment.map){let t=e.segment.map.bytes;i&&(t=oI(t)),s.parse(t)}let r=e.bytes;i&&(r=oI(r)),s.parse(r),s.flush()}updateTimeMapping_(e,t,i){let s=e.segment;if(!t)return;if(!e.cues.length){s.empty=!0;return}let{MPEGTS:r,LOCAL:n}=e.timestampmap,a=r/I.ONE_SECOND_IN_TS-n+t.mapping;if(e.cues.forEach(e=>{let i=e.endTime-e.startTime,s=this.handleRollover_(e.startTime+a,t.time);e.startTime=Math.max(s,0),e.endTime=Math.max(s+i,0)}),!i.syncInfo){let t=e.cues[0].startTime,r=e.cues[e.cues.length-1].startTime;i.syncInfo={mediaSequence:i.mediaSequence+e.mediaIndex,time:Math.min(t,r-s.duration)}}}handleRollover_(e,t){let i;if(null===t)return e;let s=e*I.ONE_SECOND_IN_TS,r=t*I.ONE_SECOND_IN_TS;for(i=r0x100000000;)s+=i;return s/I.ONE_SECOND_IN_TS}}let oO=function(e,t){let i=e.cues;for(let e=0;e=s.adStartTime&&t<=s.adEndTime)return s}return null},oM=function(e,t,i=0){let s;if(!e.segments)return;let r=i;for(let i=0;i=this.start&&e0}resetAppendStatus(){this.segmentSyncInfo_.resetAppendedStatus(),this.partsSyncInfo_.forEach(e=>e.resetAppendedStatus())}}class oB{constructor(){this.storage_=new Map,this.diagnostics_="",this.isReliable_=!1,this.start_=-1/0,this.end_=1/0}get start(){return this.start_}get end(){return this.end_}get diagnostics(){return this.diagnostics_}get isReliable(){return this.isReliable_}resetAppendedStatus(){this.storage_.forEach(e=>e.resetAppendStatus())}update(e,t){let{mediaSequence:i,segments:s}=e;if(this.isReliable_=this.isReliablePlaylist_(i,s),this.isReliable_)return this.updateStorage_(s,i,this.calculateBaseTime_(i,s,t))}getSyncInfoForTime(e){for(let{segmentSyncInfo:t,partsSyncInfo:i}of this.storage_.values())if(i.length){for(let t of i)if(t.isInRange(e))return t}else if(t.isInRange(e))return t;return null}getSyncInfoForMediaSequence(e){return this.storage_.get(e)}updateStorage_(e,t,i){let s=new Map,r="\n",n=i,a=t;this.start_=n,e.forEach((e,t)=>{let i=this.storage_.get(a),o=n,l=o+e.duration,h=!!(i&&i.segmentSyncInfo&&i.segmentSyncInfo.isAppended),d=new oU({start:o,end:l,appended:h,segmentIndex:t});e.syncInfo=d;let u=n,c=(e.parts||[]).map((e,s)=>{let n=u,o=u+e.duration,l=!!(i&&i.partsSyncInfo&&i.partsSyncInfo[s]&&i.partsSyncInfo[s].isAppended),h=new oU({start:n,end:o,appended:l,segmentIndex:t,partIndex:s});return u=o,r+=`Media Sequence: ${a}.${s} | Range: ${n} --> ${o} | Appended: ${l} +`,e.syncInfo=h,h});s.set(a,new oR(d,c)),r+=`${aK(e.resolvedUri)} | Media Sequence: ${a} | Range: ${o} --> ${l} | Appended: ${h} +`,a++,n=l}),this.end_=n,this.storage_=s,this.diagnostics_=r}calculateBaseTime_(e,t,i){if(!this.storage_.size)return 0;if(this.storage_.has(e))return this.storage_.get(e).segmentSyncInfo.start;let s=Math.min(...this.storage_.keys());if(ei!==1/0?{time:0,segmentIndex:0,partIndex:null}:null},{name:"MediaSequence",run:(e,t,i,s,r,n)=>{let a=e.getMediaSequenceSync(n);if(!a||!a.isReliable)return null;let o=a.getSyncInfoForTime(r);return o?{time:o.start,partIndex:o.partIndex,segmentIndex:o.segmentIndex}:null}},{name:"ProgramDateTime",run:(e,t,i,s,r)=>{if(!Object.keys(e.timelineToDatetimeMappings).length)return null;let n=null,a=null,o=rG(t);r=r||0;for(let i=0;i{let n=null,a=null;r=r||0;let o=rG(t);for(let e=0;e=e)&&(a=e,n={time:d,segmentIndex:l.segmentIndex,partIndex:l.partIndex})}}return n}},{name:"Discontinuity",run:(e,t,i,s,r)=>{let n=null;if(r=r||0,t.discontinuityStarts&&t.discontinuityStarts.length){let i=null;for(let s=0;s=e)&&(i=e,n={time:l.time,segmentIndex:a,partIndex:null})}}}return n}},{name:"Playlist",run:(e,t,i,s,r)=>t.syncInfo?{time:t.syncInfo.time,segmentIndex:t.syncInfo.mediaSequence-t.mediaSequence,partIndex:null}:null}];class oF extends rk.EventTarget{constructor(e={}){super(),this.timelines=[],this.discontinuities=[],this.timelineToDatetimeMappings={};let t=new oB,i=new oN(t),s=new oN(t);this.mediaSequenceStorage_={main:t,audio:i,vtt:s},this.logger_=rL("SyncController")}getMediaSequenceSync(e){return this.mediaSequenceStorage_[e]||null}getSyncPoint(e,t,i,s,r){if(t!==1/0)return oj.find(({name:e})=>"VOD"===e).run(this,e,t);let n=this.runStrategies_(e,t,i,s,r);if(!n.length)return null;for(let t of n){let{syncPoint:i,strategy:r}=t,{segmentIndex:n,time:a}=i;if(n<0)continue;let o=a+e.segments[n].duration;if(this.logger_(`Strategy: ${r}. Current time: ${s}. selected segment: ${n}. Time: [${a} -> ${o}]}`),s>=a&&s0&&(s.time*=-1),Math.abs(s.time+r1({defaultDuration:e.targetDuration,durationList:e.segments,startIndex:s.segmentIndex,endIndex:0}))}runStrategies_(e,t,i,s,r){let n=[];for(let a=0;a86400){rk.log.warn(`Not saving expired segment info. Media sequence gap ${i} is too large.`);return}for(let s=i-1;s>=0;s--){let i=e.segments[s];if(i&&void 0!==i.start){t.syncInfo={mediaSequence:e.mediaSequence+s,time:i.start},this.logger_(`playlist refresh sync: [time:${t.syncInfo.time}, mediaSequence: ${t.syncInfo.mediaSequence}]`),this.trigger("syncinfoupdate");break}}}setDateTimeMappingForStart(e){if(this.timelineToDatetimeMappings={},e.segments&&e.segments.length&&e.segments[0].dateTimeObject){let t=e.segments[0],i=t.dateTimeObject.getTime()/1e3;this.timelineToDatetimeMappings[t.timeline]=-i}}saveSegmentTimingInfo({segmentInfo:e,shouldSaveTimelineMapping:t}){let i=this.calculateSegmentTimeMapping_(e,e.timingInfo,t),s=e.segment;i&&(this.saveDiscontinuitySyncInfo_(e),e.playlist.syncInfo||(e.playlist.syncInfo={mediaSequence:e.playlist.mediaSequence+e.mediaIndex,time:s.start}));let r=s.dateTimeObject;s.discontinuity&&t&&r&&(this.timelineToDatetimeMappings[s.timeline]=-(r.getTime()/1e3))}timestampOffsetForTimeline(e){return void 0===this.timelines[e]?null:this.timelines[e].time}mappingForTimeline(e){return void 0===this.timelines[e]?null:this.timelines[e].mapping}calculateSegmentTimeMapping_(e,t,i){let s,r;let n=e.segment,a=e.part,o=this.timelines[e.timeline];if("number"==typeof e.timestampOffset)o={time:e.startOfSegment,mapping:e.startOfSegment-t.start},i&&(this.timelines[e.timeline]=o,this.trigger("timestampoffset"),this.logger_(`time mapping for timeline ${e.timeline}: [time: ${o.time}] [mapping: ${o.mapping}]`)),s=e.startOfSegment,r=t.end+o.mapping;else{if(!o)return!1;s=t.start+o.mapping,r=t.end+o.mapping}return a&&(a.start=s,a.end=r),(!n.start||so){let s;s=a<0?i.start-r1({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex,endIndex:r}):i.end+r1({defaultDuration:t.targetDuration,durationList:t.segments,startIndex:e.mediaIndex+1,endIndex:r}),this.discontinuities[n]={time:s,accuracy:o}}}}dispose(){this.trigger("dispose"),this.off()}}class o$ extends rk.EventTarget{constructor(){super(),this.pendingTimelineChanges_={},this.lastTimelineChanges_={}}clearPendingTimelineChange(e){this.pendingTimelineChanges_[e]=null,this.trigger("pendingtimelinechange")}pendingTimelineChange({type:e,from:t,to:i}){return"number"==typeof t&&"number"==typeof i&&(this.pendingTimelineChanges_[e]={type:e,from:t,to:i},this.trigger("pendingtimelinechange")),this.pendingTimelineChanges_[e]}lastTimelineChange({type:e,from:t,to:i}){return"number"==typeof t&&"number"==typeof i&&(this.lastTimelineChanges_[e]={type:e,from:t,to:i},delete this.pendingTimelineChanges_[e],this.trigger({type:"timelinechange",metadata:{timelineChangeInfo:{from:t,to:i}}})),this.lastTimelineChanges_[e]}dispose(){this.trigger("dispose"),this.pendingTimelineChanges_={},this.lastTimelineChanges_={},this.off()}}var oq=n7(n9(ae(function(){var e,t,s,r=function(){function e(){this.listeners={}}var t=e.prototype;return t.on=function(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},t.off=function(e,t){if(!this.listeners[e])return!1;var i=this.listeners[e].indexOf(t);return this.listeners[e]=this.listeners[e].slice(0),this.listeners[e].splice(i,1),i>-1},t.trigger=function(e){var t=this.listeners[e];if(t){if(2==arguments.length)for(var i=t.length,s=0;s>7)*283)^e]=e;for(t=i=0;!u[t];t^=s||1,i=m[i]||1)for(e=0,n=(n=i^i<<1^i<<2^i<<3^i<<4)>>8^255&n^99,u[t]=n,c[n]=t,o=0x1010101*p[r=p[s=p[t]]]^65537*r^257*s^0x1010100*t,a=257*p[n]^0x1010100*n;e<4;e++)h[e][t]=a=a<<24^a>>>8,d[e][n]=o=o<<24^o>>>8;for(e=0;e<5;e++)h[e]=h[e].slice(0),d[e]=d[e].slice(0);return l},a=null;class o{constructor(e){let t,i,s;a||(a=n()),this._tables=[[a[0][0].slice(),a[0][1].slice(),a[0][2].slice(),a[0][3].slice(),a[0][4].slice()],[a[1][0].slice(),a[1][1].slice(),a[1][2].slice(),a[1][3].slice(),a[1][4].slice()]];let r=this._tables[0][4],o=this._tables[1],l=e.length,h=1;if(4!==l&&6!==l&&8!==l)throw Error("Invalid aes key size");let d=e.slice(0),u=[];for(this._key=[d,u],t=l;t<4*l+28;t++)s=d[t-1],(t%l==0||8===l&&t%l==4)&&(s=r[s>>>24]<<24^r[s>>16&255]<<16^r[s>>8&255]<<8^r[255&s],t%l==0&&(s=s<<8^s>>>24^h<<24,h=h<<1^(h>>7)*283)),d[t]=d[t-l]^s;for(i=0;t;i++,t--)s=d[3&i?t:t-4],t<=4||i<4?u[i]=s:u[i]=o[0][r[s>>>24]]^o[1][r[s>>16&255]]^o[2][r[s>>8&255]]^o[3][r[255&s]]}decrypt(e,t,i,s,r,n){let a,o,l,h;let d=this._key[1],u=e^d[0],c=s^d[1],p=i^d[2],m=t^d[3],g=d.length/4-2,f=4,_=this._tables[1],y=_[0],v=_[1],b=_[2],T=_[3],S=_[4];for(h=0;h>>24]^v[c>>16&255]^b[p>>8&255]^T[255&m]^d[f],o=y[c>>>24]^v[p>>16&255]^b[m>>8&255]^T[255&u]^d[f+1],l=y[p>>>24]^v[m>>16&255]^b[u>>8&255]^T[255&c]^d[f+2],m=y[m>>>24]^v[u>>16&255]^b[c>>8&255]^T[255&p]^d[f+3],f+=4,u=a,c=o,p=l;for(h=0;h<4;h++)r[(3&-h)+n]=S[u>>>24]<<24^S[c>>16&255]<<16^S[p>>8&255]<<8^S[255&m]^d[f++],a=u,u=c,c=p,p=m,m=a}}class l extends r{constructor(){super(r),this.jobs=[],this.delay=1,this.timeout_=null}processJob_(){this.jobs.shift()(),this.jobs.length?this.timeout_=setTimeout(this.processJob_.bind(this),this.delay):this.timeout_=null}push(e){this.jobs.push(e),this.timeout_||(this.timeout_=setTimeout(this.processJob_.bind(this),this.delay))}}let h=function(e){return e<<24|(65280&e)<<8|(0xff0000&e)>>8|e>>>24},d=function(e,t,i){let s,r,n,a,l,d,u,c,p;let m=new Int32Array(e.buffer,e.byteOffset,e.byteLength>>2),g=new o(Array.prototype.slice.call(t)),f=new Uint8Array(e.byteLength),_=new Int32Array(f.buffer);for(p=0,s=i[0],r=i[1],n=i[2],a=i[3];p{let s=e[i];("function"===ArrayBuffer.isView?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer)?t[i]={bytes:s.buffer,byteOffset:s.byteOffset,byteLength:s.byteLength}:t[i]=s}),t};self.onmessage=function(e){let t=e.data,i=new Uint8Array(t.encrypted.bytes,t.encrypted.byteOffset,t.encrypted.byteLength);new u(i,new Uint32Array(t.key.bytes,t.key.byteOffset,t.key.byteLength/4),new Uint32Array(t.iv.bytes,t.iv.byteOffset,t.iv.byteLength/4),function(e,i){self.postMessage(m({source:t.source,decrypted:i}),[i.buffer])})}})));let oH=e=>{let t=e.default?"main":"alternative";return e.characteristics&&e.characteristics.indexOf("public.accessibility.describes-video")>=0&&(t="main-desc"),t},oV=(e,t)=>{e.abort(),e.pause(),t&&t.activePlaylistLoader&&(t.activePlaylistLoader.pause(),t.activePlaylistLoader=null)},oz=(e,t)=>{t.activePlaylistLoader=e,e.load()},oW=(e,t)=>()=>{let{segmentLoaders:{[e]:i,main:s},mediaTypes:{[e]:r}}=t,n=r.activeTrack(),a=r.getActiveGroup(),o=r.activePlaylistLoader,l=r.lastGroup_;if(!a||!l||a.id!==l.id){if(r.lastGroup_=a,r.lastTrack_=n,oV(i,r),a&&!a.isMainPlaylist){if(!a.playlistLoader){o&&s.resetEverything();return}i.resyncLoader(),oz(a.playlistLoader,r)}}},oG=(e,t)=>()=>{let{segmentLoaders:{[e]:i},mediaTypes:{[e]:s}}=t;s.lastGroup_=null,i.abort(),i.pause()},oK=(e,t)=>()=>{let{mainPlaylistLoader:i,segmentLoaders:{[e]:s,main:r},mediaTypes:{[e]:n}}=t,a=n.activeTrack(),o=n.getActiveGroup(),l=n.activePlaylistLoader,h=n.lastTrack_;if(!h||!a||h.id!==a.id){if(n.lastGroup_=o,n.lastTrack_=a,oV(s,n),o){if(o.isMainPlaylist){if(!a||!h||a.id===h.id)return;let e=t.vhs.playlistController_,s=e.selectPlaylist();if(e.media()===s)return;n.logger_(`track change. Switching main audio from ${h.id} to ${a.id}`),i.pause(),r.resetEverything(),e.fastQualityChange_(s);return}if("AUDIO"===e){if(!o.playlistLoader){r.setAudio(!0),r.resetEverything();return}s.setAudio(!0),r.setAudio(!1)}if(l===o.playlistLoader){oz(o.playlistLoader,n);return}s.track&&s.track(a),s.resetEverything(),oz(o.playlistLoader,n)}}},oQ={AUDIO:(e,t)=>()=>{let{mediaTypes:{[e]:i},excludePlaylist:s}=t,r=i.activeTrack(),n=i.activeGroup(),a=(n.filter(e=>e.default)[0]||n[0]).id,o=i.tracks[a];if(r===o){s({error:{message:"Problem encountered loading the default audio track."}});return}for(let e in rk.log.warn("Problem encountered loading the alternate audio track.Switching back to default."),i.tracks)i.tracks[e].enabled=i.tracks[e]===o;i.onTrackChanged()},SUBTITLES:(e,t)=>()=>{let{mediaTypes:{[e]:i}}=t;rk.log.warn("Problem encountered loading the subtitle track.Disabling subtitle track.");let s=i.activeTrack();s&&(s.mode="disabled"),i.onTrackChanged()}},oY={AUDIO:(e,t,i)=>{if(!t)return;let{tech:s,requestOptions:r,segmentLoaders:{[e]:n}}=i;t.on("loadedmetadata",()=>{let e=t.media();n.playlist(e,r),(!s.paused()||e.endList&&"none"!==s.preload())&&n.load()}),t.on("loadedplaylist",()=>{n.playlist(t.media(),r),s.paused()||n.load()}),t.on("error",oQ[e](e,i))},SUBTITLES:(e,t,i)=>{let{tech:s,requestOptions:r,segmentLoaders:{[e]:n},mediaTypes:{[e]:a}}=i;t.on("loadedmetadata",()=>{let e=t.media();n.playlist(e,r),n.track(a.activeTrack()),(!s.paused()||e.endList&&"none"!==s.preload())&&n.load()}),t.on("loadedplaylist",()=>{n.playlist(t.media(),r),s.paused()||n.load()}),t.on("error",oQ[e](e,i))}},oX={AUDIO:(e,t)=>{let{vhs:i,sourceType:s,segmentLoaders:{[e]:r},requestOptions:n,main:{mediaGroups:a},mediaTypes:{[e]:{groups:o,tracks:l,logger_:h}},mainPlaylistLoader:d}=t,u=ne(d.main);for(let r in(!a[e]||0===Object.keys(a[e]).length)&&(a[e]={main:{default:{default:!0}}},u&&(a[e].main.default.playlists=d.main.playlists)),a[e])for(let c in o[r]||(o[r]=[]),a[e][r]){let p,m=a[e][r][c];if(u?(h(`AUDIO group '${r}' label '${c}' is a main playlist`),m.isMainPlaylist=!0,p=null):p="vhs-json"===s&&m.playlists?new nC(m.playlists[0],i,n):m.resolvedUri?new nC(m.resolvedUri,i,n):m.playlists&&"dash"===s?new n4(m.playlists[0],i,n,d):null,m=rD({id:c,playlistLoader:p},m),oY[e](e,m.playlistLoader,t),o[r].push(m),void 0===l[c]){let e=new rk.AudioTrack({id:c,kind:oH(m),enabled:!1,language:m.language,default:m.default,label:c});l[c]=e}}r.on("error",oQ[e](e,t))},SUBTITLES:(e,t)=>{let{tech:i,vhs:s,sourceType:r,segmentLoaders:{[e]:n},requestOptions:a,main:{mediaGroups:o},mediaTypes:{[e]:{groups:l,tracks:h}},mainPlaylistLoader:d}=t;for(let n in o[e])for(let u in l[n]||(l[n]=[]),o[e][n]){let c;if(!s.options_.useForcedSubtitles&&o[e][n][u].forced)continue;let p=o[e][n][u];if("hls"===r)c=new nC(p.resolvedUri,s,a);else if("dash"===r){if(!p.playlists.filter(e=>e.excludeUntil!==1/0).length)return;c=new n4(p.playlists[0],s,a,d)}else"vhs-json"===r&&(c=new nC(p.playlists?p.playlists[0]:p.resolvedUri,s,a));if(p=rD({id:u,playlistLoader:c},p),oY[e](e,p.playlistLoader,t),l[n].push(p),void 0===h[u]){let e=i.addRemoteTextTrack({id:u,kind:"subtitles",default:p.default&&p.autoselect,language:p.language,label:u},!1).track;h[u]=e}}n.on("error",oQ[e](e,t))},"CLOSED-CAPTIONS":(e,t)=>{let{tech:i,main:{mediaGroups:s},mediaTypes:{[e]:{groups:r,tracks:n}}}=t;for(let t in s[e])for(let a in r[t]||(r[t]=[]),s[e][t]){let o=s[e][t][a];if(!/^(?:CC|SERVICE)/.test(o.instreamId))continue;let l=i.options_.vhs&&i.options_.vhs.captionServices||{},h={label:a,language:o.language,instreamId:o.instreamId,default:o.default&&o.autoselect};if(l[h.instreamId]&&(h=rD(h,l[h.instreamId])),void 0===h.default&&delete h.default,r[t].push(rD({id:a},o)),void 0===n[a]){let e=i.addRemoteTextTrack({id:h.instreamId,kind:"captions",default:h.default,language:h.language,label:h.label},!1).track;n[a]=e}}}},oJ=(e,t)=>{for(let i=0;ii=>{let{mainPlaylistLoader:s,mediaTypes:{[e]:{groups:r}}}=t,n=s.media();if(!n)return null;let a=null;n.attributes[e]&&(a=r[n.attributes[e]]);let o=Object.keys(r);if(!a){if("AUDIO"===e&&o.length>1&&ne(t.main))for(let e=0;ee.id===i.id)[0]||null},o0={AUDIO:(e,t)=>()=>{let{mediaTypes:{[e]:{tracks:i}}}=t;for(let e in i)if(i[e].enabled)return i[e];return null},SUBTITLES:(e,t)=>()=>{let{mediaTypes:{[e]:{tracks:i}}}=t;for(let e in i)if("showing"===i[e].mode||"hidden"===i[e].mode)return i[e];return null}},o1=(e,{mediaTypes:t})=>()=>{let i=t[e].activeTrack();return i?t[e].activeGroup(i):null},o2=e=>{["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(t=>{oX[t](t,e)});let{mediaTypes:t,mainPlaylistLoader:i,tech:s,vhs:r,segmentLoaders:{AUDIO:n,main:a}}=e;["AUDIO","SUBTITLES"].forEach(i=>{t[i].activeGroup=oZ(i,e),t[i].activeTrack=o0[i](i,e),t[i].onGroupChanged=oW(i,e),t[i].onGroupChanging=oG(i,e),t[i].onTrackChanged=oK(i,e),t[i].getActiveGroup=o1(i,e)});let o=t.AUDIO.activeGroup();if(o){let e=(o.filter(e=>e.default)[0]||o[0]).id;t.AUDIO.tracks[e].enabled=!0,t.AUDIO.onGroupChanged(),t.AUDIO.onTrackChanged(),t.AUDIO.getActiveGroup().playlistLoader?(a.setAudio(!1),n.setAudio(!0)):a.setAudio(!0)}i.on("mediachange",()=>{["AUDIO","SUBTITLES"].forEach(e=>t[e].onGroupChanged())}),i.on("mediachanging",()=>{["AUDIO","SUBTITLES"].forEach(e=>t[e].onGroupChanging())});let l=()=>{t.AUDIO.onTrackChanged(),s.trigger({type:"usage",name:"vhs-audio-change"})};for(let e in s.audioTracks().addEventListener("change",l),s.remoteTextTracks().addEventListener("change",t.SUBTITLES.onTrackChanged),r.on("dispose",()=>{s.audioTracks().removeEventListener("change",l),s.remoteTextTracks().removeEventListener("change",t.SUBTITLES.onTrackChanged)}),s.clearTracks("audio"),t.AUDIO.tracks)s.audioTracks().addTrack(t.AUDIO.tracks[e])},o4=()=>{let e={};return["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(t=>{e[t]={groups:{},tracks:{},activePlaylistLoader:null,activeGroup:of,activeTrack:of,getActiveGroup:of,onGroupChanged:of,onTrackChanged:of,lastTrack_:null,logger_:rL(`MediaGroups[${t}]`)}}),e};class o8{constructor(){this.priority_=[],this.pathwayClones_=new Map}set version(e){1===e&&(this.version_=e)}set ttl(e){this.ttl_=e||300}set reloadUri(e){e&&(this.reloadUri_=rP(this.reloadUri_,e))}set priority(e){e&&e.length&&(this.priority_=e)}set pathwayClones(e){e&&e.length&&(this.pathwayClones_=new Map(e.map(e=>[e.ID,e])))}get version(){return this.version_}get ttl(){return this.ttl_}get reloadUri(){return this.reloadUri_}get priority(){return this.priority_}get pathwayClones(){return this.pathwayClones_}}class o5 extends rk.EventTarget{constructor(e,t){super(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=!1,this.availablePathways_=new Set,this.steeringManifest=new o8,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.currentPathwayClones=new Map,this.nextPathwayClones=new Map,this.excludedSteeringManifestURLs=new Set,this.logger_=rL("Content Steering"),this.xhr_=e,this.getBandwidth_=t}assignTagProperties(e,t){this.manifestType_=t.serverUri?"HLS":"DASH";let i=t.serverUri||t.serverURL;if(!i){this.logger_(`steering manifest URL is ${i}, cannot request steering manifest.`),this.trigger("error");return}if(i.startsWith("data:")){this.decodeDataUriManifest_(i.substring(i.indexOf(",")+1));return}this.steeringManifest.reloadUri=rP(e,i),this.defaultPathway=t.pathwayId||t.defaultServiceLocation,this.queryBeforeStart=t.queryBeforeStart,this.proxyServerUrl_=t.proxyServerURL,this.defaultPathway&&!this.queryBeforeStart&&this.trigger("content-steering")}requestSteeringManifest(e){let t=this.steeringManifest.reloadUri;if(!t)return;let i=e?t:this.getRequestURI(t);if(!i){this.logger_("No valid content steering manifest URIs. Stopping content steering."),this.trigger("error"),this.dispose();return}let s={contentSteeringInfo:{uri:i}};this.trigger({type:"contentsteeringloadstart",metadata:s}),this.request_=this.xhr_({uri:i,requestType:"content-steering-manifest"},(e,t)=>{let r;if(e){if(410===t.status){this.logger_(`manifest request 410 ${e}.`),this.logger_(`There will be no more content steering requests to ${i} this session.`),this.excludedSteeringManifestURLs.add(i);return}if(429===t.status){let i=t.responseHeaders["retry-after"];this.logger_(`manifest request 429 ${e}.`),this.logger_(`content steering will retry in ${i} seconds.`),this.startTTLTimeout_(parseInt(i,10));return}this.logger_(`manifest failed to load ${e}.`),this.startTTLTimeout_();return}this.trigger({type:"contentsteeringloadcomplete",metadata:s});try{r=JSON.parse(this.request_.responseText)}catch(t){let e={errorType:rk.Error.StreamingContentSteeringParserError,error:t};this.trigger({type:"error",metadata:e})}this.assignSteeringProperties_(r);let n={contentSteeringInfo:s.contentSteeringInfo,contentSteeringManifest:{version:this.steeringManifest.version,reloadUri:this.steeringManifest.reloadUri,priority:this.steeringManifest.priority}};this.trigger({type:"contentsteeringparsed",metadata:n}),this.startTTLTimeout_()})}setProxyServerUrl_(e){let t=new(d()).URL(e),i=new(d()).URL(this.proxyServerUrl_);return i.searchParams.set("url",encodeURI(t.toString())),this.setSteeringParams_(i.toString())}decodeDataUriManifest_(e){let t=JSON.parse(d().atob(e));this.assignSteeringProperties_(t)}setSteeringParams_(e){let t=new(d()).URL(e),i=this.getPathway(),s=this.getBandwidth_();if(i){let e=`_${this.manifestType_}_pathway`;t.searchParams.set(e,i)}if(s){let e=`_${this.manifestType_}_throughput`;t.searchParams.set(e,s)}return t.toString()}assignSteeringProperties_(e){if(this.steeringManifest.version=e.VERSION,!this.steeringManifest.version){this.logger_(`manifest version is ${e.VERSION}, which is not supported.`),this.trigger("error");return}this.steeringManifest.ttl=e.TTL,this.steeringManifest.reloadUri=e["RELOAD-URI"],this.steeringManifest.priority=e["PATHWAY-PRIORITY"]||e["SERVICE-LOCATION-PRIORITY"],this.steeringManifest.pathwayClones=e["PATHWAY-CLONES"],this.nextPathwayClones=this.steeringManifest.pathwayClones,this.availablePathways_.size||(this.logger_("There are no available pathways for content steering. Ending content steering."),this.trigger("error"),this.dispose());let t=(e=>{for(let t of e)if(this.availablePathways_.has(t))return t;return[...this.availablePathways_][0]})(this.steeringManifest.priority);this.currentPathway!==t&&(this.currentPathway=t,this.trigger("content-steering"))}getPathway(){return this.currentPathway||this.defaultPathway}getRequestURI(e){if(!e)return null;let t=e=>this.excludedSteeringManifestURLs.has(e);if(this.proxyServerUrl_){let i=this.setProxyServerUrl_(e);if(!t(i))return i}let i=this.setSteeringParams_(e);return t(i)?null:i}startTTLTimeout_(e=this.steeringManifest.ttl){this.ttlTimeout_=d().setTimeout(()=>{this.requestSteeringManifest()},1e3*e)}clearTTLTimeout_(){d().clearTimeout(this.ttlTimeout_),this.ttlTimeout_=null}abort(){this.request_&&this.request_.abort(),this.request_=null}dispose(){this.off("content-steering"),this.off("error"),this.abort(),this.clearTTLTimeout_(),this.currentPathway=null,this.defaultPathway=null,this.queryBeforeStart=null,this.proxyServerUrl_=null,this.manifestType_=null,this.ttlTimeout_=null,this.request_=null,this.excludedSteeringManifestURLs=new Set,this.availablePathways_=new Set,this.steeringManifest=new o8}addAvailablePathway(e){e&&this.availablePathways_.add(e)}clearAvailablePathways(){this.availablePathways_.clear()}excludePathway(e){return this.availablePathways_.delete(e)}didDASHTagChange(e,t){return!t&&this.steeringManifest.reloadUri||t&&(rP(e,t.serverURL)!==this.steeringManifest.reloadUri||t.defaultServiceLocation!==this.defaultPathway||t.queryBeforeStart!==this.queryBeforeStart||t.proxyServerURL!==this.proxyServerUrl_)}getAvailablePathways(){return this.availablePathways_}}let o3=(e,t)=>{let i=null;return(...s)=>{clearTimeout(i),i=setTimeout(()=>{e.apply(null,s)},t)}},o6=["mediaRequests","mediaRequestsAborted","mediaRequestsTimedout","mediaRequestsErrored","mediaTransferDuration","mediaBytesTransferred","mediaAppends"],o7=function(e){return this.audioSegmentLoader_[e]+this.mainSegmentLoader_[e]},o9=function({currentPlaylist:e,buffered:t,currentTime:i,nextPlaylist:s,bufferLowWaterLine:r,bufferHighWaterLine:n,duration:a,bufferBasedABR:o,log:l}){if(!s)return rk.log.warn("We received no playlist to switch to. Please check your stream."),!1;let h=`allowing switch ${e&&e.id||"null"} -> ${s.id}`;if(!e)return l(`${h} as current playlist is not set`),!0;if(s.id===e.id)return!1;let d=!!rB(t,i).length;if(!e.endList)return d||"number"!=typeof e.partTargetDuration?(l(`${h} as current playlist is live`),!0):(l(`not ${h} as current playlist is live llhls, but currentTime isn't in buffered.`),!1);let u=rz(t,i),c=o?n8.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE:n8.MAX_BUFFER_LOW_WATER_LINE;if(am)&&u>=r){let e=`${h} as forwardBuffer >= bufferLowWaterLine (${u} >= ${r})`;return o&&(e+=` and next bandwidth > current bandwidth (${p} > ${m})`),l(e),!0}return l(`not ${h} as no switching criteria met`),!1};class le extends rk.EventTarget{constructor(e){super(),this.fastQualityChange_=o3(this.fastQualityChange_.bind(this),100);let{src:t,withCredentials:i,tech:s,bandwidth:r,externVhs:n,useCueTags:a,playlistExclusionDuration:o,enableLowInitialPlaylist:h,sourceType:u,cacheEncryptionKeys:c,bufferBasedABR:p,leastPixelDiffSelector:m,captionServices:g,experimentalUseMMS:f}=e;if(!t)throw Error("A non-empty playlist URL or JSON manifest string is required");let{maxPlaylistRetries:_}=e;null==_&&(_=1/0),l=n,this.bufferBasedABR=!!p,this.leastPixelDiffSelector=!!m,this.withCredentials=i,this.tech_=s,this.vhs_=s.vhs,this.player_=e.player_,this.sourceType_=u,this.useCueTags_=a,this.playlistExclusionDuration=o,this.maxPlaylistRetries=_,this.enableLowInitialPlaylist=h,this.usingManagedMediaSource_=!1,this.useCueTags_&&(this.cueTagsTrack_=this.tech_.addTextTrack("metadata","ad-cues"),this.cueTagsTrack_.inBandMetadataTrackDispatchType=""),this.requestOptions_={withCredentials:i,maxPlaylistRetries:_,timeout:null},this.on("error",this.pauseLoading),this.mediaTypes_=o4(),f&&d().ManagedMediaSource?(this.tech_.el_.disableRemotePlayback=!0,this.mediaSource=new(d()).ManagedMediaSource,this.usingManagedMediaSource_=!0,rk.log("Using ManagedMediaSource")):d().MediaSource&&(this.mediaSource=new(d()).MediaSource),this.handleDurationChange_=this.handleDurationChange_.bind(this),this.handleSourceOpen_=this.handleSourceOpen_.bind(this),this.handleSourceEnded_=this.handleSourceEnded_.bind(this),this.load=this.load.bind(this),this.pause=this.pause.bind(this),this.mediaSource.addEventListener("durationchange",this.handleDurationChange_),this.mediaSource.addEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.addEventListener("sourceended",this.handleSourceEnded_),this.mediaSource.addEventListener("startstreaming",this.load),this.mediaSource.addEventListener("endstreaming",this.pause),this.seekable_=rO(),this.hasPlayed_=!1,this.syncController_=new oF(e),this.segmentMetadataTrack_=s.addRemoteTextTrack({kind:"metadata",label:"segment-metadata"},!1).track,this.decrypter_=new oq,this.sourceUpdater_=new ox(this.mediaSource),this.inbandTextTracks_={},this.timelineChangeController_=new o$,this.keyStatusMap_=new Map;let y={vhs:this.vhs_,parse708captions:e.parse708captions,useDtsForTimestampOffset:e.useDtsForTimestampOffset,captionServices:g,mediaSource:this.mediaSource,currentTime:this.tech_.currentTime.bind(this.tech_),seekable:()=>this.seekable(),seeking:()=>this.tech_.seeking(),duration:()=>this.duration(),hasPlayed:()=>this.hasPlayed_,goalBufferLength:()=>this.goalBufferLength(),bandwidth:r,syncController:this.syncController_,decrypter:this.decrypter_,sourceType:this.sourceType_,inbandTextTracks:this.inbandTextTracks_,cacheEncryptionKeys:c,sourceUpdater:this.sourceUpdater_,timelineChangeController:this.timelineChangeController_,exactManifestTimings:e.exactManifestTimings,addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)};this.mainPlaylistLoader_="dash"===this.sourceType_?new n4(t,this.vhs_,rD(this.requestOptions_,{addMetadataToTextTrack:this.addMetadataToTextTrack.bind(this)})):new nC(t,this.vhs_,rD(this.requestOptions_,{addDateRangesToTextTrack:this.addDateRangesToTextTrack_.bind(this)})),this.setupMainPlaylistLoaderListeners_(),this.mainSegmentLoader_=new og(rD(y,{segmentMetadataTrack:this.segmentMetadataTrack_,loaderType:"main"}),e),this.audioSegmentLoader_=new og(rD(y,{loaderType:"audio"}),e),this.subtitleSegmentLoader_=new oD(rD(y,{loaderType:"vtt",featuresNativeTextTracks:this.tech_.featuresNativeTextTracks,loadVttJs:()=>new Promise((e,t)=>{function i(){s.off("vttjserror",r),e()}function r(){s.off("vttjsloaded",i),t()}s.one("vttjsloaded",i),s.one("vttjserror",r),s.addWebVttScript_()})}),e),this.contentSteeringController_=new o5(this.vhs_.xhr,()=>this.mainSegmentLoader_.bandwidth),this.setupSegmentLoaderListeners_(),this.bufferBasedABR&&(this.mainPlaylistLoader_.one("loadedplaylist",()=>this.startABRTimer_()),this.tech_.on("pause",()=>this.stopABRTimer_()),this.tech_.on("play",()=>this.startABRTimer_())),o6.forEach(e=>{this[e+"_"]=o7.bind(this,e)}),this.logger_=rL("pc"),this.triggeredFmp4Usage=!1,"none"===this.tech_.preload()?(this.loadOnPlay_=()=>{this.loadOnPlay_=null,this.mainPlaylistLoader_.load()},this.tech_.one("play",this.loadOnPlay_)):this.mainPlaylistLoader_.load(),this.timeToLoadedData__=-1,this.mainAppendsToLoadedData__=-1,this.audioAppendsToLoadedData__=-1;let v="none"===this.tech_.preload()?"play":"loadstart";this.tech_.one(v,()=>{let e=Date.now();this.tech_.one("loadeddata",()=>{this.timeToLoadedData__=Date.now()-e,this.mainAppendsToLoadedData__=this.mainSegmentLoader_.mediaAppends,this.audioAppendsToLoadedData__=this.audioSegmentLoader_.mediaAppends})})}mainAppendsToLoadedData_(){return this.mainAppendsToLoadedData__}audioAppendsToLoadedData_(){return this.audioAppendsToLoadedData__}appendsToLoadedData_(){let e=this.mainAppendsToLoadedData_(),t=this.audioAppendsToLoadedData_();return -1===e||-1===t?-1:e+t}timeToLoadedData_(){return this.timeToLoadedData__}checkABR_(e="abr"){let t=this.selectPlaylist();t&&this.shouldSwitchToMedia_(t)&&this.switchMedia_(t,e)}switchMedia_(e,t,i){let s=this.media(),r=s&&(s.id||s.uri),n=e&&(e.id||e.uri);if(r&&r!==n){this.logger_(`switch media ${r} -> ${n} from ${t}`);let i={renditionInfo:{id:n,bandwidth:e.attributes.BANDWIDTH,resolution:e.attributes.RESOLUTION,codecs:e.attributes.CODECS},cause:t};this.trigger({type:"renditionselected",metadata:i}),this.tech_.trigger({type:"usage",name:`vhs-rendition-change-${t}`})}this.mainPlaylistLoader_.media(e,i)}switchMediaForDASHContentSteering_(){["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach(e=>{let t=this.mediaTypes_[e],i=t?t.activeGroup():null,s=this.contentSteeringController_.getPathway();if(i&&s){let t=(i.length?i[0].playlists:i.playlists).filter(e=>e.attributes.serviceLocation===s);t.length&&this.mediaTypes_[e].activePlaylistLoader.media(t[0])}})}startABRTimer_(){this.stopABRTimer_(),this.abrTimer_=d().setInterval(()=>this.checkABR_(),250)}stopABRTimer_(){!(this.tech_.scrubbing&&this.tech_.scrubbing())&&(d().clearInterval(this.abrTimer_),this.abrTimer_=null)}getAudioTrackPlaylists_(){let e;let t=this.main(),i=t&&t.playlists||[];if(!t||!t.mediaGroups||!t.mediaGroups.AUDIO)return i;let s=t.mediaGroups.AUDIO,r=Object.keys(s);if(Object.keys(this.mediaTypes_.AUDIO.groups).length)e=this.mediaTypes_.AUDIO.activeTrack();else{let t=s.main||r.length&&s[r[0]];for(let i in t)if(t[i].default){e={label:i};break}}if(!e)return i;let n=[];for(let i in s)if(s[i][e.label]){let r=s[i][e.label];if(r.playlists&&r.playlists.length)n.push.apply(n,r.playlists);else if(r.uri)n.push(r);else if(t.playlists.length)for(let e=0;e{let e=this.mainPlaylistLoader_.media(),t=1500*e.targetDuration;r6(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,e.endList&&"none"!==this.tech_.preload()&&(this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.mainSegmentLoader_.load()),o2({sourceType:this.sourceType_,segmentLoaders:{AUDIO:this.audioSegmentLoader_,SUBTITLES:this.subtitleSegmentLoader_,main:this.mainSegmentLoader_},tech:this.tech_,requestOptions:this.requestOptions_,mainPlaylistLoader:this.mainPlaylistLoader_,vhs:this.vhs_,main:this.main(),mediaTypes:this.mediaTypes_,excludePlaylist:this.excludePlaylist.bind(this)}),this.triggerPresenceUsage_(this.main(),e),this.setupFirstPlay(),!this.mediaTypes_.AUDIO.activePlaylistLoader||this.mediaTypes_.AUDIO.activePlaylistLoader.media()?this.trigger("selectedinitialmedia"):this.mediaTypes_.AUDIO.activePlaylistLoader.one("loadedmetadata",()=>{this.trigger("selectedinitialmedia")})}),this.mainPlaylistLoader_.on("loadedplaylist",()=>{this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_);let e=this.mainPlaylistLoader_.media();if(!e){let t;if(this.attachContentSteeringListeners_(),this.initContentSteeringController_(),this.excludeUnsupportedVariants_(),this.enableLowInitialPlaylist&&(t=this.selectInitialPlaylist()),t||(t=this.selectPlaylist()),!t||!this.shouldSwitchToMedia_(t)||(this.initialMedia_=t,this.switchMedia_(this.initialMedia_,"initial"),!("vhs-json"===this.sourceType_&&this.initialMedia_.segments)))return;e=this.initialMedia_}this.handleUpdatedMediaPlaylist(e)}),this.mainPlaylistLoader_.on("error",()=>{let e=this.mainPlaylistLoader_.error;this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainPlaylistLoader_.on("mediachanging",()=>{this.mainSegmentLoader_.abort(),this.mainSegmentLoader_.pause()}),this.mainPlaylistLoader_.on("mediachange",()=>{let e=this.mainPlaylistLoader_.media(),t=1500*e.targetDuration;r6(this.mainPlaylistLoader_.main,this.mainPlaylistLoader_.media())?this.requestOptions_.timeout=0:this.requestOptions_.timeout=t,"dash"===this.sourceType_&&this.mainPlaylistLoader_.isPaused&&this.mainPlaylistLoader_.load(),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_?this.runFastQualitySwitch_():this.mainSegmentLoader_.load(),this.tech_.trigger({type:"mediachange",bubbles:!0})}),this.mainPlaylistLoader_.on("playlistunchanged",()=>{let e=this.mainPlaylistLoader_.media();"playlist-unchanged"!==e.lastExcludeReason_&&this.stuckAtPlaylistEnd_(e)&&(this.excludePlaylist({error:{message:"Playlist no longer updating.",reason:"playlist-unchanged"}}),this.tech_.trigger("playliststuck"))}),this.mainPlaylistLoader_.on("renditiondisabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-disabled"})}),this.mainPlaylistLoader_.on("renditionenabled",()=>{this.tech_.trigger({type:"usage",name:"vhs-rendition-enabled"})}),["manifestrequeststart","manifestrequestcomplete","manifestparsestart","manifestparsecomplete","playlistrequeststart","playlistrequestcomplete","playlistparsestart","playlistparsecomplete","renditiondisabled","renditionenabled"].forEach(e=>{this.mainPlaylistLoader_.on(e,e=>{this.player_.trigger((0,_.A)({},e))})})}handleUpdatedMediaPlaylist(e){this.useCueTags_&&this.updateAdCues_(e),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.playlist(e,this.requestOptions_),this.waitingForFastQualityPlaylistReceived_&&this.runFastQualitySwitch_(),this.updateDuration(!e.endList),!this.tech_.paused()&&(this.mainSegmentLoader_.load(),this.audioSegmentLoader_&&this.audioSegmentLoader_.load())}triggerPresenceUsage_(e,t){let i=e.mediaGroups||{},s=!0,r=Object.keys(i.AUDIO);for(let e in i.AUDIO)for(let t in i.AUDIO[e])i.AUDIO[e][t].uri||(s=!1);s&&this.tech_.trigger({type:"usage",name:"vhs-demuxed"}),Object.keys(i.SUBTITLES).length&&this.tech_.trigger({type:"usage",name:"vhs-webvtt"}),l.Playlist.isAes(t)&&this.tech_.trigger({type:"usage",name:"vhs-aes"}),r.length&&Object.keys(i.AUDIO[r[0]]).length>1&&this.tech_.trigger({type:"usage",name:"vhs-alternate-audio"}),this.useCueTags_&&this.tech_.trigger({type:"usage",name:"vhs-playlist-cue-tags"})}shouldSwitchToMedia_(e){let t=this.mainPlaylistLoader_.media()||this.mainPlaylistLoader_.pendingMedia_,i=this.tech_.currentTime(),s=this.bufferLowWaterLine(),r=this.bufferHighWaterLine();return o9({buffered:this.tech_.buffered(),currentTime:i,currentPlaylist:t,nextPlaylist:e,bufferLowWaterLine:s,bufferHighWaterLine:r,duration:this.duration(),bufferBasedABR:this.bufferBasedABR,log:this.logger_})}setupSegmentLoaderListeners_(){this.mainSegmentLoader_.on("bandwidthupdate",()=>{this.checkABR_("bandwidthupdate"),this.tech_.trigger("bandwidthupdate")}),this.mainSegmentLoader_.on("timeout",()=>{this.bufferBasedABR&&this.mainSegmentLoader_.load()}),this.bufferBasedABR||this.mainSegmentLoader_.on("progress",()=>{this.trigger("progress")}),this.mainSegmentLoader_.on("error",()=>{let e=this.mainSegmentLoader_.error();this.excludePlaylist({playlistToExclude:e.playlist,error:e})}),this.mainSegmentLoader_.on("appenderror",()=>{this.error=this.mainSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.mainSegmentLoader_.on("timestampoffset",()=>{this.tech_.trigger({type:"usage",name:"vhs-timestamp-offset"})}),this.audioSegmentLoader_.on("syncinfoupdate",()=>{this.onSyncInfoUpdate_()}),this.audioSegmentLoader_.on("appenderror",()=>{this.error=this.audioSegmentLoader_.error_,this.trigger("error")}),this.mainSegmentLoader_.on("ended",()=>{this.logger_("main segment loader ended"),this.onEndOfStream()}),this.timelineChangeController_.on("audioTimelineBehind",()=>{let e=this.audioSegmentLoader_.pendingSegment_;if(!e||!e.segment||!e.segment.syncInfo)return;let t=e.segment.syncInfo.end+.01;this.tech_.setCurrentTime(t)}),this.timelineChangeController_.on("fixBadTimelineChange",()=>{this.logger_("Fix bad timeline change. Restarting al segment loaders..."),this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}),this.mainSegmentLoader_.on("earlyabort",e=>{!this.bufferBasedABR&&(this.delegateLoaders_("all",["abort"]),this.excludePlaylist({error:{message:"Aborted early because there isn't enough bandwidth to complete the request without rebuffering."},playlistExclusionDuration:10}))});let e=()=>{if(!this.sourceUpdater_.hasCreatedSourceBuffers())return this.tryToCreateSourceBuffers_();let e=this.getCodecsOrExclude_();e&&this.sourceUpdater_.addOrChangeSourceBuffers(e)};this.mainSegmentLoader_.on("trackinfo",e),this.audioSegmentLoader_.on("trackinfo",e),this.mainSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("fmp4",()=>{this.triggeredFmp4Usage||(this.tech_.trigger({type:"usage",name:"vhs-fmp4"}),this.triggeredFmp4Usage=!0)}),this.audioSegmentLoader_.on("ended",()=>{this.logger_("audioSegmentLoader ended"),this.onEndOfStream()}),["segmentselected","segmentloadstart","segmentloaded","segmentkeyloadstart","segmentkeyloadcomplete","segmentdecryptionstart","segmentdecryptioncomplete","segmenttransmuxingstart","segmenttransmuxingcomplete","segmenttransmuxingtrackinfoavailable","segmenttransmuxingtiminginfoavailable","segmentappendstart","appendsdone","bandwidthupdated","timelinechange","codecschange"].forEach(e=>{this.mainSegmentLoader_.on(e,e=>{this.player_.trigger((0,_.A)({},e))}),this.audioSegmentLoader_.on(e,e=>{this.player_.trigger((0,_.A)({},e))}),this.subtitleSegmentLoader_.on(e,e=>{this.player_.trigger((0,_.A)({},e))})})}mediaSecondsLoaded_(){return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded+this.mainSegmentLoader_.mediaSecondsLoaded)}load(){this.mainSegmentLoader_.load(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.load(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.load()}pause(){this.mainSegmentLoader_.pause(),this.mediaTypes_.AUDIO.activePlaylistLoader&&this.audioSegmentLoader_.pause(),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&this.subtitleSegmentLoader_.pause()}fastQualityChange_(e=this.selectPlaylist()){if(e&&e===this.mainPlaylistLoader_.media()){this.logger_("skipping fastQualityChange because new media is same as old");return}this.switchMedia_(e,"fast-quality"),this.waitingForFastQualityPlaylistReceived_=!0}runFastQualitySwitch_(){this.waitingForFastQualityPlaylistReceived_=!1,this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()}play(){if(this.setupFirstPlay())return;this.tech_.ended()&&this.tech_.setCurrentTime(0),this.hasPlayed_&&this.load();let e=this.tech_.seekable();if(this.tech_.duration()===1/0&&this.tech_.currentTime(){})}this.trigger("sourceopen")}handleSourceEnded_(){if(!this.inbandTextTracks_.metadataTrack_)return;let e=this.inbandTextTracks_.metadataTrack_.cues;if(!e||!e.length)return;let t=this.duration();e[e.length-1].endTime=isNaN(t)||Math.abs(t)===1/0?Number.MAX_VALUE:t}handleDurationChange_(){this.tech_.trigger("durationchange")}onEndOfStream(){let e=this.mainSegmentLoader_.ended_;if(this.mediaTypes_.AUDIO.activePlaylistLoader){let t=this.mainSegmentLoader_.getCurrentMediaInfo_();e=!t||t.hasVideo?e&&this.audioSegmentLoader_.ended_:this.audioSegmentLoader_.ended_}e&&(this.stopABRTimer_(),this.sourceUpdater_.endOfStream())}stuckAtPlaylistEnd_(e){if(!this.seekable().length)return!1;let t=this.syncController_.getExpiredTime(e,this.duration());if(null===t)return!1;let i=l.Playlist.playlistEnd(e,t),s=this.tech_.currentTime(),r=this.tech_.buffered();if(!r.length)return i-s<=rU;let n=r.end(r.length-1);return n-s<=rU&&i-n<=rU}excludePlaylist({playlistToExclude:e=this.mainPlaylistLoader_.media(),error:t={},playlistExclusionDuration:i}){let s;if(e=e||this.mainPlaylistLoader_.media(),i=i||t.playlistExclusionDuration||this.playlistExclusionDuration,!e){this.error=t,"open"!==this.mediaSource.readyState?this.trigger("error"):this.sourceUpdater_.endOfStream("network");return}e.playlistErrors_++;let r=this.mainPlaylistLoader_.main.playlists,n=r.filter(r5),a=1===n.length&&n[0]===e;if(1===r.length&&i!==1/0)return rk.log.warn(`Problem encountered with playlist ${e.id}. Trying again since it is the only playlist.`),this.tech_.trigger("retryplaylist"),this.mainPlaylistLoader_.load(a);if(a){if(this.main().contentSteering){let t=this.pathwayAttribute_(e),i=1e3*this.contentSteeringController_.steeringManifest.ttl;this.contentSteeringController_.excludePathway(t),this.excludeThenChangePathway_(),setTimeout(()=>{this.contentSteeringController_.addAvailablePathway(t)},i);return}let t=!1;r.forEach(i=>{if(i===e)return;let s=i.excludeUntil;void 0!==s&&s!==1/0&&(t=!0,delete i.excludeUntil)}),t&&(rk.log.warn("Removing other playlists from the exclusion list because the last rendition is about to be excluded."),this.tech_.trigger("retryplaylist"))}s=e.playlistErrors_>this.maxPlaylistRetries?1/0:Date.now()+1e3*i,e.excludeUntil=s,t.reason&&(e.lastExcludeReason_=t.reason),this.tech_.trigger("excludeplaylist"),this.tech_.trigger({type:"usage",name:"vhs-rendition-excluded"});let o=this.selectPlaylist();if(!o){this.error="Playback cannot continue. No available working or supported playlists.",this.trigger("error");return}let l=t.internal?this.logger_:rk.log.warn,h=t.message?" "+t.message:"";l(`${t.internal?"Internal problem":"Problem"} encountered with playlist ${e.id}.${h} Switching to playlist ${o.id}.`),o.attributes.AUDIO!==e.attributes.AUDIO&&this.delegateLoaders_("audio",["abort","pause"]),o.attributes.SUBTITLES!==e.attributes.SUBTITLES&&this.delegateLoaders_("subtitle",["abort","pause"]),this.delegateLoaders_("main",["abort","pause"]);let d=o.targetDuration/2*1e3||5e3,u="number"==typeof o.lastRequest&&Date.now()-o.lastRequest<=d;return this.switchMedia_(o,"exclude",a||u)}pauseLoading(){this.delegateLoaders_("all",["abort","pause"]),this.stopABRTimer_()}delegateLoaders_(e,t){let i=[],s="all"===e;(s||"main"===e)&&i.push(this.mainPlaylistLoader_);let r=[];(s||"audio"===e)&&r.push("AUDIO"),(s||"subtitle"===e)&&(r.push("CLOSED-CAPTIONS"),r.push("SUBTITLES")),r.forEach(e=>{let t=this.mediaTypes_[e]&&this.mediaTypes_[e].activePlaylistLoader;t&&i.push(t)}),["main","audio","subtitle"].forEach(t=>{let s=this[`${t}SegmentLoader_`];s&&(e===t||"all"===e)&&i.push(s)}),i.forEach(e=>t.forEach(t=>{"function"==typeof e[t]&&e[t]()}))}setCurrentTime(e){let t=rB(this.tech_.buffered(),e);return this.mainPlaylistLoader_&&this.mainPlaylistLoader_.media()&&this.mainPlaylistLoader_.media().segments?t&&t.length?e:void(this.mainSegmentLoader_.pause(),this.mainSegmentLoader_.resetEverything(),this.mediaTypes_.AUDIO.activePlaylistLoader&&(this.audioSegmentLoader_.pause(),this.audioSegmentLoader_.resetEverything()),this.mediaTypes_.SUBTITLES.activePlaylistLoader&&(this.subtitleSegmentLoader_.pause(),this.subtitleSegmentLoader_.resetEverything()),this.load()):0}duration(){if(!this.mainPlaylistLoader_)return 0;let e=this.mainPlaylistLoader_.media();return e?e.endList?this.mediaSource?this.mediaSource.duration:l.Playlist.duration(e):1/0:0}seekable(){return this.seekable_}getSeekableRange_(e,t){let i=e.media();if(!i)return null;let s=this.syncController_.getMediaSequenceSync(t);if(s&&s.isReliable){let e=s.start,t=s.end;if(!isFinite(e)||!isFinite(t))return null;let r=Math.max(0,t-l.Playlist.liveEdgeDelay(this.mainPlaylistLoader_.main,i));return rs||i>n?e:rO([[Math.max(i,r),Math.min(s,n)]])}onSyncInfoUpdate_(){let e;if(!this.mainPlaylistLoader_)return;let t=this.getSeekableRange_(this.mainPlaylistLoader_,"main");if(!t||this.mediaTypes_.AUDIO.activePlaylistLoader&&!(e=this.getSeekableRange_(this.mediaTypes_.AUDIO.activePlaylistLoader,"audio")))return;let i=this.seekable_;if(this.seekable_=this.computeFinalSeekable_(t,e),!this.seekable_||i&&i.length&&this.seekable_.length&&i.start(0)===this.seekable_.start(0)&&i.end(0)===this.seekable_.end(0))return;this.logger_(`seekable updated [${r$(this.seekable_)}]`);let s={seekableRanges:this.seekable_};this.trigger({type:"seekablerangeschanged",metadata:s}),this.tech_.trigger("seekablechanged")}updateDuration(e){if(this.updateDuration_&&(this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.updateDuration_=null),"open"!==this.mediaSource.readyState){this.updateDuration_=this.updateDuration.bind(this,e),this.mediaSource.addEventListener("sourceopen",this.updateDuration_);return}if(e){let e=this.seekable();if(!e.length)return;(isNaN(this.mediaSource.duration)||this.mediaSource.duration0&&(i=Math.max(i,t.end(t.length-1))),this.mediaSource.duration!==i&&this.sourceUpdater_.setDuration(i)}dispose(){this.trigger("dispose"),this.decrypter_.terminate(),this.mainPlaylistLoader_.dispose(),this.mainSegmentLoader_.dispose(),this.contentSteeringController_.dispose(),this.keyStatusMap_.clear(),this.loadOnPlay_&&this.tech_.off("play",this.loadOnPlay_),["AUDIO","SUBTITLES"].forEach(e=>{let t=this.mediaTypes_[e].groups;for(let e in t)t[e].forEach(e=>{e.playlistLoader&&e.playlistLoader.dispose()})}),this.audioSegmentLoader_.dispose(),this.subtitleSegmentLoader_.dispose(),this.sourceUpdater_.dispose(),this.timelineChangeController_.dispose(),this.stopABRTimer_(),this.updateDuration_&&this.mediaSource.removeEventListener("sourceopen",this.updateDuration_),this.mediaSource.removeEventListener("durationchange",this.handleDurationChange_),this.mediaSource.removeEventListener("sourceopen",this.handleSourceOpen_),this.mediaSource.removeEventListener("sourceended",this.handleSourceEnded_),this.off()}main(){return this.mainPlaylistLoader_.main}media(){return this.mainPlaylistLoader_.media()||this.initialMedia_}areMediaTypesKnown_(){let e=!!this.mediaTypes_.AUDIO.activePlaylistLoader,t=!!this.mainSegmentLoader_.getCurrentMediaInfo_(),i=!e||!!this.audioSegmentLoader_.getCurrentMediaInfo_();return!!t&&!!i}getCodecsOrExclude_(){let e;let t={main:this.mainSegmentLoader_.getCurrentMediaInfo_()||{},audio:this.audioSegmentLoader_.getCurrentMediaInfo_()||{}},i=this.mainSegmentLoader_.getPendingSegmentPlaylist()||this.media();t.video=t.main;let s=aN(this.main(),i),r={},n=!!this.mediaTypes_.AUDIO.activePlaylistLoader;if(t.main.hasVideo&&(r.video=s.video||t.main.videoCodec||b.dv),t.main.isMuxed&&(r.video+=`,${s.audio||t.main.audioCodec||b.Yg}`),(t.main.hasAudio&&!t.main.isMuxed||t.audio.hasAudio||n)&&(r.audio=s.audio||t.main.audioCodec||t.audio.audioCodec||b.Yg,t.audio.isFmp4=t.main.hasAudio&&!t.main.isMuxed?t.main.isFmp4:t.audio.isFmp4),!r.audio&&!r.video){this.excludePlaylist({playlistToExclude:i,error:{message:"Could not determine codecs for playlist."},playlistExclusionDuration:1/0});return}let a=(e,t)=>e?(0,b.TY)(t,this.usingManagedMediaSource_):(0,b.YZ)(t),o={};if(["video","audio"].forEach(function(i){if(r.hasOwnProperty(i)&&!a(t[i].isFmp4,r[i])){let s=t[i].isFmp4?"browser":"muxer";o[s]=o[s]||[],o[s].push(r[i]),"audio"===i&&(e=s)}}),n&&e&&i.attributes.AUDIO){let t=i.attributes.AUDIO;this.main().playlists.forEach(e=>{(e.attributes&&e.attributes.AUDIO)===t&&e!==i&&(e.excludeUntil=1/0)}),this.logger_(`excluding audio group ${t} as ${e} does not support codec(s): "${r.audio}"`)}if(Object.keys(o).length){let e=Object.keys(o).reduce((e,t)=>(e&&(e+=", "),e+=`${t} does not support codec(s): "${o[t].join(",")}"`),"")+".";this.excludePlaylist({playlistToExclude:i,error:{internal:!0,message:e},playlistExclusionDuration:1/0});return}if(this.sourceUpdater_.hasCreatedSourceBuffers()&&!this.sourceUpdater_.canChangeType()){let e=[];if(["video","audio"].forEach(t=>{let i=((0,b.tB)(this.sourceUpdater_.codecs[t]||"")[0]||{}).type,s=((0,b.tB)(r[t]||"")[0]||{}).type;i&&s&&i.toLowerCase()!==s.toLowerCase()&&e.push(`"${this.sourceUpdater_.codecs[t]}" -> "${r[t]}"`)}),e.length){this.excludePlaylist({playlistToExclude:i,error:{message:`Codec switching not supported: ${e.join(", ")}.`,internal:!0},playlistExclusionDuration:1/0});return}}return r}tryToCreateSourceBuffers_(){if("open"!==this.mediaSource.readyState||this.sourceUpdater_.hasCreatedSourceBuffers()||!this.areMediaTypesKnown_())return;let e=this.getCodecsOrExclude_();if(!e)return;this.sourceUpdater_.createSourceBuffers(e);let t=[e.video,e.audio].filter(Boolean).join(",");this.excludeIncompatibleVariants_(t)}excludeUnsupportedVariants_(){let e=this.main().playlists,t=[];Object.keys(e).forEach(i=>{let s=e[i];if(-1!==t.indexOf(s.id))return;t.push(s.id);let r=aN(this.main,s),n=[];!r.audio||(0,b.YZ)(r.audio)||(0,b.TY)(r.audio,this.usingManagedMediaSource_)||n.push(`audio codec ${r.audio}`),!r.video||(0,b.YZ)(r.video)||(0,b.TY)(r.video,this.usingManagedMediaSource_)||n.push(`video codec ${r.video}`),r.text&&"stpp.ttml.im1t"===r.text&&n.push(`text codec ${r.text}`),n.length&&(s.excludeUntil=1/0,this.logger_(`excluding ${s.id} for unsupported: ${n.join(", ")}`))})}excludeIncompatibleVariants_(e){let t=[],i=this.main().playlists,s=aR((0,b.tB)(e)),r=aB(s),n=s.video&&(0,b.tB)(s.video)[0]||null,a=s.audio&&(0,b.tB)(s.audio)[0]||null;Object.keys(i).forEach(e=>{let s=i[e];if(-1!==t.indexOf(s.id)||s.excludeUntil===1/0)return;t.push(s.id);let o=[],l=aN(this.mainPlaylistLoader_.main,s),h=aB(l);if(l.audio||l.video){if(h!==r&&o.push(`codec count "${h}" !== "${r}"`),!this.sourceUpdater_.canChangeType()){let e=l.video&&(0,b.tB)(l.video)[0]||null,t=l.audio&&(0,b.tB)(l.audio)[0]||null;e&&n&&e.type.toLowerCase()!==n.type.toLowerCase()&&o.push(`video codec "${e.type}" !== "${n.type}"`),t&&a&&t.type.toLowerCase()!==a.type.toLowerCase()&&o.push(`audio codec "${t.type}" !== "${a.type}"`)}o.length&&(s.excludeUntil=1/0,this.logger_(`excluding ${s.id}: ${o.join(" && ")}`))}})}updateAdCues_(e){let t=0,i=this.seekable();i.length&&(t=i.start(0)),oM(e,this.cueTagsTrack_,t)}goalBufferLength(){let e=this.tech_.currentTime(),t=n8.GOAL_BUFFER_LENGTH,i=n8.GOAL_BUFFER_LENGTH_RATE,s=Math.max(t,n8.MAX_GOAL_BUFFER_LENGTH);return Math.min(t+e*i,s)}bufferLowWaterLine(){let e=this.tech_.currentTime(),t=n8.BUFFER_LOW_WATER_LINE,i=n8.BUFFER_LOW_WATER_LINE_RATE,s=Math.max(t,n8.MAX_BUFFER_LOW_WATER_LINE),r=Math.max(t,n8.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);return Math.min(t+e*i,this.bufferBasedABR?r:s)}bufferHighWaterLine(){return n8.BUFFER_HIGH_WATER_LINE}addDateRangesToTextTrack_(e){a2(this.inbandTextTracks_,"com.apple.streaming",this.tech_),a1({inbandTextTracks:this.inbandTextTracks_,dateRanges:e})}addMetadataToTextTrack(e,t,i){let s=this.sourceUpdater_.videoBuffer?this.sourceUpdater_.videoTimestampOffset():this.sourceUpdater_.audioTimestampOffset();a2(this.inbandTextTracks_,e,this.tech_),aJ({inbandTextTracks:this.inbandTextTracks_,metadataArray:t,timestampOffset:s,videoDuration:i})}pathwayAttribute_(e){return e.attributes["PATHWAY-ID"]||e.attributes.serviceLocation}initContentSteeringController_(){let e=this.main();if(e.contentSteering){for(let t of e.playlists)this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(t));if(this.contentSteeringController_.assignTagProperties(e.uri,e.contentSteering),this.contentSteeringController_.queryBeforeStart){this.contentSteeringController_.requestSteeringManifest(!0);return}this.tech_.one("canplay",()=>{this.contentSteeringController_.requestSteeringManifest()})}}resetContentSteeringController_(){this.contentSteeringController_.clearAvailablePathways(),this.contentSteeringController_.dispose(),this.initContentSteeringController_()}attachContentSteeringListeners_(){this.contentSteeringController_.on("content-steering",this.excludeThenChangePathway_.bind(this)),["contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(e=>{this.contentSteeringController_.on(e,e=>{this.trigger((0,_.A)({},e))})}),"dash"===this.sourceType_&&this.mainPlaylistLoader_.on("loadedplaylist",()=>{let e=this.main();(this.contentSteeringController_.didDASHTagChange(e.uri,e.contentSteering)||(()=>{let t=this.contentSteeringController_.getAvailablePathways(),i=[];for(let s of e.playlists){let e=s.attributes.serviceLocation;if(e&&(i.push(e),!t.has(e)))return!0}return!i.length&&!!t.size})())&&this.resetContentSteeringController_()})}excludeThenChangePathway_(){let e=this.contentSteeringController_.getPathway();if(!e)return;this.handlePathwayClones_();let t=this.main().playlists,i=new Set,s=!1;Object.keys(t).forEach(r=>{let n=t[r],a=this.pathwayAttribute_(n),o=a&&e!==a;n.excludeUntil!==1/0||"content-steering"!==n.lastExcludeReason_||o||(delete n.excludeUntil,delete n.lastExcludeReason_,s=!0);let l=!n.excludeUntil&&n.excludeUntil!==1/0;!i.has(n.id)&&o&&l&&(i.add(n.id),n.excludeUntil=1/0,n.lastExcludeReason_="content-steering",this.logger_(`excluding ${n.id} for ${n.lastExcludeReason_}`))}),"DASH"===this.contentSteeringController_.manifestType_&&Object.keys(this.mediaTypes_).forEach(t=>{let i=this.mediaTypes_[t];if(i.activePlaylistLoader){let t=i.activePlaylistLoader.media_;t&&t.attributes.serviceLocation!==e&&(s=!0)}}),s&&this.changeSegmentPathway_()}handlePathwayClones_(){let e=this.main().playlists,t=this.contentSteeringController_.currentPathwayClones,i=this.contentSteeringController_.nextPathwayClones;if(t&&t.size||i&&i.size){for(let[e,s]of t.entries())i.get(e)||(this.mainPlaylistLoader_.updateOrDeleteClone(s),this.contentSteeringController_.excludePathway(e));for(let[s,r]of i.entries()){let i=t.get(s);if(!i){e.filter(e=>e.attributes["PATHWAY-ID"]===r["BASE-ID"]).forEach(e=>{this.mainPlaylistLoader_.addClonePathway(r,e)}),this.contentSteeringController_.addAvailablePathway(s);continue}!this.equalPathwayClones_(i,r)&&(this.mainPlaylistLoader_.updateOrDeleteClone(r,!0),this.contentSteeringController_.addAvailablePathway(s))}this.contentSteeringController_.currentPathwayClones=new Map(JSON.parse(JSON.stringify([...i])))}}equalPathwayClones_(e,t){if(e["BASE-ID"]!==t["BASE-ID"]||e.ID!==t.ID||e["URI-REPLACEMENT"].HOST!==t["URI-REPLACEMENT"].HOST)return!1;let i=e["URI-REPLACEMENT"].PARAMS,s=t["URI-REPLACEMENT"].PARAMS;for(let e in i)if(i[e]!==s[e])return!1;for(let e in s)if(i[e]!==s[e])return!1;return!0}changeSegmentPathway_(){let e=this.selectPlaylist();this.pauseLoading(),"DASH"===this.contentSteeringController_.manifestType_&&this.switchMediaForDASHContentSteering_(),this.switchMedia_(e,"content-steering")}excludeNonUsablePlaylistsByKeyId_(){if(!this.mainPlaylistLoader_||!this.mainPlaylistLoader_.main)return;let e=0,t="non-usable";this.mainPlaylistLoader_.main.playlists.forEach(i=>{let s=this.mainPlaylistLoader_.getKeyIdSet(i);s&&s.size&&s.forEach(s=>{let r="usable",n=this.keyStatusMap_.has(s)&&this.keyStatusMap_.get(s)===r,a=i.lastExcludeReason_===t&&i.excludeUntil===1/0;n?n&&a&&(delete i.excludeUntil,delete i.lastExcludeReason_,this.logger_(`enabling playlist ${i.id} because key ID ${s} is ${r}`)):(i.excludeUntil!==1/0&&i.lastExcludeReason_!==t&&(i.excludeUntil=1/0,i.lastExcludeReason_=t,this.logger_(`excluding playlist ${i.id} because the key ID ${s} doesn't exist in the keyStatusMap or is not ${r}`)),e++)})}),e>=this.mainPlaylistLoader_.main.playlists.length&&this.mainPlaylistLoader_.main.playlists.forEach(e=>{let i=e&&e.attributes&&e.attributes.RESOLUTION&&e.attributes.RESOLUTION.height<720,s=e.excludeUntil===1/0&&e.lastExcludeReason_===t;i&&s&&(delete e.excludeUntil,rk.log.warn(`enabling non-HD playlist ${e.id} because all playlists were excluded due to ${t} key IDs`))})}addKeyStatus_(e,t){let i=("string"==typeof e?e:oP(e)).slice(0,32).toLowerCase();this.logger_(`KeyStatus '${t}' with key ID ${i} added to the keyStatusMap`),this.keyStatusMap_.set(i,t)}updatePlaylistByKeyStatus(e,t){this.addKeyStatus_(e,t),this.waitingForFastQualityPlaylistReceived_||this.excludeNonUsableThenChangePlaylist_(),this.mainPlaylistLoader_.off("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this)),this.mainPlaylistLoader_.on("loadedplaylist",this.excludeNonUsableThenChangePlaylist_.bind(this))}excludeNonUsableThenChangePlaylist_(){this.excludeNonUsablePlaylistsByKeyId_(),this.fastQualityChange_()}}let lt=(e,t,i)=>s=>{let r=e.main.playlists[t],n=r8(r),a=r5(r);if(void 0===s)return a;s?delete r.disabled:r.disabled=!0;let o={renditionInfo:{id:t,bandwidth:r.attributes.BANDWIDTH,resolution:r.attributes.RESOLUTION,codecs:r.attributes.CODECS},cause:"fast-quality"};return s===a||n||(s?(i(r),e.trigger({type:"renditionenabled",metadata:o})):e.trigger({type:"renditiondisabled",metadata:o})),s};class li{constructor(e,t,i){let{playlistController_:s}=e,r=s.fastQualityChange_.bind(s);if(t.attributes){let e=t.attributes.RESOLUTION;this.width=e&&e.width,this.height=e&&e.height,this.bandwidth=t.attributes.BANDWIDTH,this.frameRate=t.attributes["FRAME-RATE"]}this.codecs=aN(s.main(),t),this.playlist=t,this.id=i,this.enabled=lt(e.playlists,t.id,r)}}let ls=function(e){e.representations=()=>{let t=e.playlistController_.main(),i=ne(t)?e.playlistController_.getAudioTrackPlaylists_():t.playlists;return i?i.filter(e=>!r8(e)).map((t,i)=>new li(e,t,t.id)):[]}},lr=["seeking","seeked","pause","playing","error"];class ln extends rk.EventTarget{constructor(e){super(),this.playlistController_=e.playlistController,this.tech_=e.tech,this.seekable=e.seekable,this.allowSeeksWithinUnsafeLiveWindow=e.allowSeeksWithinUnsafeLiveWindow,this.liveRangeSafeTimeDelta=e.liveRangeSafeTimeDelta,this.media=e.media,this.playedRanges_=[],this.consecutiveUpdates=0,this.lastRecordedTime=null,this.checkCurrentTimeTimeout_=null,this.logger_=rL("PlaybackWatcher"),this.logger_("initialize");let t=()=>this.monitorCurrentTime_(),i=()=>this.monitorCurrentTime_(),s=()=>this.techWaiting_(),r=()=>this.resetTimeUpdate_(),n=this.playlistController_,a=["main","subtitle","audio"],o={};a.forEach(e=>{o[e]={reset:()=>this.resetSegmentDownloads_(e),updateend:()=>this.checkSegmentDownloads_(e)},n[`${e}SegmentLoader_`].on("appendsdone",o[e].updateend),n[`${e}SegmentLoader_`].on("playlistupdate",o[e].reset),this.tech_.on(["seeked","seeking"],o[e].reset)});let l=e=>{["main","audio"].forEach(t=>{n[`${t}SegmentLoader_`][e]("appended",this.seekingAppendCheck_)})};this.seekingAppendCheck_=()=>{this.fixesBadSeeks_()&&(this.consecutiveUpdates=0,this.lastRecordedTime=this.tech_.currentTime(),l("off"))},this.clearSeekingAppendCheck_=()=>l("off"),this.watchForBadSeeking_=()=>{this.clearSeekingAppendCheck_(),l("on")},this.tech_.on("seeked",this.clearSeekingAppendCheck_),this.tech_.on("seeking",this.watchForBadSeeking_),this.tech_.on("waiting",s),this.tech_.on(lr,r),this.tech_.on("canplay",i),this.tech_.one("play",t),this.dispose=()=>{this.clearSeekingAppendCheck_(),this.logger_("dispose"),this.tech_.off("waiting",s),this.tech_.off(lr,r),this.tech_.off("canplay",i),this.tech_.off("play",t),this.tech_.off("seeking",this.watchForBadSeeking_),this.tech_.off("seeked",this.clearSeekingAppendCheck_),a.forEach(e=>{n[`${e}SegmentLoader_`].off("appendsdone",o[e].updateend),n[`${e}SegmentLoader_`].off("playlistupdate",o[e].reset),this.tech_.off(["seeked","seeking"],o[e].reset)}),this.checkCurrentTimeTimeout_&&d().clearTimeout(this.checkCurrentTimeTimeout_),this.resetTimeUpdate_()}}monitorCurrentTime_(){this.checkCurrentTime_(),this.checkCurrentTimeTimeout_&&d().clearTimeout(this.checkCurrentTimeTimeout_),this.checkCurrentTimeTimeout_=d().setTimeout(this.monitorCurrentTime_.bind(this),250)}resetSegmentDownloads_(e){let t=this.playlistController_[`${e}SegmentLoader_`];this[`${e}StalledDownloads_`]>0&&this.logger_(`resetting possible stalled download count for ${e} loader`),this[`${e}StalledDownloads_`]=0,this[`${e}Buffered_`]=t.buffered_()}checkSegmentDownloads_(e){let t=this.playlistController_,i=t[`${e}SegmentLoader_`],s=i.buffered_(),r=rH(this[`${e}Buffered_`],s);if(this[`${e}Buffered_`]=s,r){t.trigger({type:"bufferedrangeschanged",metadata:{bufferedRanges:s}}),this.resetSegmentDownloads_(e);return}if(this[`${e}StalledDownloads_`]++,this.logger_(`found #${this[`${e}StalledDownloads_`]} ${e} appends that did not increase buffer (possible stalled download)`,{playlistId:i.playlist_&&i.playlist_.id,buffered:rq(s)}),!(this[`${e}StalledDownloads_`]<10))this.logger_(`${e} loader stalled download exclusion`),this.resetSegmentDownloads_(e),this.tech_.trigger({type:"usage",name:`vhs-${e}-download-exclusion`}),"subtitle"!==e&&t.excludePlaylist({error:{message:`Excessive ${e} segment downloading detected.`},playlistExclusionDuration:1/0})}checkCurrentTime_(){if(this.tech_.paused()||this.tech_.seeking())return;let e=this.tech_.currentTime(),t=this.tech_.buffered();if(this.lastRecordedTime===e&&(!t.length||e+rU>=t.end(t.length-1)))return this.techWaiting_();if(this.consecutiveUpdates>=5&&e===this.lastRecordedTime)this.consecutiveUpdates++,this.waiting_();else if(e===this.lastRecordedTime)this.consecutiveUpdates++;else{this.playedRanges_.push(rO([this.lastRecordedTime,e]));let t={playedRanges:this.playedRanges_};this.playlistController_.trigger({type:"playedrangeschanged",metadata:t}),this.consecutiveUpdates=0,this.lastRecordedTime=e}}resetTimeUpdate_(){this.consecutiveUpdates=0}fixesBadSeeks_(){let e;if(!this.tech_.seeking())return!1;let t=this.seekable(),i=this.tech_.currentTime();if(this.afterSeekableWindow_(t,i,this.media(),this.allowSeeksWithinUnsafeLiveWindow)&&(e=t.end(t.length-1)),this.beforeSeekableWindow_(t,i)){let i=t.start(0);e=i+(i===t.end(0)?0:rU)}if(void 0!==e)return this.logger_(`Trying to seek outside of seekable at time ${i} with seekable range ${r$(t)}. Seeking to ${e}.`),this.tech_.setCurrentTime(e),!0;let s=this.playlistController_.sourceUpdater_,r=this.tech_.buffered(),n=s.audioBuffer?s.audioBuffered():null,a=s.videoBuffer?s.videoBuffered():null,o=this.media(),l=o.partTargetDuration?o.partTargetDuration:(o.targetDuration-rM)*2,h=[n,a];for(let e=0;e ${t.end(0)}]. Attempting to resume playback by seeking to the current time.`),this.tech_.trigger({type:"usage",name:"vhs-unknown-waiting"});return}}techWaiting_(){let e=this.seekable(),t=this.tech_.currentTime();if(this.tech_.seeking())return!0;if(this.beforeSeekableWindow_(e,t)){let i=e.end(e.length-1);return this.logger_(`Fell out of live window at time ${t}. Seeking to live point (seekable end) ${i}`),this.resetTimeUpdate_(),this.tech_.setCurrentTime(i),this.tech_.trigger({type:"usage",name:"vhs-live-resync"}),!0}let i=this.tech_.vhs.playlistController_.sourceUpdater_,s=this.tech_.buffered();if(this.videoUnderflow_({audioBuffered:i.audioBuffered(),videoBuffered:i.videoBuffered(),currentTime:t}))return this.resetTimeUpdate_(),this.tech_.setCurrentTime(t),this.tech_.trigger({type:"usage",name:"vhs-video-underflow"}),!0;let r=rN(s,t);return r.length>0&&(this.logger_(`Stopped at ${t} and seeking to ${r.start(0)}`),this.resetTimeUpdate_(),this.skipTheGap_(t),!0)}afterSeekableWindow_(e,t,i,s=!1){if(!e.length)return!1;let r=e.end(e.length-1)+rU,n=!i.endList,a="number"==typeof i.partTargetDuration;return n&&(a||s)&&(r=e.end(e.length-1)+3*i.targetDuration),t>r}beforeSeekableWindow_(e,t){return!!(e.length&&e.start(0)>0&&t2)return{start:s,end:r}}return null}}let la={errorInterval:30,getSource(e){return e(this.tech({IWillNotUseThisInPlugins:!0}).currentSource_||this.currentSource())}},lo=function(e,t){let i=0,s=0,r=rD(la,t);e.ready(()=>{e.trigger({type:"usage",name:"vhs-error-reload-initialized"})});let n=function(){s&&e.currentTime(s)},a=function(t){null!=t&&(s=e.duration()!==1/0&&e.currentTime()||0,e.one("loadedmetadata",n),e.src(t),e.trigger({type:"usage",name:"vhs-error-reload"}),e.play())},o=function(){if(Date.now()-i<1e3*r.errorInterval){e.trigger({type:"usage",name:"vhs-error-reload-canceled"});return}if(!r.getSource||"function"!=typeof r.getSource){rk.log.error("ERROR: reloadSourceOnError - The option getSource must be a function!");return}return i=Date.now(),r.getSource.call(e,a)},l=function(){e.off("loadedmetadata",n),e.off("error",o),e.off("dispose",l)};e.on("error",o),e.on("dispose",l),e.reloadSourceOnError=function(t){l(),lo(e,t)}};var ll="3.16.2";let lh={PlaylistLoader:nC,Playlist:nt,utils:nB,STANDARD_PLAYLIST_SELECTOR:az,INITIAL_PLAYLIST_SELECTOR:function(){let e=this.playlists.main.playlists.filter(nt.isEnabled);return aq(e,(e,t)=>aH(e,t)),e.filter(e=>!!aN(this.playlists.main,e).video)[0]||null},lastBandwidthSelector:az,movingAverageBandwidthSelector:function(e){let t=-1,i=-1;if(e<0||e>1)throw Error("Moving average bandwidth decay must be between 0 and 1.");return function(){let s=this.useDevicePixelRatio&&d().devicePixelRatio||1;return isNaN(this.customPixelRatio)||(s=this.customPixelRatio),t<0&&(t=this.systemBandwidth,i=this.systemBandwidth),this.systemBandwidth>0&&this.systemBandwidth!==i&&(t=e*this.systemBandwidth+(1-e)*t,i=this.systemBandwidth),aV(this.playlists.main,t,parseInt(a$(this.tech_.el(),"width"),10)*s,parseInt(a$(this.tech_.el(),"height"),10)*s,this.limitRenditionByPlayerDimensions,this.playlistController_)}},comparePlaylistBandwidth:aH,comparePlaylistResolution:function(e,t){let i,s;return(e.attributes.RESOLUTION&&e.attributes.RESOLUTION.width&&(i=e.attributes.RESOLUTION.width),i=i||d().Number.MAX_VALUE,t.attributes.RESOLUTION&&t.attributes.RESOLUTION.width&&(s=t.attributes.RESOLUTION.width),i===(s=s||d().Number.MAX_VALUE)&&e.attributes.BANDWIDTH&&t.attributes.BANDWIDTH)?e.attributes.BANDWIDTH-t.attributes.BANDWIDTH:i-s},xhr:nI()};Object.keys(n8).forEach(e=>{Object.defineProperty(lh,e,{get:()=>(rk.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),n8[e]),set(t){if(rk.log.warn(`using Vhs.${e} is UNSAFE be sure you know what you are doing`),"number"!=typeof t||t<0){rk.log.warn(`value of Vhs.${e} must be greater than or equal to 0`);return}n8[e]=t}})});let ld="videojs-vhs",lu=function(e,t){let i=t.media(),s=-1;for(let t=0;t{e.addQualityLevel(t)}),lu(e,t.playlists)};lh.canPlaySource=function(){return rk.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")};let lp=(e,t,i)=>{if(!e)return e;let s={};t&&t.attributes&&t.attributes.CODECS&&(s=aR((0,b.tB)(t.attributes.CODECS))),i&&i.attributes&&i.attributes.CODECS&&(s.audio=i.attributes.CODECS);let r=(0,b.UD)(s.video),n=(0,b.UD)(s.audio),a={};for(let i in e)a[i]={},n&&(a[i].audioContentType=n),r&&(a[i].videoContentType=r),t.contentProtection&&t.contentProtection[i]&&t.contentProtection[i].pssh&&(a[i].pssh=t.contentProtection[i].pssh),"string"==typeof e[i]&&(a[i].url=e[i]);return rD(e,a)},lm=(e,t)=>e.reduce((e,i)=>{if(!i.contentProtection)return e;let s=t.reduce((e,t)=>{let s=i.contentProtection[t];return s&&s.pssh&&(e[t]={pssh:s.pssh}),e},{});return Object.keys(s).length&&e.push(s),e},[]),lg=({player:e,sourceKeySystems:t,audioMedia:i,mainPlaylists:s})=>{if(!e.eme.initializeMediaKeys)return Promise.resolve();let r=lm(i?s.concat([i]):s,Object.keys(t)),n=[],a=[];return r.forEach(t=>{a.push(new Promise((t,i)=>{e.tech_.one("keysessioncreated",t)})),n.push(new Promise((i,s)=>{e.eme.initializeMediaKeys({keySystems:t},e=>{if(e){s(e);return}i()})}))}),Promise.race([Promise.all(n),Promise.race(a)])},lf=({player:e,sourceKeySystems:t,media:i,audioMedia:s})=>{let r=lp(t,i,s);return!!r&&(e.currentSource().keySystems=r,!r||!!e.eme||(rk.log.warn("DRM encrypted source cannot be decrypted without a DRM plugin"),!1))},l_=()=>{if(!d().localStorage)return null;let e=d().localStorage.getItem(ld);if(!e)return null;try{return JSON.parse(e)}catch(e){return null}},ly=e=>{if(!d().localStorage)return!1;let t=l_();t=t?rD(t,e):e;try{d().localStorage.setItem(ld,JSON.stringify(t))}catch(e){return!1}return t},lv=e=>0===e.toLowerCase().indexOf("data:application/vnd.videojs.vhs+json,")?JSON.parse(e.substring(e.indexOf(",")+1)):e,lb=(e,t)=>{e._requestCallbackSet||(e._requestCallbackSet=new Set),e._requestCallbackSet.add(t)},lT=(e,t)=>{e._responseCallbackSet||(e._responseCallbackSet=new Set),e._responseCallbackSet.add(t)},lS=(e,t)=>{e._requestCallbackSet&&(e._requestCallbackSet.delete(t),e._requestCallbackSet.size||delete e._requestCallbackSet)},lk=(e,t)=>{e._responseCallbackSet&&(e._responseCallbackSet.delete(t),e._responseCallbackSet.size||delete e._responseCallbackSet)};lh.supportsNativeHls=function(){if(!c()||!c().createElement)return!1;let e=c().createElement("video");return!!rk.getTech("Html5").isSupported()&&["application/vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"].some(function(t){return/maybe|probably/i.test(e.canPlayType(t))})}(),lh.supportsNativeDash=!!(c()&&c().createElement&&rk.getTech("Html5").isSupported())&&/maybe|probably/i.test(c().createElement("video").canPlayType("application/dash+xml")),lh.supportsTypeNatively=e=>"hls"===e?lh.supportsNativeHls:"dash"===e&&lh.supportsNativeDash,lh.isSupported=function(){return rk.log.warn("VHS is no longer a tech. Please remove it from your player's techOrder.")},lh.xhr.onRequest=function(e){lb(lh.xhr,e)},lh.xhr.onResponse=function(e){lT(lh.xhr,e)},lh.xhr.offRequest=function(e){lS(lh.xhr,e)},lh.xhr.offResponse=function(e){lk(lh.xhr,e)};let lC=rk.getComponent("Component");class lw extends lC{constructor(e,t,i){if(super(t,i.vhs),"number"==typeof i.initialBandwidth&&(this.options_.bandwidth=i.initialBandwidth),this.logger_=rL("VhsHandler"),t.options_&&t.options_.playerId){let e=rk.getPlayer(t.options_.playerId);this.player_=e}if(this.tech_=t,this.source_=e,this.stats={},this.ignoreNextSeekingEvent_=!1,this.setOptions_(),this.options_.overrideNative&&t.overrideNativeAudioTracks&&t.overrideNativeVideoTracks)t.overrideNativeAudioTracks(!0),t.overrideNativeVideoTracks(!0);else if(this.options_.overrideNative&&(t.featuresNativeVideoTracks||t.featuresNativeAudioTracks))throw Error("Overriding native VHS requires emulated tracks. See https://git.io/vMpjB");this.on(c(),["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],e=>{let t=c().fullscreenElement||c().webkitFullscreenElement||c().mozFullScreenElement||c().msFullscreenElement;t&&t.contains(this.tech_.el())?this.playlistController_.fastQualityChange_():this.playlistController_.checkABR_()}),this.on(this.tech_,"seeking",function(){if(this.ignoreNextSeekingEvent_){this.ignoreNextSeekingEvent_=!1;return}this.setCurrentTime(this.tech_.currentTime())}),this.on(this.tech_,"error",function(){this.tech_.error()&&this.playlistController_&&this.playlistController_.pauseLoading()}),this.on(this.tech_,"play",this.play)}setOptions_(e={}){if(this.options_=rD(this.options_,e),this.options_.withCredentials=this.options_.withCredentials||!1,this.options_.limitRenditionByPlayerDimensions=!1!==this.options_.limitRenditionByPlayerDimensions,this.options_.useDevicePixelRatio=this.options_.useDevicePixelRatio||!1,this.options_.useBandwidthFromLocalStorage=void 0!==this.source_.useBandwidthFromLocalStorage?this.source_.useBandwidthFromLocalStorage:this.options_.useBandwidthFromLocalStorage||!1,this.options_.useForcedSubtitles=this.options_.useForcedSubtitles||!1,this.options_.useNetworkInformationApi=this.options_.useNetworkInformationApi||!1,this.options_.useDtsForTimestampOffset=this.options_.useDtsForTimestampOffset||!1,this.options_.customTagParsers=this.options_.customTagParsers||[],this.options_.customTagMappers=this.options_.customTagMappers||[],this.options_.cacheEncryptionKeys=this.options_.cacheEncryptionKeys||!1,this.options_.llhls=!1!==this.options_.llhls,this.options_.bufferBasedABR=this.options_.bufferBasedABR||!1,"number"!=typeof this.options_.playlistExclusionDuration&&(this.options_.playlistExclusionDuration=60),"number"!=typeof this.options_.bandwidth&&this.options_.useBandwidthFromLocalStorage){let e=l_();e&&e.bandwidth&&(this.options_.bandwidth=e.bandwidth,this.tech_.trigger({type:"usage",name:"vhs-bandwidth-from-local-storage"})),e&&e.throughput&&(this.options_.throughput=e.throughput,this.tech_.trigger({type:"usage",name:"vhs-throughput-from-local-storage"}))}"number"!=typeof this.options_.bandwidth&&(this.options_.bandwidth=n8.INITIAL_BANDWIDTH),this.options_.enableLowInitialPlaylist=this.options_.enableLowInitialPlaylist&&this.options_.bandwidth===n8.INITIAL_BANDWIDTH,["withCredentials","useDevicePixelRatio","customPixelRatio","limitRenditionByPlayerDimensions","bandwidth","customTagParsers","customTagMappers","cacheEncryptionKeys","playlistSelector","initialPlaylistSelector","bufferBasedABR","liveRangeSafeTimeDelta","llhls","useForcedSubtitles","useNetworkInformationApi","useDtsForTimestampOffset","exactManifestTimings","leastPixelDiffSelector"].forEach(e=>{void 0!==this.source_[e]&&(this.options_[e]=this.source_[e])}),this.limitRenditionByPlayerDimensions=this.options_.limitRenditionByPlayerDimensions,this.useDevicePixelRatio=this.options_.useDevicePixelRatio;let t=this.options_.customPixelRatio;"number"==typeof t&&t>=0&&(this.customPixelRatio=t)}setOptions(e={}){this.setOptions_(e)}src(e,t){if(!e)return;this.setOptions_(),this.options_.src=lv(this.source_.src),this.options_.tech=this.tech_,this.options_.externVhs=lh,this.options_.sourceType=(0,T.I)(t),this.options_.seekTo=e=>{this.tech_.setCurrentTime(e)},this.options_.player_=this.player_,this.playlistController_=new le(this.options_);let i=rD({liveRangeSafeTimeDelta:rU},this.options_,{seekable:()=>this.seekable(),media:()=>this.playlistController_.media(),playlistController:this.playlistController_});this.playbackWatcher_=new ln(i),this.attachStreamingEventListeners_(),this.playlistController_.on("error",()=>{let e=rk.players[this.tech_.options_.playerId],t=this.playlistController_.error;"object"!=typeof t||t.code?"string"==typeof t&&(t={message:t,code:3}):t.code=3,e.error(t)});let s=this.options_.bufferBasedABR?lh.movingAverageBandwidthSelector(.55):lh.STANDARD_PLAYLIST_SELECTOR;this.playlistController_.selectPlaylist=this.selectPlaylist?this.selectPlaylist.bind(this):s.bind(this),this.playlistController_.selectInitialPlaylist=lh.INITIAL_PLAYLIST_SELECTOR.bind(this),this.playlists=this.playlistController_.mainPlaylistLoader_,this.mediaSource=this.playlistController_.mediaSource,Object.defineProperties(this,{selectPlaylist:{get(){return this.playlistController_.selectPlaylist},set(e){this.playlistController_.selectPlaylist=e.bind(this)}},throughput:{get(){return this.playlistController_.mainSegmentLoader_.throughput.rate},set(e){this.playlistController_.mainSegmentLoader_.throughput.rate=e,this.playlistController_.mainSegmentLoader_.throughput.count=1}},bandwidth:{get(){let e=this.playlistController_.mainSegmentLoader_.bandwidth,t=d().navigator.connection||d().navigator.mozConnection||d().navigator.webkitConnection;if(this.options_.useNetworkInformationApi&&t){let i=1e6*t.downlink;e=i>=1e7&&e>=1e7?Math.max(e,i):i}return e},set(e){this.playlistController_.mainSegmentLoader_.bandwidth=e,this.playlistController_.mainSegmentLoader_.throughput={rate:0,count:0}}},systemBandwidth:{get(){let e;return Math.floor(1/(1/(this.bandwidth||1)+(this.throughput>0?1/this.throughput:0)))},set(){rk.log.error('The "systemBandwidth" property is read-only')}}}),this.options_.bandwidth&&(this.bandwidth=this.options_.bandwidth),this.options_.throughput&&(this.throughput=this.options_.throughput),Object.defineProperties(this.stats,{bandwidth:{get:()=>this.bandwidth||0,enumerable:!0},mediaRequests:{get:()=>this.playlistController_.mediaRequests_()||0,enumerable:!0},mediaRequestsAborted:{get:()=>this.playlistController_.mediaRequestsAborted_()||0,enumerable:!0},mediaRequestsTimedout:{get:()=>this.playlistController_.mediaRequestsTimedout_()||0,enumerable:!0},mediaRequestsErrored:{get:()=>this.playlistController_.mediaRequestsErrored_()||0,enumerable:!0},mediaTransferDuration:{get:()=>this.playlistController_.mediaTransferDuration_()||0,enumerable:!0},mediaBytesTransferred:{get:()=>this.playlistController_.mediaBytesTransferred_()||0,enumerable:!0},mediaSecondsLoaded:{get:()=>this.playlistController_.mediaSecondsLoaded_()||0,enumerable:!0},mediaAppends:{get:()=>this.playlistController_.mediaAppends_()||0,enumerable:!0},mainAppendsToLoadedData:{get:()=>this.playlistController_.mainAppendsToLoadedData_()||0,enumerable:!0},audioAppendsToLoadedData:{get:()=>this.playlistController_.audioAppendsToLoadedData_()||0,enumerable:!0},appendsToLoadedData:{get:()=>this.playlistController_.appendsToLoadedData_()||0,enumerable:!0},timeToLoadedData:{get:()=>this.playlistController_.timeToLoadedData_()||0,enumerable:!0},buffered:{get:()=>rq(this.tech_.buffered()),enumerable:!0},currentTime:{get:()=>this.tech_.currentTime(),enumerable:!0},currentSource:{get:()=>this.tech_.currentSource_,enumerable:!0},currentTech:{get:()=>this.tech_.name_,enumerable:!0},duration:{get:()=>this.tech_.duration(),enumerable:!0},main:{get:()=>this.playlists.main,enumerable:!0},playerDimensions:{get:()=>this.tech_.currentDimensions(),enumerable:!0},seekable:{get:()=>rq(this.tech_.seekable()),enumerable:!0},timestamp:{get:()=>Date.now(),enumerable:!0},videoPlaybackQuality:{get:()=>this.tech_.getVideoPlaybackQuality(),enumerable:!0}}),this.tech_.one("canplay",this.playlistController_.setupFirstPlay.bind(this.playlistController_)),this.tech_.on("bandwidthupdate",()=>{this.options_.useBandwidthFromLocalStorage&&ly({bandwidth:this.bandwidth,throughput:Math.round(this.throughput)})}),this.playlistController_.on("selectedinitialmedia",()=>{ls(this)}),this.playlistController_.sourceUpdater_.on("createdsourcebuffers",()=>{this.setupEme_()}),this.on(this.playlistController_,"progress",function(){this.tech_.trigger("progress")}),this.on(this.playlistController_,"firstplay",function(){this.ignoreNextSeekingEvent_=!0}),this.setupQualityLevels_(),this.tech_.el()&&(this.mediaSourceUrl_=d().URL.createObjectURL(this.playlistController_.mediaSource),(rk.browser.IS_ANY_SAFARI||rk.browser.IS_IOS)&&this.options_.overrideNative&&"hls"===this.options_.sourceType&&"function"==typeof this.tech_.addSourceElement?(this.tech_.addSourceElement(this.mediaSourceUrl_),this.tech_.addSourceElement(this.source_.src)):this.tech_.src(this.mediaSourceUrl_))}createKeySessions_(){let e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;this.logger_("waiting for EME key session creation"),lg({player:this.player_,sourceKeySystems:this.source_.keySystems,audioMedia:e&&e.media(),mainPlaylists:this.playlists.main.playlists}).then(()=>{this.logger_("created EME key session"),this.playlistController_.sourceUpdater_.initializedEme()}).catch(e=>{this.logger_("error while creating EME key session",e),this.player_.error({message:"Failed to initialize media keys for EME",code:3})})}handleWaitingForKey_(){this.logger_("waitingforkey fired, attempting to create any new key sessions"),this.createKeySessions_()}setupEme_(){let e=this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader,t=lf({player:this.player_,sourceKeySystems:this.source_.keySystems,media:this.playlists.media(),audioMedia:e&&e.media()});if(this.player_.tech_.on("keystatuschange",e=>{this.playlistController_.updatePlaylistByKeyStatus(e.keyId,e.status)}),this.handleWaitingForKey_=this.handleWaitingForKey_.bind(this),this.player_.tech_.on("waitingforkey",this.handleWaitingForKey_),!t){this.playlistController_.sourceUpdater_.initializedEme();return}this.createKeySessions_()}setupQualityLevels_(){let e=rk.players[this.tech_.options_.playerId];e&&e.qualityLevels&&!this.qualityLevels_&&(this.qualityLevels_=e.qualityLevels(),this.playlistController_.on("selectedinitialmedia",()=>{lc(this.qualityLevels_,this)}),this.playlists.on("mediachange",()=>{lu(this.qualityLevels_,this.playlists)}))}static version(){return{"@videojs/http-streaming":ll,"mux.js":"7.1.0","mpd-parser":"1.3.1","m3u8-parser":"7.2.0","aes-decrypter":"4.0.2"}}version(){return this.constructor.version()}canChangeType(){return ox.canChangeType()}play(){this.playlistController_.play()}setCurrentTime(e){this.playlistController_.setCurrentTime(e)}duration(){return this.playlistController_.duration()}seekable(){return this.playlistController_.seekable()}dispose(){this.playbackWatcher_&&this.playbackWatcher_.dispose(),this.playlistController_&&this.playlistController_.dispose(),this.qualityLevels_&&this.qualityLevels_.dispose(),this.tech_&&this.tech_.vhs&&delete this.tech_.vhs,this.mediaSourceUrl_&&d().URL.revokeObjectURL&&(d().URL.revokeObjectURL(this.mediaSourceUrl_),this.mediaSourceUrl_=null),this.tech_&&this.tech_.off("waitingforkey",this.handleWaitingForKey_),super.dispose()}convertToProgramTime(e,t){return nV({playlist:this.playlistController_.media(),time:e,callback:t})}seekToProgramTime(e,t,i=!0,s=2){return nz({programTime:e,playlist:this.playlistController_.media(),retryCount:s,pauseAfterSeek:i,seekTo:this.options_.seekTo,tech:this.options_.tech,callback:t})}setupXhrHooks_(){this.xhr.onRequest=e=>{lb(this.xhr,e)},this.xhr.onResponse=e=>{lT(this.xhr,e)},this.xhr.offRequest=e=>{lS(this.xhr,e)},this.xhr.offResponse=e=>{lk(this.xhr,e)},this.player_.trigger("xhr-hooks-ready")}attachStreamingEventListeners_(){["seekablerangeschanged","bufferedrangeschanged","contentsteeringloadstart","contentsteeringloadcomplete","contentsteeringparsed"].forEach(e=>{this.playlistController_.on(e,e=>{this.player_.trigger((0,_.A)({},e))})}),["gapjumped","playedrangeschanged"].forEach(e=>{this.playbackWatcher_.on(e,e=>{this.player_.trigger((0,_.A)({},e))})})}}let lE={name:"videojs-http-streaming",VERSION:ll,canHandleSource(e,t={}){let i=rD(rk.options,t);return!!(i.vhs.experimentalUseMMS||(0,b.TY)("avc1.4d400d,mp4a.40.2",!1))&&lE.canPlayType(e.type,i)},handleSource(e,t,i={}){let s=rD(rk.options,i);return t.vhs=new lw(e,t,s),t.vhs.xhr=nI(),t.vhs.setupXhrHooks_(),t.vhs.src(e.src,e.type),t.vhs},canPlayType(e,t){let i=(0,T.I)(e);if(!i)return"";let s=lE.getOverrideNative(t);return!lh.supportsTypeNatively(i)||s?"maybe":""},getOverrideNative(e={}){let{vhs:t={}}=e,i=!(rk.browser.IS_ANY_SAFARI||rk.browser.IS_IOS),{overrideNative:s=i}=t;return s}};(0,b.TY)("avc1.4d400d,mp4a.40.2",!0)&&rk.getTech("Html5").registerSourceHandler(lE,0),rk.VhsHandler=lw,rk.VhsSourceHandler=lE,rk.Vhs=lh,rk.use||rk.registerComponent("Vhs",lh),rk.options.vhs=rk.options.vhs||{},rk.getPlugin&&rk.getPlugin("reloadSourceOnError")||rk.registerPlugin("reloadSourceOnError",function(e){lo(this,e)})}}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/app/_not-found/page-7afcdaac0636e021.js b/services/v1/media/feedback/static/_next/static/chunks/app/_not-found/page-7afcdaac0636e021.js new file mode 100644 index 0000000000000000000000000000000000000000..2ef29e44eced249c182578da3afa4bb6217413da --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/app/_not-found/page-7afcdaac0636e021.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[492],{3384:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HTTPAccessErrorFallback",{enumerable:!0,get:function(){return o}}),r(306);let l=r(5155);r(2115);let n={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{display:"inline-block"},h1:{display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},h2:{fontSize:14,fontWeight:400,lineHeight:"49px",margin:0}};function o(e){let{status:t,message:r}=e;return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("title",{children:t+": "+r}),(0,l.jsx)("div",{style:n.error,children:(0,l.jsxs)("div",{children:[(0,l.jsx)("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}),(0,l.jsx)("h1",{className:"next-error-h1",style:n.h1,children:t}),(0,l.jsx)("div",{style:n.desc,children:(0,l.jsx)("h2",{style:n.h2,children:r})})]})})]})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3868:(e,t,r)=>{(window.__NEXT_P=window.__NEXT_P||[]).push(["/_not-found/page",function(){return r(5623)}])},5623:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return o}});let l=r(5155),n=r(3384);function o(){return(0,l.jsx)(n.HTTPAccessErrorFallback,{status:404,message:"This page could not be found."})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}},e=>{var t=t=>e(e.s=t);e.O(0,[441,587,358],()=>t(3868)),_N_E=e.O()}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/app/layout-ada07d2d40a2b79a.js b/services/v1/media/feedback/static/_next/static/chunks/app/layout-ada07d2d40a2b79a.js new file mode 100644 index 0000000000000000000000000000000000000000..91c9e242636591a400e931d03160d9828475e0ec --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/app/layout-ada07d2d40a2b79a.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[177],{341:(e,a,s)=>{Promise.resolve().then(s.t.bind(s,5795,23)),Promise.resolve().then(s.t.bind(s,9497,23)),Promise.resolve().then(s.t.bind(s,347,23))},347:()=>{},5795:e=>{e.exports={style:{fontFamily:"'Geist', 'Geist Fallback'",fontStyle:"normal"},className:"__className_4d318d",variable:"__variable_4d318d"}},9497:e=>{e.exports={style:{fontFamily:"'Geist Mono', 'Geist Mono Fallback'",fontStyle:"normal"},className:"__className_ea5f4b",variable:"__variable_ea5f4b"}}},e=>{var a=a=>e(e.s=a);e.O(0,[830,441,587,358],()=>a(341)),_N_E=e.O()}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/app/page-f3889bc9ae1bdb7d.js b/services/v1/media/feedback/static/_next/static/chunks/app/page-f3889bc9ae1bdb7d.js new file mode 100644 index 0000000000000000000000000000000000000000..f266618f4dc50be260fc054f20a8eb4b1aa8d2cf --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/app/page-f3889bc9ae1bdb7d.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[974],{542:()=>{},2088:(e,t,r)=>{Promise.resolve().then(r.bind(r,7684))},7684:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>x});var n=r(5155),s=r(2115),a=r(1935);r(6368);var l=r(4787);let o=()=>{let[e,t]=(0,s.useState)({width:0,height:0}),[r,n]=(0,s.useState)(null),a=(0,s.useCallback)(e=>{null!==e&&n(e)},[]);return(0,s.useEffect)(()=>{if(!r)return;(()=>{let{width:e,height:n}=r.getBoundingClientRect();t({width:e,height:n})})();let e=new ResizeObserver(e=>{for(let r of e){let{width:e,height:n}=r.contentRect;t({width:e,height:n})}});return e.observe(r),()=>{e.disconnect()}},[r]),[a,e]},i=()=>{let[e,t]=(0,s.useState)({width:0,height:0}),[r,n]=(0,s.useState)(null),[a,l]=(0,s.useState)({width:0,height:0}),o=(0,s.useCallback)(e=>{null!==e&&n(e)},[]);return(0,s.useEffect)(()=>{let e=()=>{l({width:window.innerWidth,height:window.innerHeight})};return e(),window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}},[]),(0,s.useEffect)(()=>{if(!r)return;(()=>{let{width:e,height:n}=r.getBoundingClientRect();t({width:e,height:n})})();let e=new ResizeObserver(e=>{for(let r of e){let{width:e,height:n}=r.contentRect;t({width:e,height:n})}});return e.observe(r),()=>{e.disconnect()}},[r]),(0,s.useEffect)(()=>{if(!r||0===e.width||0===e.height)return;let t=a.width-320,n=a.height/e.height,s=e.width*n;s>t?(r.style.width="100%",r.style.marginLeft="auto",r.style.marginRight="auto"):r.style.width="".concat(s,"px")},[a,e]),[o,e]};var c=r(2651);let d=(e,t,r)=>{let[n,a]=(0,s.useState)({data:null,loading:!0,error:null}),l=async()=>{if(e)try{a(e=>({...e,loading:!0}));let{data:n}=await (0,c.A)({method:"post",url:e,data:{action:"load",id:t,type:r},headers:{"Content-Type":"application/json"}});a({data:n,loading:!1,error:null})}catch(e){a({data:null,loading:!1,error:e})}finally{a(e=>({...e,loading:!1}))}};return(0,s.useEffect)(()=>{l()},[e]),{...n,handleFetch:l}},u=(e,t,r)=>{let[n,a]=(0,s.useState)({data:null,loading:!0,error:null,success:!1});return[async n=>{if(e)try{a(e=>({...e,loading:!0,success:!1})),n.id=t,r?n.type=r:n.type="";let{data:s}=await (0,c.A)({method:"post",url:e,data:n,headers:{"Content-Type":"application/json"}});a({data:s,loading:!1,error:null,success:!0})}catch(e){throw Error("Error en post")}finally{a(e=>({...e,loading:!1}))}},{...n}]},m={no_status:{label:"No Status",color:"gray",bgColor:"bg-gray-500/50",textColor:"text-gray-200"},in_progress:{label:"In Progress",color:"blue",bgColor:"bg-blue-500/50",textColor:"text-blue-200"},needs_review:{label:"Needs Review",color:"orange",bgColor:"bg-orange-500/50",textColor:"text-orange-200"},approved:{label:"Approved",color:"green",bgColor:"bg-green-500/50",textColor:"text-green-200"}},h=e=>{let{active:t,message:r,setStateMessage:a}=e;return(0,s.useEffect)(()=>{let e;return t&&(e=setTimeout(()=>{a({show:!1,message:""})},5e3)),()=>{e&&clearTimeout(e)}},[t,a]),(0,n.jsxs)("div",{className:"\n fixed bottom-4 left-1/2 -translate-x-1/2 \n transform transition-all duration-300 ease-in-out\n ".concat(t?"translate-y-0 opacity-100":"translate-y-20 opacity-0 pointer-events-none","\n z-50 min-w-[300px] max-w-md\n "),children:[(0,n.jsxs)("div",{className:"bg-red-500/90 backdrop-blur-sm text-white px-6 py-4 rounded-lg shadow-lg flex items-center justify-between gap-4",children:[(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("div",{className:"flex-shrink-0",children:(0,n.jsxs)("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,n.jsx)("path",{d:"M12 4.5C7.85786 4.5 4.5 7.85786 4.5 12C4.5 16.1421 7.85786 19.5 12 19.5C16.1421 19.5 19.5 16.1421 19.5 12C19.5 7.85786 16.1421 4.5 12 4.5ZM3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12Z",fill:"currentColor"}),(0,n.jsx)("path",{d:"M12 7.5C12.4142 7.5 12.75 7.83579 12.75 8.25V12.75C12.75 13.1642 12.4142 13.5 12 13.5C11.5858 13.5 11.25 13.1642 11.25 12.75V8.25C11.25 7.83579 11.5858 7.5 12 7.5Z",fill:"currentColor"}),(0,n.jsx)("path",{d:"M12 16.5C12.4142 16.5 12.75 16.1642 12.75 15.75C12.75 15.3358 12.4142 15 12 15C11.5858 15 11.25 15.3358 11.25 15.75C11.25 16.1642 11.5858 16.5 12 16.5Z",fill:"currentColor"})]})}),(0,n.jsx)("p",{className:"text-sm font-medium",children:r})]}),(0,n.jsx)("button",{onClick:()=>a({show:!1,message:""}),className:"flex-shrink-0 hover:bg-white/20 rounded-lg p-1.5 transition-colors duration-200",children:(0,n.jsxs)("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,n.jsx)("path",{d:"M6.75 6.75L17.25 17.25",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M17.25 6.75L6.75 17.25",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})})]}),(0,n.jsx)("div",{className:"absolute bottom-0 left-0 w-full h-1 bg-white/20 rounded-b-lg overflow-hidden",children:(0,n.jsx)("div",{className:"h-full bg-white/40 transition-all duration-[5000ms] ease-linear",style:{width:t?"0%":"100%",transitionProperty:"width"}})})]})},g=e=>{let{isVideoLoaded:t,isImage:r,imageRef:a,comments:l,playerRef:o,fabricCanvasRef:i,canva:c,dimensions:d,setIsDrawingMode:m,updateHandlerRef:h,queryParams:g,toggleDrawingMode:p,setComments:x,isDrawingMode:v,data:w,clearCanvas:f,handleFetch:y,setVideoStatus:b,successPostVideoStatus:j,setStateMessage:C,dataComments:k,setDataComments:N,optimisticComments:S,setOptimisticComments:E,lastUpdatedComments:D,setLastUpdatedComments:M}=e,[R,q]=(0,s.useState)(null),[L,O]=(0,s.useState)(!1);(0,s.useEffect)(()=>{N(l)},[l]);let _=(0,s.useRef)(k);(0,s.useEffect)(()=>{M(l)},[]);let[W,T]=(0,s.useTransition)(),z=()=>{if(!o.current||!l.length||r)return;o.current.pause(),document.querySelectorAll(".vjs-marker").forEach(e=>e.remove());let e=o.current.el().querySelector(".vjs-progress-control"),t=null==e?void 0:e.querySelector(".vjs-progress-holder");t&&l.forEach(e=>{let r=document.createElement("div");r.className="vjs-marker";let n=o.current.duration(),s=e.timestamp/n*100;r.style.left="".concat(s,"%"),r.addEventListener("click",t=>{t.stopPropagation(),J(e.timestamp,e.drawing,e.canvasWidth,e.canvasHeight)}),r.addEventListener("mouseenter",()=>{r.style.width="1rem",r.style.height="400%"}),r.addEventListener("mouseleave",()=>{r.style.width="0.5rem",r.style.height="200%"}),r.title="".concat(I(e.timestamp),": ").concat(e.text),t.appendChild(r)})};(0,s.useEffect)(()=>{if(o.current&&!r)return o.current.on("loadedmetadata",z),z(),()=>{o.current&&o.current.off("loadedmetadata",z)}},[l,t,d]);let A=e=>{let[t,r,n]=I(e.timestamp).split(":");q({...e,editText:e.text,hours:t,minutes:r,seconds:n})},B=(e,t)=>{q(r=>({...r,[e]:t}))},H=(e,t)=>{"Enter"===e.key&&t()},P=async e=>{let t=D.map(t=>t.id===e?{...t,commentDone:!t.commentDone}:t);M(t),O(!1);let r={action:"save",lastUpdated:Date.now(),comments:t};O(!1),T(async()=>{try{M(t),E({type:"check",updatedComments:t}),await Y(r),N(t),x(t),O(!0)}catch(e){console.error("Error updating comments:",e),C({show:!0,message:"Error checking/unchecking comment"})}})},I=e=>{let t=new Date(0);return t.setSeconds(e),t.toISOString().substring(11,19)},U=(e,t,r)=>3600*e+60*t+r,J=(e,t,r,n)=>{o.current&&(v&&p(),o.current.pause(),o.current.one("seeked",()=>{if(i.current&&t){let s=document.querySelector(".canvas-container"),a=document.querySelector(".canvi"),l=document.querySelector(".upper-canvas");s&&(s.style.display="block",s.style.pointerEvents="none"),a&&l&&(a.style.pointerEvents="none",l.style.pointerEvents="none"),i.current.clear();let c=JSON.parse(JSON.stringify(t)),u=d.width/r,m=d.height/n;c.objects&&c.objects.forEach(e=>{let t=e.strokeWidth;e.left=e.left*u,e.top=e.top*m,e.scaleX=e.scaleX*u,e.scaleY=e.scaleY*m,e.strokeWidth=t/((u+m)/2)}),i.current.loadFromJSON(c,()=>{i.current.renderAll(),setTimeout(()=>{i.current.renderAll()},50)});let g=()=>{.1>Math.abs(o.current.currentTime()-e)?(s&&(s.style.display="block"),i.current.renderAll()):s&&f()};h.current&&o.current.off("timeupdate",h.current),g(),o.current.on("timeupdate",g),h.current=g}}),o.current.currentTime(e))},F=(e,t,r,n)=>{let s=document.querySelector(".canvas-container"),a=document.querySelector(".canvi"),l=document.querySelector(".upper-canvas");s&&(s.style.display="block",s.style.pointerEvents="none"),a&&l&&(a.style.pointerEvents="none",l.style.pointerEvents="none"),m(!1);let o=d.width/r,i=d.height/n;c.clear();let u=JSON.parse(JSON.stringify(t));u.objects.forEach(e=>{let t=e.strokeWidth;e.left=e.left*o,e.top=e.top*i,e.scaleX=e.scaleX*o,e.scaleY=e.scaleY*i,e.strokeWidth=t/((o+i)/2)}),c.loadFromJSON(u,()=>{})},V=async()=>{if(!R)return;let e=i.current?i.current.toJSON():null,t=parseInt(R.hours)||0,r=parseInt(R.minutes)||0,n=parseInt(R.seconds)||0,s=U(t=Math.min(Math.max(t,0),23),r=Math.min(Math.max(r,0),59),n=Math.min(Math.max(n,0),59)),a=Date.now(),l={...R,id:a,text:R.editText,timestamp:s,formattedTime:I(s),drawing:e,canvasWidth:d.width,canvasHeight:d.height};try{let e=D.map(e=>e.id===R.id?l:e),t={action:"save",lastUpdated:Date.now(),comments:e};_.current=k,M(e),T(async()=>{try{v&&p(),M(e),E({type:"update",updatedComments:e}),await Y(t),N(e),x(e),q(null)}catch(e){console.error("Error updating comments:",e),C({show:!0,message:"Error updating comment"})}})}catch(e){console.error("Error updating comments:",e)}},X=async()=>{if(!R)return;v&&p();let e=l.filter(e=>e.id!==R.id),t={action:"save",lastUpdated:Date.now(),comments:e};_.current=k,T(async()=>{try{E({type:"delete",updatedComments:e}),await Y(t),N(e),M(e)}catch(e){N(_.current),E(),C({show:!0,message:"Error deleting comment"})}}),f(),x(e),q(null)},[Y,{data:Z,loading:K,error:$,success:G}]=u(g.webhook_url,g.id,g.type);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"flex items-center gap-2 mb-4",children:(0,n.jsx)("h3",{className:"text-sm font-medium text-gray-200 py-2",children:"Comments"})}),(0,n.jsx)("div",{className:"flex-grow overflow-y-auto space-y-2 text-sm scrollbar-thin scrollbar-thumb-gray-600 scrollbar-track-transparent",children:(null==S?void 0:S.length)>0?S.map(e=>R&&R.id===e.id?(0,n.jsxs)("div",{className:"p-2.5 bg-gray-700/50 backdrop-blur-sm rounded-lg",children:[!r&&(0,n.jsxs)("div",{className:"flex gap-1 mb-2",children:[(0,n.jsx)("input",{type:"text",className:"border border-gray-400 p-1 w-10 text-center text-white",value:R.hours,onChange:e=>B("hours",e.target.value)}),":",(0,n.jsx)("input",{type:"text",className:"border border-gray-400 p-1 w-10 text-center text-white",value:R.minutes,onChange:e=>B("minutes",e.target.value)}),":",(0,n.jsx)("input",{type:"text",className:"border border-gray-400 p-1 w-10 text-center text-white",value:R.seconds,onChange:e=>B("seconds",e.target.value)})]}),(0,n.jsx)("input",{type:"text",className:"border border-gray-400 p-2 w-full text-white",value:R.editText,onChange:e=>q({...R,editText:e.target.value}),onKeyPress:e=>H(e,V)}),(0,n.jsxs)("div",{className:"flex gap-2 mt-2",children:[(0,n.jsx)("button",{className:"bg-green-500 text-white px-4 py-1",onClick:V,children:"Save"}),(0,n.jsx)("button",{className:"bg-gray-500 text-white px-4 py-1",onClick:()=>{q(null),v&&p()},children:"Cancel"}),(0,n.jsx)("button",{className:"bg-red-500 text-white px-4 py-1",onClick:X,children:"Delete"})]})]},e.id):(0,n.jsxs)("div",{className:"p-2.5 bg-gray-700/50 backdrop-blur-sm rounded-lg hover:bg-gray-600/50 transition-all duration-200",onClick:()=>r?F(e.timestamp,e.drawing,e.canvasWidth,e.canvasHeight):J(e.timestamp,e.drawing,e.canvasWidth,e.canvasHeight),children:[(0,n.jsxs)("div",{className:"flex justify-between items-center mb-1",children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,n.jsx)("button",{onClick:()=>P(e.id),className:"relative w-4 h-4 flex items-center justify-center",children:(0,n.jsx)("div",{className:"\n w-4 h-4 border-2 rounded \n transition-all duration-200 ease-in-out\n ".concat(e.commentDone?"border-green-500 bg-green-500":"border-gray-400 bg-transparent","\n "),children:e.commentDone&&(0,n.jsx)("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 13l4 4L19 7"})})})}),!r&&(0,n.jsx)("span",{className:"text-blue-400 cursor-pointer hover:text-blue-300 text-xs ".concat(e.commentDone?"line-through text-gray-400":""),onClick:()=>J(e.timestamp,e.drawing,e.canvasWidth,e.canvasHeight),children:null==e?void 0:e.formattedTime})]}),(0,n.jsx)("button",{className:"text-gray-400 hover:text-white transition-colors duration-200 text-xs",onClick:()=>A(e),children:"✏️"})]}),(0,n.jsx)("div",{className:"text-gray-200 break-words text-xs pl-6 ".concat(e.commentDone?"line-through text-gray-400":""),children:e.text})]},e.id)):(0,n.jsx)("p",{className:"text-gray-400 text-center py-4 text-xs",children:"No comments yet"})})]})},p=e=>{let{isVideoLoaded:t,playerRef:r,fabricCanvasRef:a,dimensions:l,setComments:o,comments:i,clearCanvas:c,isDrawingMode:d,toggleDrawingMode:m,queryParams:h,setStateMessage:g,dataComments:p,setDataComments:x,optimisticComments:v,setOptimisticComments:w,canva:f,isImage:y,setIsDrawingMode:b,lastUpdatedComments:j,setLastUpdatedComments:C}=e,[k,N]=(0,s.useState)(""),S=(0,s.useRef)(null),[E,D]=(0,s.useTransition)(),[M,{data:R,loading:q,error:L,success:O}]=u(h.webhook_url,h.id,h.type),_=async()=>{let e;let t=a.current?a.current.toJSON():null;if(0===t.objects.length&&""===k)return;e=t.objects.length>0&&""===k?"*drawing only*":k;let n={id:Date.now(),text:e,timestamp:y?null:r.current.currentTime(),formattedTime:y?null:(e=>{let t=new Date(0);return t.setSeconds(e),t.toISOString().substring(11,19)})(r.current.currentTime()),drawing:t,canvasWidth:l.width,canvasHeight:l.height,commentDone:!1},s={action:"save",lastUpdated:Date.now(),comments:[...i,n]};N(""),b(!1),C(s.comments),D(async()=>{try{!y&&s.comments&&Array.isArray(s.comments)&&s.comments.sort((e,t)=>null===e.timestamp?1:null===t.timestamp?-1:e.timestamp-t.timestamp),w({type:"add",updatedComments:s.comments});let e=document.querySelector(".canvas-container");e&&(e.style.display="none");let t=document.querySelector(".canvi");t&&(t.style.pointerEvents="none");let n=document.querySelector(".upper-canvas");n&&(n.style.pointerEvents="none"),y||r.current.controls(!0),f.clear(),C(s.comments),await M(s),x(s.comments),o(s.comments)}catch(a){console.error("Error adding comment:",a),g({show:!0,message:"Error adding comment"}),N(s.comments[s.comments.length-1].text);let e=document.querySelector(".canvas-container");e&&(e.style.display="block");let t=document.querySelector(".canvi");t&&(t.style.pointerEvents="auto");let r=document.querySelector(".upper-canvas");r&&(r.style.pointerEvents="auto"),f.clear();let n=JSON.parse(JSON.stringify(s.comments[s.comments.length-1].drawing));f.loadFromJSON(n),b(!0)}}),S.current&&(S.current.style.height="auto")};return(0,n.jsx)("div",{children:t&&(0,n.jsx)("div",{className:" mt-4 w-full flex justify-center",children:(0,n.jsxs)("div",{className:"relative w-[600px] max-w-full",children:[(0,n.jsx)("textarea",{ref:S,className:"w-full bg-gray-800/50 backdrop-blur-sm text-white px-4 py-3 pr-40 rounded-xl focus:ring-2 focus:ring-blue-500 focus:outline-none min-h-[44px] max-h-[200px] resize-y md:text-sm text-base shadow-lg",value:k,onChange:e=>N(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),_())},placeholder:"Add a comment...",style:{overflow:"hidden",lineHeight:"1.5",fontSize:"14px",WebkitTextSizeAdjust:"100%"},onInput:e=>{e.target.style.height="auto",e.target.style.height=e.target.scrollHeight+"px"}}),(0,n.jsxs)("div",{className:"absolute right-2 top-2 flex gap-2",children:[(0,n.jsx)("button",{className:"p-1.5 rounded-md transition-all duration-200 ".concat(d?"bg-red-500 hover:bg-red-600":"bg-gray-600 hover:bg-gray-500"),onClick:()=>m(),title:d?"Stop Drawing":"Start Drawing",children:d?(0,n.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-white",viewBox:"0 0 20 20",fill:"currentColor",children:[(0,n.jsx)("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM8 7a1 1 0 00-1 1v4a1 1 0 002 0V8a1 1 0 00-1-1z",clipRule:"evenodd"}),(0,n.jsx)("path",{fillRule:"evenodd",d:"M12 7a1 1 0 00-1 1v4a1 1 0 002 0V8a1 1 0 00-1-1z",clipRule:"evenodd"})]}):(0,n.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-white",viewBox:"0 0 20 20",fill:"currentColor",children:(0,n.jsx)("path",{fillRule:"evenodd",d:"M13.293 3.293a1 1 0 011.414 0l2 2a1 1 0 010 1.414l-9 9a1 1 0 01-.39.242l-3 1a1 1 0 01-1.266-1.265l1-3a1 1 0 01.242-.391l9-9zM14 4l2 2-9 9-3 1 1-3 9-9z",clipRule:"evenodd"})})}),(0,n.jsx)("button",{className:"bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded-md transition-all duration-200 text-sm",onClick:_,children:"Add"})]})]})})})},x=()=>{var e,t;let[r,c]=(0,s.useState)({show:!1,message:"Hola muuundo"}),[x,v]=(0,s.useState)(""),[w,f]=(0,s.useState)([]),[y,b]=(0,s.useState)(!0),[j,C]=(0,s.useState)([]),[k,N]=(0,s.useState)(!1),[S,E]=(0,s.useState)(!1),[D,M]=(0,s.useState)(!1),[R,q]=(0,s.useState)([]),[L,O]=(0,s.useState)(!1),_=(0,s.useRef)(null),W=(0,s.useRef)(null),T=(0,s.useRef)(null),z=(0,s.useRef)(null),A=(0,s.useRef)(null),B=(0,s.useRef)(()=>{}),[H,P]=(0,s.useState)(null),[I,U]=o(),[J,F]=i(),[V,X]=(0,s.useState)(()=>{{let e=new URLSearchParams(window.location.search);return{webhook_url:e.get("webhook_url"),id:e.get("id"),type:e.get("type")}}}),[Y,Z]=(0,s.useOptimistic)(j,(e,t)=>{switch(null==t?void 0:t.type){case"delete":case"update":case"check":case"add":return t.updatedComments;default:return e}}),[K,$]=(0,s.useState)("no_status"),G=(0,s.useRef)(K),[Q,ee]=(0,s.useOptimistic)(K,(e,t)=>(null==t?void 0:t.type)==="save"?t.status:e),[et,er]=(0,s.useTransition)(),{data:en,loading:es,error:ea,handleFetch:el}=d(V.webhook_url,V.id,V.type),[eo,{data:ei,loading:ec,error:ed,success:eu}]=u(V.webhook_url,V.id,V.type);(0,s.useEffect)(()=>{en&&y&&b(!1)},[en]),(0,s.useEffect)(()=>{en&&f(en.comments)},[en]),(0,s.useEffect)(()=>{if(z.current.width=U.width,z.current.height=U.height,en&&!ev(en.video_url)&&W.current&&!T.current){T.current=(0,a.A)(W.current,{controls:!0,fluid:!0,bigPlayButton:!1,userActions:{hotkeys:!0,doubleClick:!0},controlBar:{progressControl:!0}});let e=document.querySelector(".vjs-control-bar");e&&(e.style.display="flex");let t=T.current;t.on("play",()=>{if(A.current){A.current.clear();let e=document.querySelector(".canvas-container");e&&(e.style.display="none")}}),t.on("seeking",()=>{}),t.src({src:null==en?void 0:en.video_url,type:"video/mp4"}),N(!0);try{if(z.current&&!A.current){let e=new l.Hl(z.current);A.current=e,P(e),e.freeDrawingBrush=new l.mW(e),e.freeDrawingBrush.width=4,e.freeDrawingBrush.color="#ff0000",e.isDrawingMode=!1,T.current.on("loadedmetadata",()=>{let t=T.current.el();t&&e&&(e.setDimensions({width:t.offsetWidth,height:t.offsetHeight},{cssOnly:!1}),e.renderAll());let r=document.querySelector(".canvas-container");r&&(r.style.display="none")})}}catch(e){console.error("Fabric canvas initialization error:",e)}}},[en]),(0,s.useEffect)(()=>{if(en&&ev(en.video_url)&&(O(ev(en.video_url)),_.current))try{if(z.current&&!A.current){let e=new l.Hl(z.current);A.current=e,P(e),e.freeDrawingBrush=new l.mW(e),e.freeDrawingBrush.width=4,e.freeDrawingBrush.color="#ff0000",e.isDrawingMode=!1;let t=_.current;e.setDimensions({width:t.naturalWidth,height:t.naturalHeight},{cssOnly:!1});let r=document.querySelector(".canvas-container");r&&(r.style.display="none"),e.renderAll()}}catch(e){console.error("Fabric canvas initialization error:",e)}},[en,_.current]),(0,s.useEffect)(()=>{if(H){let e=H.width,t=H.height,r=U.width/e,n=U.height/t;H.setDimensions({width:U.width,height:U.height}),H.getObjects().forEach(e=>{let t=e.strokeWidth;e.left=e.left*r,e.top=e.top*n,e.scaleX=e.scaleX*r,e.scaleY=e.scaleY*n,e.strokeWidth=t/((r+n)/2),e.setCoords()}),H.renderAll()}},[U]);let em=()=>{A.current&&(E(!S),A.current.isDrawingMode=!S,A.current.clear());let e=document.querySelector(".canvas-container");e&&(e.style.display=S?"none":"block");let t=document.querySelector(".canvi");t&&(t.style.pointerEvents=S?"none":"auto");let r=document.querySelector(".upper-canvas");r&&(r.style.pointerEvents=S?"none":"auto"),L||(S||T.current.pause(),document.querySelector(".video-js"),S?T.current.controls(!0):T.current.controls(!1))},eh=()=>{A.current&&A.current.clear()},eg=async(e,t)=>{try{let r={action:"save",lastUpdated:Date.now(),status:e,comments:t};er(async()=>{try{G.current=K,ee({type:"save",status:e}),await eo(r),$(e)}catch(e){$(G.current),ee(),c({show:!0,message:"Error saving the state"})}})}catch(e){console.error("Error al guardar el estado:",e)}};(0,s.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search);X({webhook_url:e.get("webhook_url"),id:e.get("id")})};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]);let[ep,ex]=(0,s.useState)(!0);(0,s.useEffect)(()=>{en&&en.status&&($(en.status),N(!0))},[en]);let ev=e=>/\.(jpg|jpeg|png|gif|bmp|webp|svg)(\?.*)?$/i.test(e);return(0,n.jsxs)("div",{className:"min-h-screen bg-gray-900",children:[(0,n.jsxs)("div",{className:"flex flex-col lg:flex-row min-h-screen",children:[(0,n.jsx)("div",{className:"flex-1 transition-all duration-300 ease-in-out \n ".concat(ep?"lg:pr-80":"lg:pr-0","\n ").concat(ep?"mb-[50vh]":"mb-0"," lg:mb-0\n "),children:(0,n.jsxs)("div",{className:"container-principal w-[100%] flex flex-col justify-center ",ref:J,children:[(0,n.jsxs)("div",{className:"video-container relative w-full mt-4 ",ref:I,children:[L?(0,n.jsx)("img",{ref:_,src:en.video_url,style:{width:"100%",height:"100%",objectFit:"contain",objectPosition:"center"}}):(0,n.jsx)("video",{ref:W,className:"video-js vjs-big-play-centered w-full vjs-big-play-button-hide",playsInline:!0,controls:!0}),(0,n.jsx)("canvas",{ref:z,className:"canvi absolute top-0 left-0 pointer-events-auto w-full h-full",style:{zIndex:1,width:"100%",height:"100%"}})]}),(0,n.jsx)(p,{setIsDrawingMode:E,isVideoLoaded:k,playerRef:T,fabricCanvasRef:A,dimensions:U,setComments:f,comments:w,handlePostComment:eo,clearCanvas:eh,isDrawingMode:S,toggleDrawingMode:em,queryParams:V,dataComments:j,setDataComments:C,setOptimisticComments:Z,setStateMessage:c,canva:H,isImage:L,lastUpdatedComments:R,setLastUpdatedComments:q})]})}),!ep&&(0,n.jsx)("button",{onClick:()=>ex(e=>!e),className:"fixed z-50 bg-gray-800/50 backdrop-blur-sm p-2 rounded-full hover:bg-gray-700/50 transition-all duration-200 right-4 bottom-4 lg:top-4 lg:bottom-auto",title:ep?"Hide Comments":"Show Comments",children:(0,n.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,n.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"})})}),(0,n.jsx)("div",{className:"fixed transition-all duration-300 ease-in-out\n lg:w-80 w-full h-[min(50vh,300px)] lg:h-screen\n lg:right-0 right-0\n lg:top-0 bottom-0\n bg-gray-800/50 backdrop-blur-sm\n ".concat(ep?"translate-y-0 lg:translate-x-0":"translate-y-full lg:translate-x-full","\n "),children:k&&(0,n.jsxs)("div",{className:"h-full p-4 flex flex-col",children:[(0,n.jsxs)("div",{className:"mb-4",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,n.jsx)("div",{className:"flex items-center gap-2",children:(0,n.jsx)("label",{className:"text-sm font-medium text-gray-200",children:"Video Status"})}),(0,n.jsx)("div",{className:"flex justify-end items-center",children:(0,n.jsx)("a",{href:"https://www.skool.com/no-code-architects",target:"_blank",rel:"noopener noreferrer",className:"cursor-pointer hover:opacity-80 transition-opacity",children:(0,n.jsx)("img",{src:"/logo.png",alt:"logo",className:"w-10 h-10"})})})]}),(0,n.jsx)("select",{value:Q,onChange:e=>{eg(e.target.value,w)},className:"w-full px-3 py-2 rounded-lg transition-colors duration-200 text-sm ".concat(null===(e=m[K])||void 0===e?void 0:e.bgColor," ").concat(null===(t=m[K])||void 0===t?void 0:t.textColor),style:{appearance:"none",backgroundImage:"url(\"data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e\")",backgroundRepeat:"no-repeat",backgroundPosition:"right 0.75rem center",backgroundSize:"1rem",paddingRight:"2.5rem"},children:Object.entries(m).map(e=>{let[t,{label:r,bgColor:s,textColor:a}]=e;return(0,n.jsx)("option",{value:t,className:"".concat(s," ").concat(a),style:{backgroundColor:"rgba(0,0,0,0.5)"},children:r},t)})})]}),(0,n.jsx)(g,{isVideoLoaded:k,comments:w,setComments:f,handlePostComment:eo,handleFetch:el,playerRef:T,fabricCanvasRef:A,canva:H,dimensions:U,setIsDrawingMode:E,updateHandlerRef:B,queryParams:V,toggleDrawingMode:em,isDrawingMode:S,data:en,clearCanvas:eh,setVideoStatus:$,setStateMessage:c,dataComments:j,setDataComments:C,optimisticComments:Y,setOptimisticComments:Z,imageRef:_,isImage:L,lastUpdatedComments:R,setLastUpdatedComments:q})]})})]}),y&&(0,n.jsx)("div",{className:"fixed inset-0 bg-gray-900 z-50 flex items-center justify-center",children:(0,n.jsxs)("div",{className:"flex flex-col items-center",children:[(0,n.jsx)("img",{src:"/logo.png",alt:"logo",className:"w-20 h-20 animate-pulse"}),(0,n.jsxs)("div",{className:"mt-4 flex items-center gap-2",children:[(0,n.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-bounce",style:{animationDelay:"0s"}}),(0,n.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-bounce",style:{animationDelay:"0.2s"}}),(0,n.jsx)("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-bounce",style:{animationDelay:"0.4s"}})]})]})}),(0,n.jsx)(h,{active:r.show,message:r.message,setStateMessage:c})]})}}},e=>{var t=t=>e(e.s=t);e.O(0,[953,776,742,821,441,587,358],()=>t(2088)),_N_E=e.O()}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/framework-fabc53829daf7685.js b/services/v1/media/feedback/static/_next/static/chunks/framework-fabc53829daf7685.js new file mode 100644 index 0000000000000000000000000000000000000000..8e5fc0cb2e9ea9e1fe061f52e2d957c7e7778ff2 --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/framework-fabc53829daf7685.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[593],{2167:(e,t,n)=>{var r=n(9742),l=Symbol.for("react.transitional.element"),a=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),u=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),c=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.iterator,g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,v={};function b(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}function k(){}function w(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}b.prototype.isReactComponent={},b.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},b.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},k.prototype=b.prototype;var S=w.prototype=new k;S.constructor=w,y(S,b.prototype),S.isPureReactComponent=!0;var x=Array.isArray,E={H:null,A:null,T:null,S:null},C=Object.prototype.hasOwnProperty;function _(e,t,n,r,a,o){return{$$typeof:l,type:e,key:t,ref:void 0!==(n=o.ref)?n:null,props:o}}function P(e){return"object"==typeof e&&null!==e&&e.$$typeof===l}var z=/\/+/g;function N(e,t){var n,r;return"object"==typeof e&&null!==e&&null!=e.key?(n=""+e.key,r={"=":"=0",":":"=2"},"$"+n.replace(/[=:]/g,function(e){return r[e]})):t.toString(36)}function T(){}function L(e,t,n){if(null==e)return e;var r=[],o=0;return!function e(t,n,r,o,i){var u,s,c,f=typeof t;("undefined"===f||"boolean"===f)&&(t=null);var d=!1;if(null===t)d=!0;else switch(f){case"bigint":case"string":case"number":d=!0;break;case"object":switch(t.$$typeof){case l:case a:d=!0;break;case m:return e((d=t._init)(t._payload),n,r,o,i)}}if(d)return i=i(t),d=""===o?"."+N(t,0):o,x(i)?(r="",null!=d&&(r=d.replace(z,"$&/")+"/"),e(i,n,r,"",function(e){return e})):null!=i&&(P(i)&&(u=i,s=r+(null==i.key||t&&t.key===i.key?"":(""+i.key).replace(z,"$&/")+"/")+d,i=_(u.type,s,void 0,void 0,void 0,u.props)),n.push(i)),1;d=0;var p=""===o?".":o+":";if(x(t))for(var g=0;g{e.exports=n(5919)},4232:(e,t,n)=>{e.exports=n(2167)},4279:(e,t,n)=>{var r,l,a=n(9742),o=n(2786),i=n(4232),u=n(8477);function s(e){var t="https://react.dev/errors/"+e;if(1)":-1l||u[r]!==s[l]){var c="\n"+u[r].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=r&&0<=l);break}}}finally{F=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?A(n):""}function M(e){try{var t="";do t+=function(e){switch(e.tag){case 26:case 27:case 5:return A(e.type);case 16:return A("Lazy");case 13:return A("Suspense");case 19:return A("SuspenseList");case 0:case 15:return e=D(e.type,!1);case 11:return e=D(e.type.render,!1);case 1:return e=D(e.type,!0);default:return""}}(e),e=e.return;while(e);return t}catch(e){return"\nError generating stack: "+e.message+"\n"+e.stack}}function I(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do 0!=(4098&(t=e).flags)&&(n=t.return),e=t.return;while(e)}return 3===t.tag?n:null}function U(e){if(13===e.tag){var t=e.memoizedState;if(null===t&&null!==(e=e.alternate)&&(t=e.memoizedState),null!==t)return t.dehydrated}return null}function j(e){if(I(e)!==e)throw Error(s(188))}var H=Array.isArray,$=u.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},B=[],W=-1;function Q(e){return{current:e}}function q(e){0>W||(e.current=B[W],B[W]=null,W--)}function K(e,t){B[++W]=e.current,e.current=t}var Y=Q(null),G=Q(null),X=Q(null),Z=Q(null);function J(e,t){switch(K(X,t),K(G,e),K(Y,null),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)&&(t=t.namespaceURI)?u5(t):0;break;default:if(t=(e=8===e?t.parentNode:t).tagName,e=e.namespaceURI)t=u9(e=u5(e),t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}q(Y),K(Y,t)}function ee(){q(Y),q(G),q(X)}function et(e){null!==e.memoizedState&&K(Z,e);var t=Y.current,n=u9(t,e.type);t!==n&&(K(G,e),K(Y,n))}function en(e){G.current===e&&(q(Y),q(G)),Z.current===e&&(q(Z),sM._currentValue=V)}var er=Object.prototype.hasOwnProperty,el=o.unstable_scheduleCallback,ea=o.unstable_cancelCallback,eo=o.unstable_shouldYield,ei=o.unstable_requestPaint,eu=o.unstable_now,es=o.unstable_getCurrentPriorityLevel,ec=o.unstable_ImmediatePriority,ef=o.unstable_UserBlockingPriority,ed=o.unstable_NormalPriority,ep=o.unstable_LowPriority,em=o.unstable_IdlePriority,eh=o.log,eg=o.unstable_setDisableYieldValue,ey=null,ev=null;function eb(e){if("function"==typeof eh&&eg(e),ev&&"function"==typeof ev.setStrictMode)try{ev.setStrictMode(ey,e)}catch(e){}}var ek=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(ew(e)/eS|0)|0},ew=Math.log,eS=Math.LN2,ex=128,eE=4194304;function eC(e){var t=42&e;if(0!==t)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194176&e;case 4194304:case 8388608:case 0x1000000:case 0x2000000:return 0x3c00000&e;case 0x4000000:return 0x4000000;case 0x8000000:return 0x8000000;case 0x10000000:return 0x10000000;case 0x20000000:return 0x20000000;case 0x40000000:return 0;default:return e}}function e_(e,t){var n=e.pendingLanes;if(0===n)return 0;var r=0,l=e.suspendedLanes,a=e.pingedLanes,o=e.warmLanes;e=0!==e.finishedLanes;var i=0x7ffffff&n;return 0!==i?0!=(n=i&~l)?r=eC(n):0!=(a&=i)?r=eC(a):e||0!=(o=i&~o)&&(r=eC(o)):0!=(i=n&~l)?r=eC(i):0!==a?r=eC(a):e||0!=(o=n&~o)&&(r=eC(o)),0===r?0:0!==t&&t!==r&&0==(t&l)&&((l=r&-r)>=(o=t&-t)||32===l&&0!=(4194176&o))?t:r}function eP(e,t){return 0==(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)}function ez(){var e=ex;return 0==(4194176&(ex<<=1))&&(ex=128),e}function eN(){var e=eE;return 0==(0x3c00000&(eE<<=1))&&(eE=4194304),e}function eT(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function eL(e,t){e.pendingLanes|=t,0x10000000!==t&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function eO(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-ek(t);e.entangledLanes|=t,e.entanglements[r]=0x40000000|e.entanglements[r]|4194218&n}function eR(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-ek(n),l=1<=ne),nr=!1;function nl(e,t){switch(e){case"keyup":return -1!==t9.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function na(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var no=!1,ni={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function nu(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!ni[e.type]:"textarea"===t}function ns(e,t,n,r){tw?tS?tS.push(r):tS=[r]:tw=r,0<(t=uq(t,"onChange")).length&&(n=new tH("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var nc=null,nf=null;function nd(e){uU(e,0)}function np(e){if(tt(eK(e)))return e}function nm(e,t){if("change"===e)return t}var nh=!1;if(e1){if(e1){var ng="oninput"in document;if(!ng){var ny=document.createElement("div");ny.setAttribute("oninput","return;"),ng="function"==typeof ny.oninput}r=ng}else r=!1;nh=r&&(!document.documentMode||9=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=n_(r)}}function nz(e){e=null!=e&&null!=e.ownerDocument&&null!=e.ownerDocument.defaultView?e.ownerDocument.defaultView:window;for(var t=tn(e.document);t instanceof e.HTMLIFrameElement;){try{var n="string"==typeof t.contentWindow.location.href}catch(e){n=!1}if(n)e=t.contentWindow;else break;t=tn(e.document)}return t}function nN(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var nT=e1&&"documentMode"in document&&11>=document.documentMode,nL=null,nO=null,nR=null,nA=!1;function nF(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;nA||null==nL||nL!==tn(r)||(r="selectionStart"in(r=nL)&&nN(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},nR&&nC(nR,r)||(nR=r,0<(r=uq(nO,"onSelect")).length&&(t=new tH("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=nL)))}function nD(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var nM={animationend:nD("Animation","AnimationEnd"),animationiteration:nD("Animation","AnimationIteration"),animationstart:nD("Animation","AnimationStart"),transitionrun:nD("Transition","TransitionRun"),transitionstart:nD("Transition","TransitionStart"),transitioncancel:nD("Transition","TransitionCancel"),transitionend:nD("Transition","TransitionEnd")},nI={},nU={};function nj(e){if(nI[e])return nI[e];if(!nM[e])return e;var t,n=nM[e];for(t in n)if(n.hasOwnProperty(t)&&t in nU)return nI[e]=n[t];return e}e1&&(nU=document.createElement("div").style,"AnimationEvent"in window||(delete nM.animationend.animation,delete nM.animationiteration.animation,delete nM.animationstart.animation),"TransitionEvent"in window||delete nM.transitionend.transition);var nH=nj("animationend"),n$=nj("animationiteration"),nV=nj("animationstart"),nB=nj("transitionrun"),nW=nj("transitionstart"),nQ=nj("transitioncancel"),nq=nj("transitionend"),nK=new Map,nY="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll scrollEnd toggle touchMove waiting wheel".split(" ");function nG(e,t){nK.set(e,t),eJ(t,[e])}var nX=[],nZ=0,nJ=0;function n0(){for(var e=nZ,t=nJ=nZ=0;t>=o,l-=o,ro=1<<32-ek(t)+l|n<d?(p=f,f=null):p=f.sibling;var m=g(l,f,i[d],u);if(null===m){null===f&&(f=p);break}e&&f&&null===m.alternate&&t(l,f),o=a(m,o,d),null===c?s=m:c.sibling=m,c=m,f=p}if(d===i.length)return n(l,f),rm&&ru(l,d),s;if(null===f){for(;dp?(m=d,d=null):m=d.sibling;var b=g(l,d,v.value,u);if(null===b){null===d&&(d=m);break}e&&d&&null===b.alternate&&t(l,d),o=a(b,o,p),null===f?c=b:f.sibling=b,f=b,d=m}if(v.done)return n(l,d),rm&&ru(l,p),c;if(null===d){for(;!v.done;p++,v=i.next())null!==(v=h(l,v.value,u))&&(o=a(v,o,p),null===f?c=v:f.sibling=v,f=v);return rm&&ru(l,p),c}for(d=r(d);!v.done;p++,v=i.next())null!==(v=y(d,l,p,v.value,u))&&(e&&null!==v.alternate&&d.delete(null===v.key?p:v.key),o=a(v,o,p),null===f?c=v:f.sibling=v,f=v);return e&&d.forEach(function(e){return t(l,e)}),rm&&ru(l,p),c}(u,c,f=k.call(f),v)}if("function"==typeof f.then)return i(u,c,rA(f),v);if(f.$$typeof===b)return i(u,c,op(u,f),v);rD(u,f)}return"string"==typeof f&&""!==f||"number"==typeof f||"bigint"==typeof f?(f=""+f,null!==c&&6===c.tag?(n(u,c.sibling),(v=l(c,f)).return=u):(n(u,c),(v=im(f,u.mode,v)).return=u),o(u=v)):n(u,c)}(i,u,c,f);return rO=null,v}catch(e){if(e===rE)throw e;var k=io(29,e,null,i.mode);return k.lanes=f,k.return=i,k}finally{}}}var rU=rI(!0),rj=rI(!1),rH=Q(null),r$=Q(0);function rV(e,t){K(r$,e=iR),K(rH,t),iR=e|t.baseLanes}function rB(){K(r$,iR),K(rH,rH.current)}function rW(){iR=r$.current,q(rH),q(r$)}var rQ=Q(null),rq=null;function rK(e){var t=e.alternate;K(rZ,1&rZ.current),K(rQ,e),null===rq&&(null===t||null!==rH.current?rq=e:null!==t.memoizedState&&(rq=e))}function rY(e){if(22===e.tag){if(K(rZ,rZ.current),K(rQ,e),null===rq){var t=e.alternate;null!==t&&null!==t.memoizedState&&(rq=e)}}else rG(e)}function rG(){K(rZ,rZ.current),K(rQ,rQ.current)}function rX(e){q(rQ),rq===e&&(rq=null),q(rZ)}var rZ=Q(0);function rJ(e){for(var t=e;null!==t;){if(13===t.tag){var n=t.memoizedState;if(null!==n&&(null===(n=n.dehydrated)||"$?"===n.data||"$!"===n.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(0!=(128&t.flags))return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var r0="undefined"!=typeof AbortController?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(t,n){e.push(n)}};this.abort=function(){t.aborted=!0,e.forEach(function(e){return e()})}},r1=o.unstable_scheduleCallback,r2=o.unstable_NormalPriority,r3={$$typeof:b,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function r4(){return{controller:new r0,data:new Map,refCount:0}}function r6(e){e.refCount--,0===e.refCount&&r1(r2,function(){e.controller.abort()})}var r8=null,r5=0,r9=0,r7=null;function le(){if(0==--r5&&null!==r8){null!==r7&&(r7.status="fulfilled");var e=r8;r8=null,r9=0,r7=null;for(var t=0;ta?a:8;var o=O.T,i={};O.T=i,av(e,!1,t,n);try{var u=l(),s=O.S;if(null!==s&&s(i,u),null!==u&&"object"==typeof u&&"function"==typeof u.then){var c,f,d=(c=[],f={status:"pending",value:null,reason:null,then:function(e){c.push(e)}},u.then(function(){f.status="fulfilled",f.value=r;for(var e=0;e title"))),u3(a,r,n),a[eM]=e,eG(a),r=a;break e;case"link":var o=sz("link","href",l).get(r+(n.href||""));if(o){for(var i=0;i<\/script>",e=e.removeChild(e.firstChild);break;case"select":e="string"==typeof r.is?l.createElement("select",{is:r.is}):l.createElement("select"),r.multiple?e.multiple=!0:r.size&&(e.size=r.size);break;default:e="string"==typeof r.is?l.createElement(n,{is:r.is}):l.createElement(n)}}e[eM]=t,e[eI]=r;e:for(l=t.child;null!==l;){if(5===l.tag||6===l.tag)e.appendChild(l.stateNode);else if(4!==l.tag&&27!==l.tag&&null!==l.child){l.child.return=l,l=l.child;continue}if(l===t)break;for(;null===l.sibling;){if(null===l.return||l.return===t)break e;l=l.return}l.sibling.return=l.return,l=l.sibling}switch(t.stateNode=e,u3(e,n,r),n){case"button":case"input":case"select":case"textarea":e=!!r.autoFocus;break;case"img":e=!0;break;default:e=!1}e&&ig(t)}}return ik(t),t.flags&=-0x1000001,null;case 6:if(e&&null!=t.stateNode)e.memoizedProps!==r&&ig(t);else{if("string"!=typeof r&&null===t.stateNode)throw Error(s(166));if(e=X.current,rw(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,null!==(l=rd))switch(l.tag){case 27:case 5:r=l.memoizedProps}e[eM]=t,(e=!!(e.nodeValue===n||null!==r&&!0===r.suppressHydrationWarning||uJ(e.nodeValue,n)))||rv(t)}else(e=u8(e).createTextNode(r))[eM]=t,t.stateNode=e}return ik(t),null;case 13:if(r=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(l=rw(t),null!==r&&null!==r.dehydrated){if(null===e){if(!l)throw Error(s(318));if(!(l=null!==(l=t.memoizedState)?l.dehydrated:null))throw Error(s(317));l[eM]=t}else rS(),0==(128&t.flags)&&(t.memoizedState=null),t.flags|=4;ik(t),l=!1}else null!==rh&&(i4(rh),rh=null),l=!0;if(!l){if(256&t.flags)return rX(t),t;return rX(t),null}}if(rX(t),0!=(128&t.flags))return t.lanes=n,t;if(n=null!==r,e=null!==e&&null!==e.memoizedState,n){r=t.child,l=null,null!==r.alternate&&null!==r.alternate.memoizedState&&null!==r.alternate.memoizedState.cachePool&&(l=r.alternate.memoizedState.cachePool.pool);var a=null;null!==r.memoizedState&&null!==r.memoizedState.cachePool&&(a=r.memoizedState.cachePool.pool),a!==l&&(r.flags|=2048)}return n!==e&&n&&(t.child.flags|=8192),iv(t,t.updateQueue),ik(t),null;case 4:return ee(),null===e&&uV(t.stateNode.containerInfo),ik(t),null;case 10:return oo(t.type),ik(t),null;case 19:if(q(rZ),null===(l=t.memoizedState))return ik(t),null;if(r=0!=(128&t.flags),null===(a=l.rendering)){if(r)ib(l,!1);else{if(0!==iA||null!==e&&0!=(128&e.flags))for(e=t.child;null!==e;){if(null!==(a=rJ(e))){for(t.flags|=128,ib(l,!1),e=a.updateQueue,t.updateQueue=e,iv(t,e),t.subtreeFlags=0,e=n,n=t.child;null!==n;)is(n,e),n=n.sibling;return K(rZ,1&rZ.current|2),t.child}e=e.sibling}null!==l.tail&&eu()>iB&&(t.flags|=128,r=!0,ib(l,!1),t.lanes=4194304)}}else{if(!r){if(null!==(e=rJ(a))){if(t.flags|=128,r=!0,e=e.updateQueue,t.updateQueue=e,iv(t,e),ib(l,!0),null===l.tail&&"hidden"===l.tailMode&&!a.alternate&&!rm)return ik(t),null}else 2*eu()-l.renderingStartTime>iB&&0x20000000!==n&&(t.flags|=128,r=!0,ib(l,!1),t.lanes=4194304)}l.isBackwards?(a.sibling=t.child,t.child=a):(null!==(e=l.last)?e.sibling=a:t.child=a,l.last=a)}if(null!==l.tail)return t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=eu(),t.sibling=null,e=rZ.current,K(rZ,r?1&e|2:1&e),t;return ik(t),null;case 22:case 23:return rX(t),rW(),r=null!==t.memoizedState,null!==e?null!==e.memoizedState!==r&&(t.flags|=8192):r&&(t.flags|=8192),r?0!=(0x20000000&n)&&0==(128&t.flags)&&(ik(t),6&t.subtreeFlags&&(t.flags|=8192)):ik(t),null!==(n=t.updateQueue)&&iv(t,n.retryQueue),n=null,null!==e&&null!==e.memoizedState&&null!==e.memoizedState.cachePool&&(n=e.memoizedState.cachePool.pool),r=null,null!==t.memoizedState&&null!==t.memoizedState.cachePool&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),null!==e&&q(ln),null;case 24:return n=null,null!==e&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),oo(r3),ik(t),null;case 25:return null}throw Error(s(156,t.tag))}(t.alternate,t,iR);if(null!==n){i_=n;return}if(null!==(t=t.sibling)){i_=t;return}i_=t=e}while(null!==t);0===iA&&(iA=5)}function us(e,t){do{var n=function(e,t){switch(rf(t),t.tag){case 1:return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return oo(r3),ee(),0!=(65536&(e=t.flags))&&0==(128&e)?(t.flags=-65537&e|128,t):null;case 26:case 27:case 5:return en(t),null;case 13:if(rX(t),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(s(340));rS()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return q(rZ),null;case 4:return ee(),null;case 10:return oo(t.type),null;case 22:case 23:return rX(t),rW(),null!==e&&q(ln),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 24:return oo(r3),null;default:return null}}(e.alternate,e);if(null!==n){n.flags&=32767,i_=n;return}if(null!==(n=e.return)&&(n.flags|=32768,n.subtreeFlags=0,n.deletions=null),!t&&null!==(e=e.sibling)){i_=e;return}i_=e=n}while(null!==e);iA=6,i_=null}function uc(e,t,n,r,l,a,o,i,u,c){var f=O.T,d=$.p;try{$.p=2,O.T=null,function(e,t,n,r,l,a,o,i){do ud();while(null!==iK);if(0!=(6&iE))throw Error(s(327));var u,c,f=e.finishedWork;if(r=e.finishedLanes,null!==f){if(e.finishedWork=null,e.finishedLanes=0,f===e.current)throw Error(s(177));e.callbackNode=null,e.callbackPriority=0,e.cancelPendingCommit=null;var d=f.lanes|f.childLanes;if(function(e,t,n,r,l,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var i=e.entanglements,u=e.expirationTimes,s=e.hiddenUpdates;for(n=o&~n;0r&&(l=r,r=a,a=l),l=nP(t,a);var o=nP(t,r);l&&o&&(1!==n.rangeCount||n.anchorNode!==l.node||n.anchorOffset!==l.offset||n.focusNode!==o.node||n.focusOffset!==o.offset)&&((e=e.createRange()).setStart(l.node,l.offset),n.removeAllRanges(),a>r?(n.addRange(e),n.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),n.addRange(e)))}}for(e=[],n=t;n=n.parentNode;)1===n.nodeType&&e.push({element:n,left:n.scrollLeft,top:n.scrollTop});for("function"==typeof t.focus&&t.focus(),t=0;tn?32:n,O.T=null,null===iK)var a=!1;else{n=iX,iX=null;var o=iK,i=iY;if(iK=null,iY=0,0!=(6&iE))throw Error(s(331));var u=iE;if(iE|=4,ir(o.current),o6(o,o.current,i,n),iE=u,uP(0,!1),ev&&"function"==typeof ev.onPostCommitFiberRoot)try{ev.onPostCommitFiberRoot(ey,o)}catch(e){}a=!0}return a}finally{$.p=l,O.T=r,uf(e,t)}}return!1}function up(e,t,n){t=n9(n,t),t=aM(e.stateNode,t,2),null!==(e=ob(e,t,2))&&(eL(e,2),u_(e))}function um(e,t,n){if(3===e.tag)up(e,e,n);else for(;null!==t;){if(3===t.tag){up(t,e,n);break}if(1===t.tag){var r=t.stateNode;if("function"==typeof t.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===iQ||!iQ.has(r))){e=n9(n,e),null!==(r=ob(t,n=aI(2),2))&&(aU(n,r,t,e),eL(r,2),u_(r));break}}t=t.return}}function uh(e,t,n){var r=e.pingCache;if(null===r){r=e.pingCache=new ix;var l=new Set;r.set(t,l)}else void 0===(l=r.get(t))&&(l=new Set,r.set(t,l));l.has(n)||(iO=!0,l.add(n),e=ug.bind(null,e,t,n),t.then(e,e))}function ug(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,iC===e&&(iP&n)===n&&(4===iA||3===iA&&(0x3c00000&iP)===iP&&300>eu()-iV?0==(2&iE)&&i7(e,0):iM|=n,iU===iP&&(iU=0)),u_(e)}function uy(e,t){0===t&&(t=eN()),null!==(e=n3(e,t))&&(eL(e,t),u_(e))}function uv(e){var t=e.memoizedState,n=0;null!==t&&(n=t.retryLane),uy(e,n)}function ub(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;null!==l&&(n=l.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(s(314))}null!==r&&r.delete(t),uy(e,n)}var uk=null,uw=null,uS=!1,ux=!1,uE=!1,uC=0;function u_(e){var t;e!==uw&&null===e.next&&(null===uw?uk=uw=e:uw=uw.next=e),ux=!0,uS||(uS=!0,t=uz,sl(function(){0!=(6&iE)?el(ec,t):t()}))}function uP(e,t){if(!uE&&ux){uE=!0;do for(var n=!1,r=uk;null!==r;){if(!t){if(0!==e){var l=r.pendingLanes;if(0===l)var a=0;else{var o=r.suspendedLanes,i=r.pingedLanes;a=0xc000055&(a=(1<<31-ek(42|e)+1)-1&(l&~(o&~i)))?0xc000055&a|1:a?2|a:0}0!==a&&(n=!0,uL(r,a))}else a=iP,0==(3&(a=e_(r,r===iC?a:0)))||eP(r,a)||(n=!0,uL(r,a))}r=r.next}while(n);uE=!1}}function uz(){ux=uS=!1;var e,t=0;0!==uC&&(((e=window.event)&&"popstate"===e.type?e===se||(se=e,0):(se=null,1))||(t=uC),uC=0);for(var n=eu(),r=null,l=uk;null!==l;){var a=l.next,o=uN(l,n);0===o?(l.next=null,null===r?uk=a:r.next=a,null===a&&(uw=r)):(r=l,(0!==t||0!=(3&o))&&(ux=!0)),l=a}uP(t,!1)}function uN(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=-0x3c00001&e.pendingLanes;0 title"):null)}function sT(e){return"stylesheet"!==e.type||0!=(3&e.state.loading)}var sL=null;function sO(){}function sR(){if(this.count--,0===this.count){if(this.stylesheets)sF(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var sA=null;function sF(e,t){e.stylesheets=null,null!==e.unsuspend&&(e.count++,sA=new Map,t.forEach(sD,e),sA=null,sR.call(e))}function sD(e,t){if(!(4&t.state.loading)){var n=sA.get(e);if(n)var r=n.get(null);else{n=new Map,sA.set(e,n);for(var l=e.querySelectorAll("link[data-precedence],style[data-precedence]"),a=0;a{var r=n(4232);function l(e){var t="https://react.dev/errors/"+e;if(1{function n(e,t){var n=e.length;for(e.push(t);0>>1,l=e[r];if(0>>1;ra(u,n))sa(c,u)?(e[r]=c,e[s]=n,r=s):(e[r]=u,e[i]=n,r=i);else if(sa(c,n))e[r]=c,e[s]=n,r=s;else break}}return t}function a(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}if(t.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var o,i=performance;t.unstable_now=function(){return i.now()}}else{var u=Date,s=u.now();t.unstable_now=function(){return u.now()-s}}var c=[],f=[],d=1,p=null,m=3,h=!1,g=!1,y=!1,v="function"==typeof setTimeout?setTimeout:null,b="function"==typeof clearTimeout?clearTimeout:null,k="undefined"!=typeof setImmediate?setImmediate:null;function w(e){for(var t=r(f);null!==t;){if(null===t.callback)l(f);else if(t.startTime<=e)l(f),t.sortIndex=t.expirationTime,n(c,t);else break;t=r(f)}}function S(e){if(y=!1,w(e),!g){if(null!==r(c))g=!0,L();else{var t=r(f);null!==t&&O(S,t.startTime-e)}}}var x=!1,E=-1,C=5,_=-1;function P(){return!(t.unstable_now()-_e&&P());){var i=p.callback;if("function"==typeof i){p.callback=null,m=p.priorityLevel;var u=i(p.expirationTime<=e);if(e=t.unstable_now(),"function"==typeof u){p.callback=u,w(e),n=!0;break t}p===r(c)&&l(c),w(e)}else l(c);p=r(c)}if(null!==p)n=!0;else{var s=r(f);null!==s&&O(S,s.startTime-e),n=!1}}break e}finally{p=null,m=a,h=!1}n=void 0}}finally{n?o():x=!1}}}if("function"==typeof k)o=function(){k(z)};else if("undefined"!=typeof MessageChannel){var N=new MessageChannel,T=N.port2;N.port1.onmessage=z,o=function(){T.postMessage(null)}}else o=function(){v(z,0)};function L(){x||(x=!0,o())}function O(e,n){E=v(function(){e(t.unstable_now())},n)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){g||h||(g=!0,L())},t.unstable_forceFrameRate=function(e){0>e||125o?(e.sortIndex=a,n(f,e),null===r(c)&&e===r(f)&&(y?(b(E),E=-1):y=!0,O(S,a-o))):(e.sortIndex=i,n(c,e),g||h||(g=!0,L())),e},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(e){var t=m;return function(){var n=m;m=t;try{return e.apply(this,arguments)}finally{m=n}}}},7876:(e,t,n)=>{e.exports=n(8228)},8228:(e,t)=>{var n=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function l(e,t,r){var l=null;if(void 0!==r&&(l=""+r),void 0!==t.key&&(l=""+t.key),"key"in t)for(var a in r={},t)"key"!==a&&(r[a]=t[a]);else r=t;return{$$typeof:n,type:e,key:l,ref:void 0!==(t=r.ref)?t:null,props:r}}t.Fragment=r,t.jsx=l,t.jsxs=l},8477:(e,t,n)=>{!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=n(4655)},8944:(e,t,n)=>{!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=n(4279)}}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/main-a0aeef4ead6250bb.js b/services/v1/media/feedback/static/_next/static/chunks/main-a0aeef4ead6250bb.js new file mode 100644 index 0000000000000000000000000000000000000000..61f5f6b99a12bd11d962e33e7e7ba8f5e5fb74b5 --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/main-a0aeef4ead6250bb.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[792],{8:(e,t)=>{"use strict";function r(e){return new URL(e,"http://n").searchParams}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"asPathToSearchParams",{enumerable:!0,get:function(){return r}})},36:(e,t)=>{"use strict";function r(){let e=Object.create(null);return{on(t,r){(e[t]||(e[t]=[])).push(r)},off(t,r){e[t]&&e[t].splice(e[t].indexOf(r)>>>0,1)},emit(t){for(var r=arguments.length,n=Array(r>1?r-1:0),o=1;o{e(...n)})}}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r}})},311:(e,t)=>{"use strict";let r;function n(e){var t;return(null==(t=function(){if(void 0===r){var e;r=(null==(e=window.trustedTypes)?void 0:e.createPolicy("nextjs",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}))||null}return r}())?void 0:t.createScriptURL(e))||e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"__unsafeCreateTrustedScriptURL",{enumerable:!0,get:function(){return n}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},451:(e,t)=>{"use strict";function r(e,t){let r={};return Object.keys(e).forEach(n=>{t.includes(n)||(r[n]=e[n])}),r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"omit",{enumerable:!0,get:function(){return r}})},462:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNextRouterError",{enumerable:!0,get:function(){return a}});let n=r(3946),o=r(2526);function a(e){return(0,o.isRedirectError)(e)||(0,n.isHTTPAccessFallbackError)(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},522:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return o},extractInterceptionRouteInformation:function(){return i},isInterceptionRouteAppPath:function(){return a}});let n=r(1980),o=["(..)(..)","(.)","(..)","(...)"];function a(e){return void 0!==e.split("/").find(e=>o.find(t=>e.startsWith(t)))}function i(e){let t,r,a;for(let n of e.split("/"))if(r=o.find(e=>n.startsWith(e))){[t,a]=e.split(r,2);break}if(!t||!r||!a)throw Object.defineProperty(Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`),"__NEXT_ERROR_CODE",{value:"E269",enumerable:!1,configurable:!0});switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":a="/"===t?`/${a}`:t+"/"+a;break;case"(..)":if("/"===t)throw Object.defineProperty(Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`),"__NEXT_ERROR_CODE",{value:"E207",enumerable:!1,configurable:!0});a=t.split("/").slice(0,-1).concat(a).join("/");break;case"(...)":a="/"+a;break;case"(..)(..)":let i=t.split("/");if(i.length<=2)throw Object.defineProperty(Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`),"__NEXT_ERROR_CODE",{value:"E486",enumerable:!1,configurable:!0});a=i.slice(0,-2).concat(a).join("/");break;default:throw Object.defineProperty(Error("Invariant: unexpected marker"),"__NEXT_ERROR_CODE",{value:"E112",enumerable:!1,configurable:!0})}return{interceptingRoute:t,interceptedRoute:a}}},800:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isLocalURL",{enumerable:!0,get:function(){return a}});let n=r(2735),o=r(4026);function a(e){if(!(0,n.isAbsoluteUrl)(e))return!0;try{let t=(0,n.getLocationOrigin)(),r=new URL(e,t);return r.origin===t&&(0,o.hasBasePath)(r.pathname)}catch(e){return!1}}},1071:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{createRouteLoader:function(){return m},getClientBuildManifest:function(){return h},isAssetError:function(){return c},markAssetError:function(){return s}}),r(4252),r(9692);let n=r(311),o=r(6202),a=r(8757),i=r(8409);function u(e,t,r){let n,o=t.get(e);if(o)return"future"in o?o.future:Promise.resolve(o);let a=new Promise(e=>{n=e});return t.set(e,{resolve:n,future:a}),r?r().then(e=>(n(e),e)).catch(r=>{throw t.delete(e),r}):a}let l=Symbol("ASSET_LOAD_ERROR");function s(e){return Object.defineProperty(e,l,{})}function c(e){return e&&l in e}let f=function(e){try{return e=document.createElement("link"),!!window.MSInputMethodContext&&!!document.documentMode||e.relList.supports("prefetch")}catch(e){return!1}}(),d=()=>(0,a.getDeploymentIdQueryOrEmptyString)();function p(e,t,r){return new Promise((n,a)=>{let i=!1;e.then(e=>{i=!0,n(e)}).catch(a),(0,o.requestIdleCallback)(()=>setTimeout(()=>{i||a(r)},t))})}function h(){return self.__BUILD_MANIFEST?Promise.resolve(self.__BUILD_MANIFEST):p(new Promise(e=>{let t=self.__BUILD_MANIFEST_CB;self.__BUILD_MANIFEST_CB=()=>{e(self.__BUILD_MANIFEST),t&&t()}}),3800,s(Object.defineProperty(Error("Failed to load client build manifest"),"__NEXT_ERROR_CODE",{value:"E273",enumerable:!1,configurable:!0})))}function _(e,t){return h().then(r=>{if(!(t in r))throw s(Object.defineProperty(Error("Failed to lookup route: "+t),"__NEXT_ERROR_CODE",{value:"E446",enumerable:!1,configurable:!0}));let o=r[t].map(t=>e+"/_next/"+(0,i.encodeURIPath)(t));return{scripts:o.filter(e=>e.endsWith(".js")).map(e=>(0,n.__unsafeCreateTrustedScriptURL)(e)+d()),css:o.filter(e=>e.endsWith(".css")).map(e=>e+d())}})}function m(e){let t=new Map,r=new Map,n=new Map,a=new Map;function i(e){{var t;let n=r.get(e.toString());return n?n:document.querySelector('script[src^="'+e+'"]')?Promise.resolve():(r.set(e.toString(),n=new Promise((r,n)=>{(t=document.createElement("script")).onload=r,t.onerror=()=>n(s(Object.defineProperty(Error("Failed to load script: "+e),"__NEXT_ERROR_CODE",{value:"E74",enumerable:!1,configurable:!0}))),t.crossOrigin=void 0,t.src=e,document.body.appendChild(t)})),n)}}function l(e){let t=n.get(e);return t||n.set(e,t=fetch(e,{credentials:"same-origin"}).then(t=>{if(!t.ok)throw Object.defineProperty(Error("Failed to load stylesheet: "+e),"__NEXT_ERROR_CODE",{value:"E189",enumerable:!1,configurable:!0});return t.text().then(t=>({href:e,content:t}))}).catch(e=>{throw s(e)})),t}return{whenEntrypoint:e=>u(e,t),onEntrypoint(e,r){(r?Promise.resolve().then(()=>r()).then(e=>({component:e&&e.default||e,exports:e}),e=>({error:e})):Promise.resolve(void 0)).then(r=>{let n=t.get(e);n&&"resolve"in n?r&&(t.set(e,r),n.resolve(r)):(r?t.set(e,r):t.delete(e),a.delete(e))})},loadRoute(r,n){return u(r,a,()=>{let o;return p(_(e,r).then(e=>{let{scripts:n,css:o}=e;return Promise.all([t.has(r)?[]:Promise.all(n.map(i)),Promise.all(o.map(l))])}).then(e=>this.whenEntrypoint(r).then(t=>({entrypoint:t,styles:e[1]}))),3800,s(Object.defineProperty(Error("Route did not complete loading: "+r),"__NEXT_ERROR_CODE",{value:"E12",enumerable:!1,configurable:!0}))).then(e=>{let{entrypoint:t,styles:r}=e,n=Object.assign({styles:r},t);return"error"in t?t:n}).catch(e=>{if(n)throw e;return{error:e}}).finally(()=>null==o?void 0:o())})},prefetch(t){let r;return(r=navigator.connection)&&(r.saveData||/2g/.test(r.effectiveType))?Promise.resolve():_(e,t).then(e=>Promise.all(f?e.scripts.map(e=>{var t,r,n;return t=e.toString(),r="script",new Promise((e,o)=>{let a='\n link[rel="prefetch"][href^="'+t+'"],\n link[rel="preload"][href^="'+t+'"],\n script[src^="'+t+'"]';if(document.querySelector(a))return e();n=document.createElement("link"),r&&(n.as=r),n.rel="prefetch",n.crossOrigin=void 0,n.onload=e,n.onerror=()=>o(s(Object.defineProperty(Error("Failed to prefetch: "+t),"__NEXT_ERROR_CODE",{value:"E268",enumerable:!1,configurable:!0}))),n.href=t,document.head.appendChild(n)})}):[])).then(()=>{(0,o.requestIdleCallback)(()=>this.loadRoute(t,!0).catch(()=>{}))}).catch(()=>{})}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1113:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(7327);let n=r(2456);window.next={version:n.version,get router(){return n.router},emitter:n.emitter},(0,n.initialize)({}).then(()=>(0,n.hydrate)()).catch(console.error),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1226:()=>{},1286:(e,t)=>{"use strict";function r(e,t){let r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let n=r.length;n--;){let o=r[n];if("query"===o){let r=Object.keys(e.query);if(r.length!==Object.keys(t.query).length)return!1;for(let n=r.length;n--;){let o=r[n];if(!t.query.hasOwnProperty(o)||e.query[o]!==t.query[o])return!1}}else if(!t.hasOwnProperty(o)||e[o]!==t[o])return!1}return!0}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"compareRouterStates",{enumerable:!0,get:function(){return r}})},1291:()=>{"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var e=/\((.*)\)/.exec(this.toString());return e?e[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(e,t){return t=this.concat.apply([],this),e>1&&t.some(Array.isArray)?t.flat(e-1):t},Array.prototype.flatMap=function(e,t){return this.map(e,t).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(e){if("function"!=typeof e)return this.then(e,e);var t=this.constructor||Promise;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})}),Object.fromEntries||(Object.fromEntries=function(e){return Array.from(e).reduce(function(e,t){return e[t[0]]=t[1],e},{})}),Array.prototype.at||(Array.prototype.at=function(e){var t=Math.trunc(e)||0;if(t<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]}),Object.hasOwn||(Object.hasOwn=function(e,t){if(null==e)throw TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(e),t)}),"canParse"in URL||(URL.canParse=function(e,t){try{return new URL(e,t),!0}catch(e){return!1}})},1851:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HTML_LIMITED_BOT_UA_RE",{enumerable:!0,get:function(){return r}});let r=/Mediapartners-Google|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview/i},1874:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getNextPathnameInfo",{enumerable:!0,get:function(){return i}});let n=r(1973),o=r(7369),a=r(7411);function i(e,t){var r,i;let{basePath:u,i18n:l,trailingSlash:s}=null!=(r=t.nextConfig)?r:{},c={pathname:e,trailingSlash:"/"!==e?e.endsWith("/"):s};u&&(0,a.pathHasPrefix)(c.pathname,u)&&(c.pathname=(0,o.removePathPrefix)(c.pathname,u),c.basePath=u);let f=c.pathname;if(c.pathname.startsWith("/_next/data/")&&c.pathname.endsWith(".json")){let e=c.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/"),r=e[0];c.buildId=r,f="index"!==e[1]?"/"+e.slice(1).join("/"):"/",!0===t.parseData&&(c.pathname=f)}if(l){let e=t.i18nProvider?t.i18nProvider.analyze(c.pathname):(0,n.normalizeLocalePath)(c.pathname,l.locales);c.locale=e.detectedLocale,c.pathname=null!=(i=e.pathname)?i:c.pathname,!e.detectedLocale&&c.buildId&&(e=t.i18nProvider?t.i18nProvider.analyze(f):(0,n.normalizeLocalePath)(f,l.locales)).detectedLocale&&(c.locale=e.detectedLocale)}return c}},1973:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return n}});let r=new WeakMap;function n(e,t){let n;if(!t)return{pathname:e};let o=r.get(t);o||(o=t.map(e=>e.toLowerCase()),r.set(t,o));let a=e.split("/",2);if(!a[1])return{pathname:e};let i=a[1].toLowerCase(),u=o.indexOf(i);return u<0?{pathname:e}:(n=t[u],{pathname:e=e.slice(n.length+1)||"/",detectedLocale:n})}},1980:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return a},normalizeRscURL:function(){return i}});let n=r(6545),o=r(7835);function a(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,o.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function i(e){return e.replace(/\.rsc($|\?)/,"$1")}},2080:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{VALID_LOADERS:function(){return r},imageConfigDefault:function(){return n}});let r=["default","imgix","cloudinary","akamai","custom"],n={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"attachment",localPatterns:void 0,remotePatterns:[],qualities:void 0,unoptimized:!1}},2119:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"detectDomainLocale",{enumerable:!0,get:function(){return r}});let r=function(){for(var e=arguments.length,t=Array(e),r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reportGlobalError",{enumerable:!0,get:function(){return r}});let r="function"==typeof reportError?reportError:e=>{globalThis.console.error(e)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2326:(e,t)=>{"use strict";function r(e){return"/api"===e||!!(null==e?void 0:e.startsWith("/api/"))}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isAPIRoute",{enumerable:!0,get:function(){return r}})},2456:(e,t,r)=>{"use strict";let n,o,a,i,u,l,s,c,f,d,p,h;Object.defineProperty(t,"__esModule",{value:!0});let _=r(8365);Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{emitter:function(){return X},hydrate:function(){return el},initialize:function(){return V},router:function(){return n},version:function(){return H}});let m=r(4252),g=r(7876);r(1291);let b=m._(r(4232)),E=m._(r(8944)),y=r(2458),P=m._(r(36)),R=r(4769),v=r(7537),O=r(7426),S=r(2587),j=r(3284),T=r(2735),A=r(9909),C=m._(r(8188)),w=m._(r(8233)),I=r(7667),N=r(5045),x=r(6240),M=r(7168),L=r(4902),D=r(4026),U=r(3043),k=r(4652),F=r(9042),B=r(5174);r(5262),r(462);let H="15.2.0",X=(0,P.default)(),W=e=>[].slice.call(e),G=!1;class q extends b.default.Component{componentDidCatch(e,t){this.props.fn(e,t)}componentDidMount(){this.scrollToHash(),n.isSsr&&(o.isFallback||o.nextExport&&((0,O.isDynamicRoute)(n.pathname)||location.search||G)||o.props&&o.props.__N_SSG&&(location.search||G))&&n.replace(n.pathname+"?"+String((0,S.assign)((0,S.urlQueryToSearchParams)(n.query),new URLSearchParams(location.search))),a,{_h:1,shallow:!o.isFallback&&!G}).catch(e=>{if(!e.cancelled)throw e})}componentDidUpdate(){this.scrollToHash()}scrollToHash(){let{hash:e}=location;if(!(e=e&&e.substring(1)))return;let t=document.getElementById(e);t&&setTimeout(()=>t.scrollIntoView(),0)}render(){return this.props.children}}async function V(e){void 0===e&&(e={}),o=JSON.parse(document.getElementById("__NEXT_DATA__").textContent),window.__NEXT_DATA__=o,h=o.defaultLocale;let t=o.assetPrefix||"";if(self.__next_set_public_path__(""+t+"/_next/"),(0,j.setConfig)({serverRuntimeConfig:{},publicRuntimeConfig:o.runtimeConfig||{}}),a=(0,T.getURL)(),(0,D.hasBasePath)(a)&&(a=(0,L.removeBasePath)(a)),o.scriptLoader){let{initScriptLoader:e}=r(6179);e(o.scriptLoader)}i=new w.default(o.buildId,t);let s=e=>{let[t,r]=e;return i.routeLoader.onEntrypoint(t,r)};return window.__NEXT_P&&window.__NEXT_P.map(e=>setTimeout(()=>s(e),0)),window.__NEXT_P=[],window.__NEXT_P.push=s,(l=(0,C.default)()).getIsSsr=()=>n.isSsr,u=document.getElementById("__next"),{assetPrefix:t}}function z(e,t){return(0,g.jsx)(e,{...t})}function Y(e){var t;let{children:r}=e,o=b.default.useMemo(()=>(0,k.adaptForAppRouterInstance)(n),[]);return(0,g.jsx)(q,{fn:e=>$({App:f,err:e}).catch(e=>console.error("Error rendering page: ",e)),children:(0,g.jsx)(U.AppRouterContext.Provider,{value:o,children:(0,g.jsx)(F.SearchParamsContext.Provider,{value:(0,k.adaptForSearchParams)(n),children:(0,g.jsx)(k.PathnameContextProviderAdapter,{router:n,isAutoExport:null!=(t=self.__NEXT_DATA__.autoExport)&&t,children:(0,g.jsx)(F.PathParamsContext.Provider,{value:(0,k.adaptForPathParams)(n),children:(0,g.jsx)(R.RouterContext.Provider,{value:(0,N.makePublicRouterInstance)(n),children:(0,g.jsx)(y.HeadManagerContext.Provider,{value:l,children:(0,g.jsx)(M.ImageConfigContext.Provider,{value:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1},children:r})})})})})})})})}let K=e=>t=>{let r={...t,Component:p,err:o.err,router:n};return(0,g.jsx)(Y,{children:z(e,r)})};function $(e){let{App:t,err:u}=e;return console.error(u),console.error("A client-side exception has occurred, see here for more info: https://nextjs.org/docs/messages/client-side-exception-occurred"),i.loadPage("/_error").then(n=>{let{page:o,styleSheets:a}=n;return(null==s?void 0:s.Component)===o?Promise.resolve().then(()=>_._(r(9468))).then(n=>Promise.resolve().then(()=>_._(r(9761))).then(r=>(t=r.default,e.App=t,n))).then(e=>({ErrorComponent:e.default,styleSheets:[]})):{ErrorComponent:o,styleSheets:a}}).then(r=>{var i;let{ErrorComponent:l,styleSheets:s}=r,c=K(t),f={Component:l,AppTree:c,router:n,ctx:{err:u,pathname:o.page,query:o.query,asPath:a,AppTree:c}};return Promise.resolve((null==(i=e.props)?void 0:i.err)?e.props:(0,T.loadGetInitialProps)(t,f)).then(t=>ei({...e,err:u,Component:l,styleSheets:s,props:t}))})}function Q(e){let{callback:t}=e;return b.default.useLayoutEffect(()=>t(),[t]),null}let J={navigationStart:"navigationStart",beforeRender:"beforeRender",afterRender:"afterRender",afterHydrate:"afterHydrate",routeChange:"routeChange"},Z={hydration:"Next.js-hydration",beforeHydration:"Next.js-before-hydration",routeChangeToRender:"Next.js-route-change-to-render",render:"Next.js-render"},ee=null,et=!0;function er(){[J.beforeRender,J.afterHydrate,J.afterRender,J.routeChange].forEach(e=>performance.clearMarks(e))}function en(){T.ST&&(performance.mark(J.afterHydrate),performance.getEntriesByName(J.beforeRender,"mark").length&&(performance.measure(Z.beforeHydration,J.navigationStart,J.beforeRender),performance.measure(Z.hydration,J.beforeRender,J.afterHydrate)),d&&performance.getEntriesByName(Z.hydration).forEach(d),er())}function eo(){if(!T.ST)return;performance.mark(J.afterRender);let e=performance.getEntriesByName(J.routeChange,"mark");e.length&&(performance.getEntriesByName(J.beforeRender,"mark").length&&(performance.measure(Z.routeChangeToRender,e[0].name,J.beforeRender),performance.measure(Z.render,J.beforeRender,J.afterRender),d&&(performance.getEntriesByName(Z.render).forEach(d),performance.getEntriesByName(Z.routeChangeToRender).forEach(d))),er(),[Z.routeChangeToRender,Z.render].forEach(e=>performance.clearMeasures(e)))}function ea(e){let{callbacks:t,children:r}=e;return b.default.useLayoutEffect(()=>t.forEach(e=>e()),[t]),r}function ei(e){let t,{App:r,Component:o,props:a,err:i}=e,l="initial"in e?void 0:e.styleSheets;o=o||s.Component;let f={...a=a||s.props,Component:o,err:i,router:n};s=f;let d=!1,p=new Promise((e,r)=>{c&&c(),t=()=>{c=null,e()},c=()=>{d=!0,c=null;let e=Object.defineProperty(Error("Cancel rendering route"),"__NEXT_ERROR_CODE",{value:"E503",enumerable:!1,configurable:!0});e.cancelled=!0,r(e)}});function h(){t()}!function(){if(!l)return;let e=new Set(W(document.querySelectorAll("style[data-n-href]")).map(e=>e.getAttribute("data-n-href"))),t=document.querySelector("noscript[data-n-css]"),r=null==t?void 0:t.getAttribute("data-n-css");l.forEach(t=>{let{href:n,text:o}=t;if(!e.has(n)){let e=document.createElement("style");e.setAttribute("data-n-href",n),e.setAttribute("media","x"),r&&e.setAttribute("nonce",r),document.head.appendChild(e),e.appendChild(document.createTextNode(o))}})}();let _=(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(Q,{callback:function(){if(l&&!d){let e=new Set(l.map(e=>e.href)),t=W(document.querySelectorAll("style[data-n-href]")),r=t.map(e=>e.getAttribute("data-n-href"));for(let n=0;n{let{href:t}=e,r=document.querySelector('style[data-n-href="'+t+'"]');r&&(n.parentNode.insertBefore(r,n.nextSibling),n=r)}),W(document.querySelectorAll("link[data-n-p]")).forEach(e=>{e.parentNode.removeChild(e)})}if(e.scroll){let{x:t,y:r}=e.scroll;(0,v.handleSmoothScroll)(()=>{window.scrollTo(t,r)})}}}),(0,g.jsxs)(Y,{children:[z(r,f),(0,g.jsx)(A.Portal,{type:"next-route-announcer",children:(0,g.jsx)(I.RouteAnnouncer,{})})]})]});return!function(e,t){T.ST&&performance.mark(J.beforeRender);let r=t(et?en:eo);ee?(0,b.default.startTransition)(()=>{ee.render(r)}):(ee=E.default.hydrateRoot(e,r,{onRecoverableError:B.onRecoverableError}),et=!1)}(u,e=>(0,g.jsx)(ea,{callbacks:[e,h],children:_})),p}async function eu(e){if(e.err&&(void 0===e.Component||!e.isHydratePass)){await $(e);return}try{await ei(e)}catch(r){let t=(0,x.getProperError)(r);if(t.cancelled)throw t;await $({...e,err:t})}}async function el(e){let t=o.err;try{let e=await i.routeLoader.whenEntrypoint("/_app");if("error"in e)throw e.error;let{component:t,exports:r}=e;f=t,r&&r.reportWebVitals&&(d=e=>{let t,{id:n,name:o,startTime:a,value:i,duration:u,entryType:l,entries:s,attribution:c}=e,f=Date.now()+"-"+(Math.floor(Math.random()*(9e12-1))+1e12);s&&s.length&&(t=s[0].startTime);let d={id:n||f,name:o,startTime:a||t,value:null==i?u:i,label:"mark"===l||"measure"===l?"custom":"web-vital"};c&&(d.attribution=c),r.reportWebVitals(d)});let n=await i.routeLoader.whenEntrypoint(o.page);if("error"in n)throw n.error;p=n.component}catch(e){t=(0,x.getProperError)(e)}window.__NEXT_PRELOADREADY&&await window.__NEXT_PRELOADREADY(o.dynamicIds),n=(0,N.createRouter)(o.page,o.query,a,{initialProps:o.props,pageLoader:i,App:f,Component:p,wrapApp:K,err:t,isFallback:!!o.isFallback,subscription:(e,t,r)=>eu(Object.assign({},e,{App:t,scroll:r})),locale:o.locale,locales:o.locales,defaultLocale:h,domainLocales:o.domainLocales,isPreview:o.isPreview}),G=await n._initialMatchesMiddlewarePromise;let r={App:f,initial:!0,Component:p,props:o.props,err:t,isHydratePass:!0};(null==e?void 0:e.beforeRender)&&await e.beforeRender(),eu(r)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2458:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HeadManagerContext",{enumerable:!0,get:function(){return n}});let n=r(4252)._(r(4232)).default.createContext({})},2526:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{REDIRECT_ERROR_CODE:function(){return o},RedirectType:function(){return a},isRedirectError:function(){return i}});let n=r(3604),o="NEXT_REDIRECT";var a=function(e){return e.push="push",e.replace="replace",e}({});function i(e){if("object"!=typeof e||null===e||!("digest"in e)||"string"!=typeof e.digest)return!1;let t=e.digest.split(";"),[r,a]=t,i=t.slice(2,-2).join(";"),u=Number(t.at(-2));return r===o&&("replace"===a||"push"===a)&&"string"==typeof i&&!isNaN(u)&&u in n.RedirectStatusCode}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2587:(e,t)=>{"use strict";function r(e){let t={};for(let[r,n]of e.entries()){let e=t[r];void 0===e?t[r]=n:Array.isArray(e)?e.push(n):t[r]=[e,n]}return t}function n(e){return"string"==typeof e?e:("number"!=typeof e||isNaN(e))&&"boolean"!=typeof e?"":String(e)}function o(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(Array.isArray(o))for(let e of o)t.append(r,n(e));else t.set(r,n(o));return t}function a(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"interpolateAs",{enumerable:!0,get:function(){return a}});let n=r(6288),o=r(4645);function a(e,t,r){let a="",i=(0,o.getRouteRegex)(e),u=i.groups,l=(t!==e?(0,n.getRouteMatcher)(i)(t):"")||r;a=e;let s=Object.keys(u);return s.every(e=>{let t=l[e]||"",{repeat:r,optional:n}=u[e],o="["+(r?"...":"")+e+"]";return n&&(o=(t?"":"/")+"["+o+"]"),r&&!Array.isArray(t)&&(t=[t]),(n||e in l)&&(a=a.replace(o,r?t.map(e=>encodeURIComponent(e)).join("/"):encodeURIComponent(t))||"/")})||(a=""),{params:s,result:a}}},2735:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DecodeError:function(){return h},MiddlewareNotFoundError:function(){return b},MissingStaticPage:function(){return g},NormalizeError:function(){return _},PageNotFoundError:function(){return m},SP:function(){return d},ST:function(){return p},WEB_VITALS:function(){return r},execOnce:function(){return n},getDisplayName:function(){return l},getLocationOrigin:function(){return i},getURL:function(){return u},isAbsoluteUrl:function(){return a},isResSent:function(){return s},loadGetInitialProps:function(){return f},normalizeRepeatedSlashes:function(){return c},stringifyError:function(){return E}});let r=["CLS","FCP","FID","INP","LCP","TTFB"];function n(e){let t,r=!1;return function(){for(var n=arguments.length,o=Array(n),a=0;ao.test(e);function i(){let{protocol:e,hostname:t,port:r}=window.location;return e+"//"+t+(r?":"+r:"")}function u(){let{href:e}=window.location,t=i();return e.substring(t.length)}function l(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function s(e){return e.finished||e.headersSent}function c(e){let t=e.split("?");return t[0].replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function f(e,t){let r=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await f(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(r&&s(r))return n;if(!n)throw Object.defineProperty(Error('"'+l(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.'),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return n}let d="undefined"!=typeof performance,p=d&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);class h extends Error{}class _ extends Error{}class m extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}}class g extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}}class b extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}}function E(e){return JSON.stringify({message:e.message,stack:e.stack})}},2982:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return o}});let n=r(8963);function o(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:a}=(0,n.parsePath)(e);return""+t+r+o+a}},3043:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{AppRouterContext:function(){return o},GlobalLayoutRouterContext:function(){return i},LayoutRouterContext:function(){return a},MissingSlotContext:function(){return l},TemplateContext:function(){return u}});let n=r(4252)._(r(4232)),o=n.default.createContext(null),a=n.default.createContext(null),i=n.default.createContext(null),u=n.default.createContext(null),l=n.default.createContext(new Set)},3264:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseRelativeUrl",{enumerable:!0,get:function(){return a}});let n=r(2735),o=r(2587);function a(e,t,r){void 0===r&&(r=!0);let a=new URL((0,n.getLocationOrigin)()),i=t?new URL(t,a):e.startsWith(".")?new URL(window.location.href):a,{pathname:u,searchParams:l,search:s,hash:c,href:f,origin:d}=new URL(e,i);if(d!==a.origin)throw Object.defineProperty(Error("invariant: invalid relative URL, router received "+e),"__NEXT_ERROR_CODE",{value:"E159",enumerable:!1,configurable:!0});return{pathname:u,query:r?(0,o.searchParamsToUrlQuery)(l):void 0,search:s,hash:c,href:f.slice(d.length)}}},3283:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathSuffix",{enumerable:!0,get:function(){return o}});let n=r(8963);function o(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:a}=(0,n.parsePath)(e);return""+r+t+o+a}},3284:(e,t)=>{"use strict";let r;Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return n},setConfig:function(){return o}});let n=()=>r;function o(e){r=e}},3604:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RedirectStatusCode",{enumerable:!0,get:function(){return r}});var r=function(e){return e[e.SeeOther=303]="SeeOther",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e}({});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3748:(e,t,r)=>{"use strict";var n=r(9742);Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return m},defaultHead:function(){return d}});let o=r(4252),a=r(8365),i=r(7876),u=a._(r(4232)),l=o._(r(4361)),s=r(8880),c=r(2458),f=r(6392);function d(e){void 0===e&&(e=!1);let t=[(0,i.jsx)("meta",{charSet:"utf-8"},"charset")];return e||t.push((0,i.jsx)("meta",{name:"viewport",content:"width=device-width"},"viewport")),t}function p(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===u.default.Fragment?e.concat(u.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}r(9482);let h=["name","httpEquiv","charSet","itemProp"];function _(e,t){let{inAmpMode:r}=t;return e.reduce(p,[]).reverse().concat(d(r).reverse()).filter(function(){let e=new Set,t=new Set,r=new Set,n={};return o=>{let a=!0,i=!1;if(o.key&&"number"!=typeof o.key&&o.key.indexOf("$")>0){i=!0;let t=o.key.slice(o.key.indexOf("$")+1);e.has(t)?a=!1:e.add(t)}switch(o.type){case"title":case"base":t.has(o.type)?a=!1:t.add(o.type);break;case"meta":for(let e=0,t=h.length;e{let o=e.key||t;if(n.env.__NEXT_OPTIMIZE_FONTS&&!r&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,u.default.cloneElement(e,t)}return u.default.cloneElement(e,{key:o})})}let m=function(e){let{children:t}=e,r=(0,u.useContext)(s.AmpStateContext),n=(0,u.useContext)(c.HeadManagerContext);return(0,i.jsx)(l.default,{reduceComponentsToState:_,headManager:n,inAmpMode:(0,f.isInAmpMode)(r),children:t})};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3897:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"escapeStringRegexp",{enumerable:!0,get:function(){return o}});let r=/[|\\{}()[\]^$+*?.-]/,n=/[|\\{}()[\]^$+*?.-]/g;function o(e){return r.test(e)?e.replace(n,"\\$&"):e}},3946:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{HTTPAccessErrorStatus:function(){return r},HTTP_ERROR_FALLBACK_ERROR_CODE:function(){return o},getAccessFallbackErrorTypeByStatus:function(){return u},getAccessFallbackHTTPStatus:function(){return i},isHTTPAccessFallbackError:function(){return a}});let r={NOT_FOUND:404,FORBIDDEN:403,UNAUTHORIZED:401},n=new Set(Object.values(r)),o="NEXT_HTTP_ERROR_FALLBACK";function a(e){if("object"!=typeof e||null===e||!("digest"in e)||"string"!=typeof e.digest)return!1;let[t,r]=e.digest.split(";");return t===o&&n.has(Number(r))}function i(e){return Number(e.digest.split(";")[1])}function u(e){switch(e){case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";default:return}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4015:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"formatNextPathnameInfo",{enumerable:!0,get:function(){return u}});let n=r(7125),o=r(2982),a=r(3283),i=r(8906);function u(e){let t=(0,i.addLocale)(e.pathname,e.locale,e.buildId?void 0:e.defaultLocale,e.ignorePrefix);return(e.buildId||!e.trailingSlash)&&(t=(0,n.removeTrailingSlash)(t)),e.buildId&&(t=(0,a.addPathSuffix)((0,o.addPathPrefix)(t,"/_next/data/"+e.buildId),"/"===e.pathname?"index.json":".json")),t=(0,o.addPathPrefix)(t,e.basePath),!e.buildId&&e.trailingSlash?t.endsWith("/")?t:(0,a.addPathSuffix)(t,"/"):(0,n.removeTrailingSlash)(t)}},4026:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return o}});let n=r(7411);function o(e){return(0,n.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4252:(e,t,r)=>{"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:()=>n})},4304:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getSortedRouteObjects:function(){return o},getSortedRoutes:function(){return n}});class r{insert(e){this._insert(e.split("/").filter(Boolean),[],!1)}smoosh(){return this._smoosh()}_smoosh(e){void 0===e&&(e="/");let t=[...this.children.keys()].sort();null!==this.slugName&&t.splice(t.indexOf("[]"),1),null!==this.restSlugName&&t.splice(t.indexOf("[...]"),1),null!==this.optionalRestSlugName&&t.splice(t.indexOf("[[...]]"),1);let r=t.map(t=>this.children.get(t)._smoosh(""+e+t+"/")).reduce((e,t)=>[...e,...t],[]);if(null!==this.slugName&&r.push(...this.children.get("[]")._smoosh(e+"["+this.slugName+"]/")),!this.placeholder){let t="/"===e?"/":e.slice(0,-1);if(null!=this.optionalRestSlugName)throw Object.defineProperty(Error('You cannot define a route with the same specificity as a optional catch-all route ("'+t+'" and "'+t+"[[..."+this.optionalRestSlugName+']]").'),"__NEXT_ERROR_CODE",{value:"E458",enumerable:!1,configurable:!0});r.unshift(t)}return null!==this.restSlugName&&r.push(...this.children.get("[...]")._smoosh(e+"[..."+this.restSlugName+"]/")),null!==this.optionalRestSlugName&&r.push(...this.children.get("[[...]]")._smoosh(e+"[[..."+this.optionalRestSlugName+"]]/")),r}_insert(e,t,n){if(0===e.length){this.placeholder=!1;return}if(n)throw Object.defineProperty(Error("Catch-all must be the last part of the URL."),"__NEXT_ERROR_CODE",{value:"E392",enumerable:!1,configurable:!0});let o=e[0];if(o.startsWith("[")&&o.endsWith("]")){let r=o.slice(1,-1),i=!1;if(r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1),i=!0),r.startsWith("…"))throw Object.defineProperty(Error("Detected a three-dot character ('…') at ('"+r+"'). Did you mean ('...')?"),"__NEXT_ERROR_CODE",{value:"E147",enumerable:!1,configurable:!0});if(r.startsWith("...")&&(r=r.substring(3),n=!0),r.startsWith("[")||r.endsWith("]"))throw Object.defineProperty(Error("Segment names may not start or end with extra brackets ('"+r+"')."),"__NEXT_ERROR_CODE",{value:"E421",enumerable:!1,configurable:!0});if(r.startsWith("."))throw Object.defineProperty(Error("Segment names may not start with erroneous periods ('"+r+"')."),"__NEXT_ERROR_CODE",{value:"E288",enumerable:!1,configurable:!0});function a(e,r){if(null!==e&&e!==r)throw Object.defineProperty(Error("You cannot use different slug names for the same dynamic path ('"+e+"' !== '"+r+"')."),"__NEXT_ERROR_CODE",{value:"E337",enumerable:!1,configurable:!0});t.forEach(e=>{if(e===r)throw Object.defineProperty(Error('You cannot have the same slug name "'+r+'" repeat within a single dynamic path'),"__NEXT_ERROR_CODE",{value:"E247",enumerable:!1,configurable:!0});if(e.replace(/\W/g,"")===o.replace(/\W/g,""))throw Object.defineProperty(Error('You cannot have the slug names "'+e+'" and "'+r+'" differ only by non-word symbols within a single dynamic path'),"__NEXT_ERROR_CODE",{value:"E499",enumerable:!1,configurable:!0})}),t.push(r)}if(n){if(i){if(null!=this.restSlugName)throw Object.defineProperty(Error('You cannot use both an required and optional catch-all route at the same level ("[...'+this.restSlugName+']" and "'+e[0]+'" ).'),"__NEXT_ERROR_CODE",{value:"E299",enumerable:!1,configurable:!0});a(this.optionalRestSlugName,r),this.optionalRestSlugName=r,o="[[...]]"}else{if(null!=this.optionalRestSlugName)throw Object.defineProperty(Error('You cannot use both an optional and required catch-all route at the same level ("[[...'+this.optionalRestSlugName+']]" and "'+e[0]+'").'),"__NEXT_ERROR_CODE",{value:"E300",enumerable:!1,configurable:!0});a(this.restSlugName,r),this.restSlugName=r,o="[...]"}}else{if(i)throw Object.defineProperty(Error('Optional route parameters are not yet supported ("'+e[0]+'").'),"__NEXT_ERROR_CODE",{value:"E435",enumerable:!1,configurable:!0});a(this.slugName,r),this.slugName=r,o="[]"}}this.children.has(o)||this.children.set(o,new r),this.children.get(o)._insert(e.slice(1),t,n)}constructor(){this.placeholder=!0,this.children=new Map,this.slugName=null,this.restSlugName=null,this.optionalRestSlugName=null}}function n(e){let t=new r;return e.forEach(e=>t.insert(e)),t.smoosh()}function o(e,t){let r={},o=[];for(let n=0;ne[r[t]])}},4361:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return i}});let n=r(4232),o=n.useLayoutEffect,a=n.useEffect;function i(e){let{headManager:t,reduceComponentsToState:r}=e;function i(){if(t&&t.mountedInstances){let o=n.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(r(o,e))}}return o(()=>{var r;return null==t||null==(r=t.mountedInstances)||r.add(e.children),()=>{var r;null==t||null==(r=t.mountedInstances)||r.delete(e.children)}}),o(()=>(t&&(t._pendingUpdate=i),()=>{t&&(t._pendingUpdate=i)})),a(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},4645:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getNamedMiddlewareRegex:function(){return _},getNamedRouteRegex:function(){return h},getRouteRegex:function(){return f},parseParameter:function(){return l}});let n=r(9308),o=r(522),a=r(3897),i=r(7125),u=/^([^[]*)\[((?:\[[^\]]*\])|[^\]]+)\](.*)$/;function l(e){let t=e.match(u);return t?s(t[2]):s(e)}function s(e){let t=e.startsWith("[")&&e.endsWith("]");t&&(e=e.slice(1,-1));let r=e.startsWith("...");return r&&(e=e.slice(3)),{key:e,repeat:r,optional:t}}function c(e,t,r){let n={},l=1,c=[];for(let f of(0,i.removeTrailingSlash)(e).slice(1).split("/")){let e=o.INTERCEPTION_ROUTE_MARKERS.find(e=>f.startsWith(e)),i=f.match(u);if(e&&i&&i[2]){let{key:t,optional:r,repeat:o}=s(i[2]);n[t]={pos:l++,repeat:o,optional:r},c.push("/"+(0,a.escapeStringRegexp)(e)+"([^/]+?)")}else if(i&&i[2]){let{key:e,repeat:t,optional:o}=s(i[2]);n[e]={pos:l++,repeat:t,optional:o},r&&i[1]&&c.push("/"+(0,a.escapeStringRegexp)(i[1]));let u=t?o?"(?:/(.+?))?":"/(.+?)":"/([^/]+?)";r&&i[1]&&(u=u.substring(1)),c.push(u)}else c.push("/"+(0,a.escapeStringRegexp)(f));t&&i&&i[3]&&c.push((0,a.escapeStringRegexp)(i[3]))}return{parameterizedRoute:c.join(""),groups:n}}function f(e,t){let{includeSuffix:r=!1,includePrefix:n=!1,excludeOptionalTrailingSlash:o=!1}=void 0===t?{}:t,{parameterizedRoute:a,groups:i}=c(e,r,n),u=a;return o||(u+="(?:/)?"),{re:RegExp("^"+u+"$"),groups:i}}function d(e){let t,{interceptionMarker:r,getSafeRouteKey:n,segment:o,routeKeys:i,keyPrefix:u,backreferenceDuplicateKeys:l}=e,{key:c,optional:f,repeat:d}=s(o),p=c.replace(/\W/g,"");u&&(p=""+u+p);let h=!1;(0===p.length||p.length>30)&&(h=!0),isNaN(parseInt(p.slice(0,1)))||(h=!0),h&&(p=n());let _=p in i;u?i[p]=""+u+c:i[p]=c;let m=r?(0,a.escapeStringRegexp)(r):"";return t=_&&l?"\\k<"+p+">":d?"(?<"+p+">.+?)":"(?<"+p+">[^/]+?)",f?"(?:/"+m+t+")?":"/"+m+t}function p(e,t,r,l,s){let c;let f=(c=0,()=>{let e="",t=++c;for(;t>0;)e+=String.fromCharCode(97+(t-1)%26),t=Math.floor((t-1)/26);return e}),p={},h=[];for(let c of(0,i.removeTrailingSlash)(e).slice(1).split("/")){let e=o.INTERCEPTION_ROUTE_MARKERS.some(e=>c.startsWith(e)),i=c.match(u);if(e&&i&&i[2])h.push(d({getSafeRouteKey:f,interceptionMarker:i[1],segment:i[2],routeKeys:p,keyPrefix:t?n.NEXT_INTERCEPTION_MARKER_PREFIX:void 0,backreferenceDuplicateKeys:s}));else if(i&&i[2]){l&&i[1]&&h.push("/"+(0,a.escapeStringRegexp)(i[1]));let e=d({getSafeRouteKey:f,segment:i[2],routeKeys:p,keyPrefix:t?n.NEXT_QUERY_PARAM_PREFIX:void 0,backreferenceDuplicateKeys:s});l&&i[1]&&(e=e.substring(1)),h.push(e)}else h.push("/"+(0,a.escapeStringRegexp)(c));r&&i&&i[3]&&h.push((0,a.escapeStringRegexp)(i[3]))}return{namedParameterizedRoute:h.join(""),routeKeys:p}}function h(e,t){var r,n,o;let a=p(e,t.prefixRouteKeys,null!=(r=t.includeSuffix)&&r,null!=(n=t.includePrefix)&&n,null!=(o=t.backreferenceDuplicateKeys)&&o),i=a.namedParameterizedRoute;return t.excludeOptionalTrailingSlash||(i+="(?:/)?"),{...f(e,t),namedRegex:"^"+i+"$",routeKeys:a.routeKeys}}function _(e,t){let{parameterizedRoute:r}=c(e,!1,!1),{catchAll:n=!0}=t;if("/"===r)return{namedRegex:"^/"+(n?".*":"")+"$"};let{namedParameterizedRoute:o}=p(e,!1,!1,!1,!1);return{namedRegex:"^"+o+(n?"(?:(/.*)?)":"")+"$"}}},4652:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PathnameContextProviderAdapter:function(){return p},adaptForAppRouterInstance:function(){return c},adaptForPathParams:function(){return d},adaptForSearchParams:function(){return f}});let n=r(8365),o=r(7876),a=n._(r(4232)),i=r(9042),u=r(8266),l=r(8),s=r(4645);function c(e){return{back(){e.back()},forward(){e.forward()},refresh(){e.reload()},hmrRefresh(){},push(t,r){let{scroll:n}=void 0===r?{}:r;e.push(t,void 0,{scroll:n})},replace(t,r){let{scroll:n}=void 0===r?{}:r;e.replace(t,void 0,{scroll:n})},prefetch(t){e.prefetch(t)}}}function f(e){return e.isReady&&e.query?(0,l.asPathToSearchParams)(e.asPath):new URLSearchParams}function d(e){if(!e.isReady||!e.query)return null;let t={};for(let r of Object.keys((0,s.getRouteRegex)(e.pathname).groups))t[r]=e.query[r];return t}function p(e){let{children:t,router:r,...n}=e,l=(0,a.useRef)(n.isAutoExport),s=(0,a.useMemo)(()=>{let e;let t=l.current;if(t&&(l.current=!1),(0,u.isDynamicRoute)(r.pathname)&&(r.isFallback||t&&!r.isReady))return null;try{e=new URL(r.asPath,"http://f")}catch(e){return"/"}return e.pathname},[r.asPath,r.isFallback,r.isReady,r.pathname]);return(0,o.jsx)(i.PathnameContext.Provider,{value:s,children:t})}},4769:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RouterContext",{enumerable:!0,get:function(){return n}});let n=r(4252)._(r(4232)).default.createContext(null)},4902:(e,t,r)=>{"use strict";function n(e){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return n}}),r(4026),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5045:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{Router:function(){return a.default},createRouter:function(){return _},default:function(){return p},makePublicRouterInstance:function(){return m},useRouter:function(){return h},withRouter:function(){return l.default}});let n=r(4252),o=n._(r(4232)),a=n._(r(6249)),i=r(4769),u=n._(r(6240)),l=n._(r(9218)),s={router:null,readyCallbacks:[],ready(e){if(this.router)return e();this.readyCallbacks.push(e)}},c=["pathname","route","query","asPath","components","isFallback","basePath","locale","locales","defaultLocale","isReady","isPreview","isLocaleDomain","domainLocales"],f=["push","replace","reload","back","prefetch","beforePopState"];function d(){if(!s.router)throw Object.defineProperty(Error('No router instance found.\nYou should only use "next/router" on the client side of your app.\n'),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return s.router}Object.defineProperty(s,"events",{get:()=>a.default.events}),c.forEach(e=>{Object.defineProperty(s,e,{get:()=>d()[e]})}),f.forEach(e=>{s[e]=function(){for(var t=arguments.length,r=Array(t),n=0;n{s.ready(()=>{a.default.events.on(e,function(){for(var t=arguments.length,r=Array(t),n=0;ne()),s.readyCallbacks=[],s.router}function m(e){let t={};for(let r of c){if("object"==typeof e[r]){t[r]=Object.assign(Array.isArray(e[r])?[]:{},e[r]);continue}t[r]=e[r]}return t.events=a.default.events,f.forEach(r=>{t[r]=function(){for(var t=arguments.length,n=Array(t),o=0;o{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"onRecoverableError",{enumerable:!0,get:function(){return l}});let n=r(4252),o=r(7258),a=r(2194),i=r(5688),u=n._(r(6240)),l=(e,t)=>{let r=(0,u.default)(e)&&"cause"in e?e.cause:e,n=(0,i.getReactStitchedError)(r);(0,o.isBailoutToCSRError)(r)||(0,a.reportGlobalError)(n)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5202:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{HTML_LIMITED_BOT_UA_RE:function(){return n.HTML_LIMITED_BOT_UA_RE},HTML_LIMITED_BOT_UA_RE_STRING:function(){return a},getBotType:function(){return l},isBot:function(){return u}});let n=r(1851),o=/Googlebot|Google-PageRenderer|AdsBot-Google|googleweblight|Storebot-Google/i,a=n.HTML_LIMITED_BOT_UA_RE.source;function i(e){return n.HTML_LIMITED_BOT_UA_RE.test(e)}function u(e){return o.test(e)||i(e)}function l(e){return o.test(e)?"dom":i(e)?"html":void 0}},5262:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return i}});let n=r(4252)._(r(36));class o{end(e){if("ended"===this.state.state)throw Object.defineProperty(Error("Span has already ended"),"__NEXT_ERROR_CODE",{value:"E17",enumerable:!1,configurable:!0});this.state={state:"ended",endTime:null!=e?e:Date.now()},this.onSpanEnd(this)}constructor(e,t,r){var n,o;this.name=e,this.attributes=null!=(n=t.attributes)?n:{},this.startTime=null!=(o=t.startTime)?o:Date.now(),this.onSpanEnd=r,this.state={state:"inprogress"}}}class a{startSpan(e,t){return new o(e,t,this.handleSpanEnd)}onSpanEnd(e){return this._emitter.on("spanend",e),()=>{this._emitter.off("spanend",e)}}constructor(){this._emitter=(0,n.default)(),this.handleSpanEnd=e=>{this._emitter.emit("spanend",e)}}}let i=new a;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5322:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"denormalizePagePath",{enumerable:!0,get:function(){return a}});let n=r(8266),o=r(5712);function a(e){let t=(0,o.normalizePathSep)(e);return t.startsWith("/index/")&&!(0,n.isDynamicRoute)(t)?t.slice(6):"/index"!==t?t:"/"}},5688:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getReactStitchedError",{enumerable:!0,get:function(){return s}});let n=r(4252),o=n._(r(4232)),a=n._(r(6240)),i=r(8089),u="react-stack-bottom-frame",l=RegExp("(at "+u+" )|("+u+"\\@)");function s(e){let t=(0,a.default)(e),r=t&&e.stack||"",n=t?e.message:"",u=r.split("\n"),s=u.findIndex(e=>l.test(e)),c=s>=0?u.slice(0,s).join("\n"):r,f=Object.defineProperty(Error(n),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0});return Object.assign(f,e),(0,i.copyNextErrorCode)(e,f),f.stack=c,function(e){if(!o.default.captureOwnerStack)return;let t=e.stack||"",r=o.default.captureOwnerStack();r&&!1===t.endsWith(r)&&(t+=r,e.stack=t)}(f),f}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5712:(e,t)=>{"use strict";function r(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return r}})},5733:e=>{"use strict";e.exports=["chrome 64","edge 79","firefox 67","opera 51","safari 12"]},5912:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_REQUEST_META:function(){return r},addRequestMeta:function(){return a},getRequestMeta:function(){return n},removeRequestMeta:function(){return i},setRequestMeta:function(){return o}});let r=Symbol.for("NextInternalRequestMeta");function n(e,t){let n=e[r]||{};return"string"==typeof t?n[t]:n}function o(e,t){return e[r]=t,t}function a(e,t,r){let a=n(e);return a[t]=r,o(e,a)}function i(e,t){let r=n(e);return delete r[t],o(e,r)}},5927:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{APP_BUILD_MANIFEST:function(){return E},APP_CLIENT_INTERNALS:function(){return Q},APP_PATHS_MANIFEST:function(){return m},APP_PATH_ROUTES_MANIFEST:function(){return g},BARREL_OPTIMIZATION_PREFIX:function(){return X},BLOCKED_PAGES:function(){return U},BUILD_ID_FILE:function(){return D},BUILD_MANIFEST:function(){return b},CLIENT_PUBLIC_FILES_PATH:function(){return k},CLIENT_REFERENCE_MANIFEST:function(){return W},CLIENT_STATIC_FILES_PATH:function(){return F},CLIENT_STATIC_FILES_RUNTIME_AMP:function(){return Z},CLIENT_STATIC_FILES_RUNTIME_MAIN:function(){return K},CLIENT_STATIC_FILES_RUNTIME_MAIN_APP:function(){return $},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS:function(){return et},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL:function(){return er},CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH:function(){return J},CLIENT_STATIC_FILES_RUNTIME_WEBPACK:function(){return ee},COMPILER_INDEXES:function(){return a},COMPILER_NAMES:function(){return o},CONFIG_FILES:function(){return L},DEFAULT_RUNTIME_WEBPACK:function(){return en},DEFAULT_SANS_SERIF_FONT:function(){return el},DEFAULT_SERIF_FONT:function(){return eu},DEV_CLIENT_MIDDLEWARE_MANIFEST:function(){return N},DEV_CLIENT_PAGES_MANIFEST:function(){return C},DYNAMIC_CSS_MANIFEST:function(){return Y},EDGE_RUNTIME_WEBPACK:function(){return eo},EDGE_UNSUPPORTED_NODE_APIS:function(){return ep},EXPORT_DETAIL:function(){return O},EXPORT_MARKER:function(){return v},FUNCTIONS_CONFIG_MANIFEST:function(){return y},IMAGES_MANIFEST:function(){return T},INTERCEPTION_ROUTE_REWRITE_MANIFEST:function(){return z},MIDDLEWARE_BUILD_MANIFEST:function(){return q},MIDDLEWARE_MANIFEST:function(){return w},MIDDLEWARE_REACT_LOADABLE_MANIFEST:function(){return V},MODERN_BROWSERSLIST_TARGET:function(){return n.default},NEXT_BUILTIN_DOCUMENT:function(){return H},NEXT_FONT_MANIFEST:function(){return R},PAGES_MANIFEST:function(){return h},PHASE_DEVELOPMENT_SERVER:function(){return f},PHASE_EXPORT:function(){return l},PHASE_INFO:function(){return p},PHASE_PRODUCTION_BUILD:function(){return s},PHASE_PRODUCTION_SERVER:function(){return c},PHASE_TEST:function(){return d},PRERENDER_MANIFEST:function(){return S},REACT_LOADABLE_MANIFEST:function(){return x},ROUTES_MANIFEST:function(){return j},RSC_MODULE_TYPES:function(){return ed},SERVER_DIRECTORY:function(){return M},SERVER_FILES_MANIFEST:function(){return A},SERVER_PROPS_ID:function(){return ei},SERVER_REFERENCE_MANIFEST:function(){return G},STATIC_PROPS_ID:function(){return ea},STATIC_STATUS_PAGES:function(){return es},STRING_LITERAL_DROP_BUNDLE:function(){return B},SUBRESOURCE_INTEGRITY_MANIFEST:function(){return P},SYSTEM_ENTRYPOINTS:function(){return eh},TRACE_OUTPUT_VERSION:function(){return ec},TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST:function(){return I},TURBO_TRACE_DEFAULT_MEMORY_LIMIT:function(){return ef},UNDERSCORE_NOT_FOUND_ROUTE:function(){return i},UNDERSCORE_NOT_FOUND_ROUTE_ENTRY:function(){return u},WEBPACK_STATS:function(){return _}});let n=r(4252)._(r(5733)),o={client:"client",server:"server",edgeServer:"edge-server"},a={[o.client]:0,[o.server]:1,[o.edgeServer]:2},i="/_not-found",u=""+i+"/page",l="phase-export",s="phase-production-build",c="phase-production-server",f="phase-development-server",d="phase-test",p="phase-info",h="pages-manifest.json",_="webpack-stats.json",m="app-paths-manifest.json",g="app-path-routes-manifest.json",b="build-manifest.json",E="app-build-manifest.json",y="functions-config-manifest.json",P="subresource-integrity-manifest",R="next-font-manifest",v="export-marker.json",O="export-detail.json",S="prerender-manifest.json",j="routes-manifest.json",T="images-manifest.json",A="required-server-files.json",C="_devPagesManifest.json",w="middleware-manifest.json",I="_clientMiddlewareManifest.json",N="_devMiddlewareManifest.json",x="react-loadable-manifest.json",M="server",L=["next.config.js","next.config.mjs","next.config.ts"],D="BUILD_ID",U=["/_document","/_app","/_error"],k="public",F="static",B="__NEXT_DROP_CLIENT_FILE__",H="__NEXT_BUILTIN_DOCUMENT__",X="__barrel_optimize__",W="client-reference-manifest",G="server-reference-manifest",q="middleware-build-manifest",V="middleware-react-loadable-manifest",z="interception-route-rewrite-manifest",Y="dynamic-css-manifest",K="main",$=""+K+"-app",Q="app-pages-internals",J="react-refresh",Z="amp",ee="webpack",et="polyfills",er=Symbol(et),en="webpack-runtime",eo="edge-runtime-webpack",ea="__N_SSG",ei="__N_SSP",eu={name:"Times New Roman",xAvgCharWidth:821,azAvgWidth:854.3953488372093,unitsPerEm:2048},el={name:"Arial",xAvgCharWidth:904,azAvgWidth:934.5116279069767,unitsPerEm:2048},es=["/500"],ec=1,ef=6e3,ed={client:"client",server:"server"},ep=["clearImmediate","setImmediate","BroadcastChannel","ByteLengthQueuingStrategy","CompressionStream","CountQueuingStrategy","DecompressionStream","DomException","MessageChannel","MessageEvent","MessagePort","ReadableByteStreamController","ReadableStreamBYOBRequest","ReadableStreamDefaultController","TransformStreamDefaultController","WritableStreamDefaultController"],eh=new Set([K,J,Z,$]);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6080:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addLocale",{enumerable:!0,get:function(){return n}}),r(9178);let n=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return b},handleClientScriptLoad:function(){return _},initScriptLoader:function(){return m}});let n=r(4252),o=r(8365),a=r(7876),i=n._(r(8477)),u=o._(r(4232)),l=r(2458),s=r(8446),c=r(6202),f=new Map,d=new Set,p=e=>{if(i.default.preinit){e.forEach(e=>{i.default.preinit(e,{as:"style"})});return}{let t=document.head;e.forEach(e=>{let r=document.createElement("link");r.type="text/css",r.rel="stylesheet",r.href=e,t.appendChild(r)})}},h=e=>{let{src:t,id:r,onLoad:n=()=>{},onReady:o=null,dangerouslySetInnerHTML:a,children:i="",strategy:u="afterInteractive",onError:l,stylesheets:c}=e,h=r||t;if(h&&d.has(h))return;if(f.has(t)){d.add(h),f.get(t).then(n,l);return}let _=()=>{o&&o(),d.add(h)},m=document.createElement("script"),g=new Promise((e,t)=>{m.addEventListener("load",function(t){e(),n&&n.call(this,t),_()}),m.addEventListener("error",function(e){t(e)})}).catch(function(e){l&&l(e)});a?(m.innerHTML=a.__html||"",_()):i?(m.textContent="string"==typeof i?i:Array.isArray(i)?i.join(""):"",_()):t&&(m.src=t,f.set(t,g)),(0,s.setAttributesFromProps)(m,e),"worker"===u&&m.setAttribute("type","text/partytown"),m.setAttribute("data-nscript",u),c&&p(c),document.body.appendChild(m)};function _(e){let{strategy:t="afterInteractive"}=e;"lazyOnload"===t?window.addEventListener("load",()=>{(0,c.requestIdleCallback)(()=>h(e))}):h(e)}function m(e){e.forEach(_),[...document.querySelectorAll('[data-nscript="beforeInteractive"]'),...document.querySelectorAll('[data-nscript="beforePageRender"]')].forEach(e=>{let t=e.id||e.getAttribute("src");d.add(t)})}function g(e){let{id:t,src:r="",onLoad:n=()=>{},onReady:o=null,strategy:s="afterInteractive",onError:f,stylesheets:p,..._}=e,{updateScripts:m,scripts:g,getIsSsr:b,appDir:E,nonce:y}=(0,u.useContext)(l.HeadManagerContext),P=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let e=t||r;P.current||(o&&e&&d.has(e)&&o(),P.current=!0)},[o,t,r]);let R=(0,u.useRef)(!1);if((0,u.useEffect)(()=>{if(!R.current){if("afterInteractive"===s)h(e);else if("lazyOnload"===s)"complete"===document.readyState?(0,c.requestIdleCallback)(()=>h(e)):window.addEventListener("load",()=>{(0,c.requestIdleCallback)(()=>h(e))});R.current=!0}},[e,s]),("beforeInteractive"===s||"worker"===s)&&(m?(g[s]=(g[s]||[]).concat([{id:t,src:r,onLoad:n,onReady:o,onError:f,..._}]),m(g)):b&&b()?d.add(t||r):b&&!b()&&h(e)),E){if(p&&p.forEach(e=>{i.default.preinit(e,{as:"style"})}),"beforeInteractive"===s)return r?(i.default.preload(r,_.integrity?{as:"script",integrity:_.integrity,nonce:y,crossOrigin:_.crossOrigin}:{as:"script",nonce:y,crossOrigin:_.crossOrigin}),(0,a.jsx)("script",{nonce:y,dangerouslySetInnerHTML:{__html:"(self.__next_s=self.__next_s||[]).push("+JSON.stringify([r,{..._,id:t}])+")"}})):(_.dangerouslySetInnerHTML&&(_.children=_.dangerouslySetInnerHTML.__html,delete _.dangerouslySetInnerHTML),(0,a.jsx)("script",{nonce:y,dangerouslySetInnerHTML:{__html:"(self.__next_s=self.__next_s||[]).push("+JSON.stringify([0,{..._,id:t}])+")"}}));"afterInteractive"===s&&r&&i.default.preload(r,_.integrity?{as:"script",integrity:_.integrity,nonce:y,crossOrigin:_.crossOrigin}:{as:"script",nonce:y,crossOrigin:_.crossOrigin})}return null}Object.defineProperty(g,"__nextScript",{value:!0});let b=g;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6202:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{cancelIdleCallback:function(){return n},requestIdleCallback:function(){return r}});let r="undefined"!=typeof self&&self.requestIdleCallback&&self.requestIdleCallback.bind(window)||function(e){let t=Date.now();return self.setTimeout(function(){e({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-t))}})},1)},n="undefined"!=typeof self&&self.cancelIdleCallback&&self.cancelIdleCallback.bind(window)||function(e){return clearTimeout(e)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6240:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return o},getProperError:function(){return a}});let n=r(9501);function o(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function a(e){return o(e)?e:Object.defineProperty(Error((0,n.isPlainObject)(e)?function(e){let t=new WeakSet;return JSON.stringify(e,(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r})}(e):e+""),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}},6249:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{createKey:function(){return G},default:function(){return z},matchesMiddleware:function(){return D}});let n=r(4252),o=r(8365),a=r(7125),i=r(1071),u=r(6179),l=o._(r(6240)),s=r(5322),c=r(1973),f=n._(r(36)),d=r(2735),p=r(7426),h=r(3264);r(1226);let _=r(6288),m=r(4645),g=r(9737);r(2119);let b=r(8963),E=r(6080),y=r(7693),P=r(4902),R=r(8549),v=r(4026),O=r(9098),S=r(2326),j=r(1874),T=r(4015),A=r(1286),C=r(800),w=r(5202),I=r(451),N=r(2680),x=r(7537),M=r(9308);function L(){return Object.assign(Object.defineProperty(Error("Route Cancelled"),"__NEXT_ERROR_CODE",{value:"E315",enumerable:!1,configurable:!0}),{cancelled:!0})}async function D(e){let t=await Promise.resolve(e.router.pageLoader.getMiddleware());if(!t)return!1;let{pathname:r}=(0,b.parsePath)(e.asPath),n=(0,v.hasBasePath)(r)?(0,P.removeBasePath)(r):r,o=(0,R.addBasePath)((0,E.addLocale)(n,e.locale));return t.some(e=>new RegExp(e.regexp).test(o))}function U(e){let t=(0,d.getLocationOrigin)();return e.startsWith(t)?e.substring(t.length):e}function k(e,t,r){let[n,o]=(0,O.resolveHref)(e,t,!0),a=(0,d.getLocationOrigin)(),i=n.startsWith(a),u=o&&o.startsWith(a);n=U(n),o=o?U(o):o;let l=i?n:(0,R.addBasePath)(n),s=r?U((0,O.resolveHref)(e,r)):o||n;return{url:l,as:u?s:(0,R.addBasePath)(s)}}function F(e,t){let r=(0,a.removeTrailingSlash)((0,s.denormalizePagePath)(e));return"/404"===r||"/_error"===r?e:(t.includes(r)||t.some(t=>{if((0,p.isDynamicRoute)(t)&&(0,m.getRouteRegex)(t).re.test(r))return e=t,!0}),(0,a.removeTrailingSlash)(e))}async function B(e){if(!await D(e)||!e.fetchData)return null;let t=await e.fetchData(),r=await function(e,t,r){let n={basePath:r.router.basePath,i18n:{locales:r.router.locales},trailingSlash:!1},o=t.headers.get("x-nextjs-rewrite"),u=o||t.headers.get("x-nextjs-matched-path"),l=t.headers.get(M.MATCHED_PATH_HEADER);if(!l||u||l.includes("__next_data_catchall")||l.includes("/_error")||l.includes("/404")||(u=l),u){if(u.startsWith("/")){let t=(0,h.parseRelativeUrl)(u),l=(0,j.getNextPathnameInfo)(t.pathname,{nextConfig:n,parseData:!0}),s=(0,a.removeTrailingSlash)(l.pathname);return Promise.all([r.router.pageLoader.getPageList(),(0,i.getClientBuildManifest)()]).then(a=>{let[i,{__rewrites:u}]=a,f=(0,E.addLocale)(l.pathname,l.locale);if((0,p.isDynamicRoute)(f)||!o&&i.includes((0,c.normalizeLocalePath)((0,P.removeBasePath)(f),r.router.locales).pathname)){let r=(0,j.getNextPathnameInfo)((0,h.parseRelativeUrl)(e).pathname,{nextConfig:n,parseData:!0});f=(0,R.addBasePath)(r.pathname),t.pathname=f}if(!i.includes(s)){let e=F(s,i);e!==s&&(s=e)}let d=i.includes(s)?s:F((0,c.normalizeLocalePath)((0,P.removeBasePath)(t.pathname),r.router.locales).pathname,i);if((0,p.isDynamicRoute)(d)){let e=(0,_.getRouteMatcher)((0,m.getRouteRegex)(d))(f);Object.assign(t.query,e||{})}return{type:"rewrite",parsedAs:t,resolvedHref:d}})}let t=(0,b.parsePath)(e);return Promise.resolve({type:"redirect-external",destination:""+(0,T.formatNextPathnameInfo)({...(0,j.getNextPathnameInfo)(t.pathname,{nextConfig:n,parseData:!0}),defaultLocale:r.router.defaultLocale,buildId:""})+t.query+t.hash})}let s=t.headers.get("x-nextjs-redirect");if(s){if(s.startsWith("/")){let e=(0,b.parsePath)(s),t=(0,T.formatNextPathnameInfo)({...(0,j.getNextPathnameInfo)(e.pathname,{nextConfig:n,parseData:!0}),defaultLocale:r.router.defaultLocale,buildId:""});return Promise.resolve({type:"redirect-internal",newAs:""+t+e.query+e.hash,newUrl:""+t+e.query+e.hash})}return Promise.resolve({type:"redirect-external",destination:s})}return Promise.resolve({type:"next"})}(t.dataHref,t.response,e);return{dataHref:t.dataHref,json:t.json,response:t.response,text:t.text,cacheKey:t.cacheKey,effect:r}}let H=Symbol("SSG_DATA_NOT_FOUND");function X(e){try{return JSON.parse(e)}catch(e){return null}}function W(e){let{dataHref:t,inflightCache:r,isPrefetch:n,hasMiddleware:o,isServerRender:a,parseJSON:u,persistCache:l,isBackground:s,unstable_skipClientCache:c}=e,{href:f}=new URL(t,window.location.href),d=e=>{var s;return(function e(t,r,n){return fetch(t,{credentials:"same-origin",method:n.method||"GET",headers:Object.assign({},n.headers,{"x-nextjs-data":"1"})}).then(o=>!o.ok&&r>1&&o.status>=500?e(t,r-1,n):o)})(t,a?3:1,{headers:Object.assign({},n?{purpose:"prefetch"}:{},n&&o?{"x-middleware-prefetch":"1"}:{},{}),method:null!=(s=null==e?void 0:e.method)?s:"GET"}).then(r=>r.ok&&(null==e?void 0:e.method)==="HEAD"?{dataHref:t,response:r,text:"",json:{},cacheKey:f}:r.text().then(e=>{if(!r.ok){if(o&&[301,302,307,308].includes(r.status))return{dataHref:t,response:r,text:e,json:{},cacheKey:f};if(404===r.status){var n;if(null==(n=X(e))?void 0:n.notFound)return{dataHref:t,json:{notFound:H},response:r,text:e,cacheKey:f}}let u=Object.defineProperty(Error("Failed to load static props"),"__NEXT_ERROR_CODE",{value:"E124",enumerable:!1,configurable:!0});throw a||(0,i.markAssetError)(u),u}return{dataHref:t,json:u?X(e):null,response:r,text:e,cacheKey:f}})).then(e=>(l&&"no-cache"!==e.response.headers.get("x-middleware-cache")||delete r[f],e)).catch(e=>{throw c||delete r[f],("Failed to fetch"===e.message||"NetworkError when attempting to fetch resource."===e.message||"Load failed"===e.message)&&(0,i.markAssetError)(e),e})};return c&&l?d({}).then(e=>("no-cache"!==e.response.headers.get("x-middleware-cache")&&(r[f]=Promise.resolve(e)),e)):void 0!==r[f]?r[f]:r[f]=d(s?{method:"HEAD"}:{})}function G(){return Math.random().toString(36).slice(2,10)}function q(e){let{url:t,router:r}=e;if(t===(0,R.addBasePath)((0,E.addLocale)(r.asPath,r.locale)))throw Object.defineProperty(Error("Invariant: attempted to hard navigate to the same URL "+t+" "+location.href),"__NEXT_ERROR_CODE",{value:"E282",enumerable:!1,configurable:!0});window.location.href=t}let V=e=>{let{route:t,router:r}=e,n=!1,o=r.clc=()=>{n=!0};return()=>{if(n){let e=Object.defineProperty(Error('Abort fetching component for route: "'+t+'"'),"__NEXT_ERROR_CODE",{value:"E483",enumerable:!1,configurable:!0});throw e.cancelled=!0,e}o===r.clc&&(r.clc=null)}};class z{reload(){window.location.reload()}back(){window.history.back()}forward(){window.history.forward()}push(e,t,r){return void 0===r&&(r={}),{url:e,as:t}=k(this,e,t),this.change("pushState",e,t,r)}replace(e,t,r){return void 0===r&&(r={}),{url:e,as:t}=k(this,e,t),this.change("replaceState",e,t,r)}async _bfl(e,t,n,o){{if(!this._bfl_s&&!this._bfl_d){let t,a;let{BloomFilter:u}=r(8286);try{({__routerFilterStatic:t,__routerFilterDynamic:a}=await (0,i.getClientBuildManifest)())}catch(t){if(console.error(t),o)return!0;return q({url:(0,R.addBasePath)((0,E.addLocale)(e,n||this.locale,this.defaultLocale)),router:this}),new Promise(()=>{})}(null==t?void 0:t.numHashes)&&(this._bfl_s=new u(t.numItems,t.errorRate),this._bfl_s.import(t)),(null==a?void 0:a.numHashes)&&(this._bfl_d=new u(a.numItems,a.errorRate),this._bfl_d.import(a))}let c=!1,f=!1;for(let{as:r,allowMatchCurrent:i}of[{as:e},{as:t}])if(r){let t=(0,a.removeTrailingSlash)(new URL(r,"http://n").pathname),d=(0,R.addBasePath)((0,E.addLocale)(t,n||this.locale));if(i||t!==(0,a.removeTrailingSlash)(new URL(this.asPath,"http://n").pathname)){var u,l,s;for(let e of(c=c||!!(null==(u=this._bfl_s)?void 0:u.contains(t))||!!(null==(l=this._bfl_s)?void 0:l.contains(d)),[t,d])){let t=e.split("/");for(let e=0;!f&&e{})}}}}return!1}async change(e,t,r,n,o){var s,c,f,O,S,j,T,w,x;let M,U;if(!(0,C.isLocalURL)(t))return q({url:t,router:this}),!1;let B=1===n._h;B||n.shallow||await this._bfl(r,void 0,n.locale);let X=B||n._shouldResolveHref||(0,b.parsePath)(t).pathname===(0,b.parsePath)(r).pathname,W={...this.state},G=!0!==this.isReady;this.isReady=!0;let V=this.isSsr;if(B||(this.isSsr=!1),B&&this.clc)return!1;let Y=W.locale;d.ST&&performance.mark("routeChange");let{shallow:K=!1,scroll:$=!0}=n,Q={shallow:K};this._inFlightRoute&&this.clc&&(V||z.events.emit("routeChangeError",L(),this._inFlightRoute,Q),this.clc(),this.clc=null),r=(0,R.addBasePath)((0,E.addLocale)((0,v.hasBasePath)(r)?(0,P.removeBasePath)(r):r,n.locale,this.defaultLocale));let J=(0,y.removeLocale)((0,v.hasBasePath)(r)?(0,P.removeBasePath)(r):r,W.locale);this._inFlightRoute=r;let Z=Y!==W.locale;if(!B&&this.onlyAHashChange(J)&&!Z){W.asPath=J,z.events.emit("hashChangeStart",r,Q),this.changeState(e,t,r,{...n,scroll:!1}),$&&this.scrollToHash(J);try{await this.set(W,this.components[W.route],null)}catch(e){throw(0,l.default)(e)&&e.cancelled&&z.events.emit("routeChangeError",e,J,Q),e}return z.events.emit("hashChangeComplete",r,Q),!0}let ee=(0,h.parseRelativeUrl)(t),{pathname:et,query:er}=ee;try{[M,{__rewrites:U}]=await Promise.all([this.pageLoader.getPageList(),(0,i.getClientBuildManifest)(),this.pageLoader.getMiddleware()])}catch(e){return q({url:r,router:this}),!1}this.urlIsNew(J)||Z||(e="replaceState");let en=r;et=et?(0,a.removeTrailingSlash)((0,P.removeBasePath)(et)):et;let eo=(0,a.removeTrailingSlash)(et),ea=r.startsWith("/")&&(0,h.parseRelativeUrl)(r).pathname;if(null==(s=this.components[et])?void 0:s.__appRouter)return q({url:r,router:this}),new Promise(()=>{});let ei=!!(ea&&eo!==ea&&(!(0,p.isDynamicRoute)(eo)||!(0,_.getRouteMatcher)((0,m.getRouteRegex)(eo))(ea))),eu=!n.shallow&&await D({asPath:r,locale:W.locale,router:this});if(B&&eu&&(X=!1),X&&"/_error"!==et&&(n._shouldResolveHref=!0,ee.pathname=F(et,M),ee.pathname===et||(et=ee.pathname,ee.pathname=(0,R.addBasePath)(et),eu||(t=(0,g.formatWithValidation)(ee)))),!(0,C.isLocalURL)(r))return q({url:r,router:this}),!1;en=(0,y.removeLocale)((0,P.removeBasePath)(en),W.locale),eo=(0,a.removeTrailingSlash)(et);let el=!1;if((0,p.isDynamicRoute)(eo)){let e=(0,h.parseRelativeUrl)(en),n=e.pathname,o=(0,m.getRouteRegex)(eo);el=(0,_.getRouteMatcher)(o)(n);let a=eo===n,i=a?(0,N.interpolateAs)(eo,n,er):{};if(el&&(!a||i.result))a?r=(0,g.formatWithValidation)(Object.assign({},e,{pathname:i.result,query:(0,I.omit)(er,i.params)})):Object.assign(er,el);else{let e=Object.keys(o.groups).filter(e=>!er[e]&&!o.groups[e].optional);if(e.length>0&&!eu)throw Object.defineProperty(Error((a?"The provided `href` ("+t+") value is missing query values ("+e.join(", ")+") to be interpolated properly. ":"The provided `as` value ("+n+") is incompatible with the `href` value ("+eo+"). ")+"Read more: https://nextjs.org/docs/messages/"+(a?"href-interpolation-failed":"incompatible-href-as")),"__NEXT_ERROR_CODE",{value:"E344",enumerable:!1,configurable:!0})}}B||z.events.emit("routeChangeStart",r,Q);let es="/404"===this.pathname||"/_error"===this.pathname;try{let a=await this.getRouteInfo({route:eo,pathname:et,query:er,as:r,resolvedAs:en,routeProps:Q,locale:W.locale,isPreview:W.isPreview,hasMiddleware:eu,unstable_skipClientCache:n.unstable_skipClientCache,isQueryUpdating:B&&!this.isFallback,isMiddlewareRewrite:ei});if(B||n.shallow||await this._bfl(r,"resolvedAs"in a?a.resolvedAs:void 0,W.locale),"route"in a&&eu){eo=et=a.route||eo,Q.shallow||(er=Object.assign({},a.query||{},er));let e=(0,v.hasBasePath)(ee.pathname)?(0,P.removeBasePath)(ee.pathname):ee.pathname;if(el&&et!==e&&Object.keys(el).forEach(e=>{el&&er[e]===el[e]&&delete er[e]}),(0,p.isDynamicRoute)(et)){let e=!Q.shallow&&a.resolvedAs?a.resolvedAs:(0,R.addBasePath)((0,E.addLocale)(new URL(r,location.href).pathname,W.locale),!0);(0,v.hasBasePath)(e)&&(e=(0,P.removeBasePath)(e));let t=(0,m.getRouteRegex)(et),n=(0,_.getRouteMatcher)(t)(new URL(e,location.href).pathname);n&&Object.assign(er,n)}}if("type"in a){if("redirect-internal"===a.type)return this.change(e,a.newUrl,a.newAs,n);return q({url:a.destination,router:this}),new Promise(()=>{})}let i=a.Component;if(i&&i.unstable_scriptLoader&&[].concat(i.unstable_scriptLoader()).forEach(e=>{(0,u.handleClientScriptLoad)(e.props)}),(a.__N_SSG||a.__N_SSP)&&a.props){if(a.props.pageProps&&a.props.pageProps.__N_REDIRECT){n.locale=!1;let t=a.props.pageProps.__N_REDIRECT;if(t.startsWith("/")&&!1!==a.props.pageProps.__N_REDIRECT_BASE_PATH){let r=(0,h.parseRelativeUrl)(t);r.pathname=F(r.pathname,M);let{url:o,as:a}=k(this,t,t);return this.change(e,o,a,n)}return q({url:t,router:this}),new Promise(()=>{})}if(W.isPreview=!!a.props.__N_PREVIEW,a.props.notFound===H){let e;try{await this.fetchComponent("/404"),e="/404"}catch(t){e="/_error"}if(a=await this.getRouteInfo({route:e,pathname:e,query:er,as:r,resolvedAs:en,routeProps:{shallow:!1},locale:W.locale,isPreview:W.isPreview,isNotFound:!0}),"type"in a)throw Object.defineProperty(Error("Unexpected middleware effect on /404"),"__NEXT_ERROR_CODE",{value:"E158",enumerable:!1,configurable:!0})}}B&&"/_error"===this.pathname&&(null==(f=self.__NEXT_DATA__.props)?void 0:null==(c=f.pageProps)?void 0:c.statusCode)===500&&(null==(O=a.props)?void 0:O.pageProps)&&(a.props.pageProps.statusCode=500);let s=n.shallow&&W.route===(null!=(S=a.route)?S:eo),d=null!=(j=n.scroll)?j:!B&&!s,g=null!=o?o:d?{x:0,y:0}:null,b={...W,route:eo,pathname:et,query:er,asPath:J,isFallback:!1};if(B&&es){if(a=await this.getRouteInfo({route:this.pathname,pathname:this.pathname,query:er,as:r,resolvedAs:en,routeProps:{shallow:!1},locale:W.locale,isPreview:W.isPreview,isQueryUpdating:B&&!this.isFallback}),"type"in a)throw Object.defineProperty(Error("Unexpected middleware effect on "+this.pathname),"__NEXT_ERROR_CODE",{value:"E225",enumerable:!1,configurable:!0});"/_error"===this.pathname&&(null==(w=self.__NEXT_DATA__.props)?void 0:null==(T=w.pageProps)?void 0:T.statusCode)===500&&(null==(x=a.props)?void 0:x.pageProps)&&(a.props.pageProps.statusCode=500);try{await this.set(b,a,g)}catch(e){throw(0,l.default)(e)&&e.cancelled&&z.events.emit("routeChangeError",e,J,Q),e}return!0}if(z.events.emit("beforeHistoryChange",r,Q),this.changeState(e,t,r,n),!(B&&!g&&!G&&!Z&&(0,A.compareRouterStates)(b,this.state))){try{await this.set(b,a,g)}catch(e){if(e.cancelled)a.error=a.error||e;else throw e}if(a.error)throw B||z.events.emit("routeChangeError",a.error,J,Q),a.error;B||z.events.emit("routeChangeComplete",r,Q),d&&/#.+$/.test(r)&&this.scrollToHash(r)}return!0}catch(e){if((0,l.default)(e)&&e.cancelled)return!1;throw e}}changeState(e,t,r,n){void 0===n&&(n={}),("pushState"!==e||(0,d.getURL)()!==r)&&(this._shallow=n.shallow,window.history[e]({url:t,as:r,options:n,__N:!0,key:this._key="pushState"!==e?this._key:G()},"",r))}async handleRouteInfoError(e,t,r,n,o,a){if(e.cancelled)throw e;if((0,i.isAssetError)(e)||a)throw z.events.emit("routeChangeError",e,n,o),q({url:n,router:this}),L();console.error(e);try{let n;let{page:o,styleSheets:a}=await this.fetchComponent("/_error"),i={props:n,Component:o,styleSheets:a,err:e,error:e};if(!i.props)try{i.props=await this.getInitialProps(o,{err:e,pathname:t,query:r})}catch(e){console.error("Error in error page `getInitialProps`: ",e),i.props={}}return i}catch(e){return this.handleRouteInfoError((0,l.default)(e)?e:Object.defineProperty(Error(e+""),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0}),t,r,n,o,!0)}}async getRouteInfo(e){let{route:t,pathname:r,query:n,as:o,resolvedAs:i,routeProps:u,locale:s,hasMiddleware:f,isPreview:d,unstable_skipClientCache:p,isQueryUpdating:h,isMiddlewareRewrite:_,isNotFound:m}=e,b=t;try{var E,y,R,v;let e=this.components[b];if(u.shallow&&e&&this.route===b)return e;let t=V({route:b,router:this});f&&(e=void 0);let l=!e||"initial"in e?void 0:e,O={dataHref:this.pageLoader.getDataHref({href:(0,g.formatWithValidation)({pathname:r,query:n}),skipInterpolation:!0,asPath:m?"/404":i,locale:s}),hasMiddleware:!0,isServerRender:this.isSsr,parseJSON:!0,inflightCache:h?this.sbc:this.sdc,persistCache:!d,isPrefetch:!1,unstable_skipClientCache:p,isBackground:h},j=h&&!_?null:await B({fetchData:()=>W(O),asPath:m?"/404":i,locale:s,router:this}).catch(e=>{if(h)return null;throw e});if(j&&("/_error"===r||"/404"===r)&&(j.effect=void 0),h&&(j?j.json=self.__NEXT_DATA__.props:j={json:self.__NEXT_DATA__.props}),t(),(null==j?void 0:null==(E=j.effect)?void 0:E.type)==="redirect-internal"||(null==j?void 0:null==(y=j.effect)?void 0:y.type)==="redirect-external")return j.effect;if((null==j?void 0:null==(R=j.effect)?void 0:R.type)==="rewrite"){let t=(0,a.removeTrailingSlash)(j.effect.resolvedHref),o=await this.pageLoader.getPageList();if((!h||o.includes(t))&&(b=t,r=j.effect.resolvedHref,n={...n,...j.effect.parsedAs.query},i=(0,P.removeBasePath)((0,c.normalizeLocalePath)(j.effect.parsedAs.pathname,this.locales).pathname),e=this.components[b],u.shallow&&e&&this.route===b&&!f))return{...e,route:b}}if((0,S.isAPIRoute)(b))return q({url:o,router:this}),new Promise(()=>{});let T=l||await this.fetchComponent(b).then(e=>({Component:e.page,styleSheets:e.styleSheets,__N_SSG:e.mod.__N_SSG,__N_SSP:e.mod.__N_SSP})),A=null==j?void 0:null==(v=j.response)?void 0:v.headers.get("x-middleware-skip"),C=T.__N_SSG||T.__N_SSP;A&&(null==j?void 0:j.dataHref)&&delete this.sdc[j.dataHref];let{props:w,cacheKey:I}=await this._getData(async()=>{if(C){if((null==j?void 0:j.json)&&!A)return{cacheKey:j.cacheKey,props:j.json};let e=(null==j?void 0:j.dataHref)?j.dataHref:this.pageLoader.getDataHref({href:(0,g.formatWithValidation)({pathname:r,query:n}),asPath:i,locale:s}),t=await W({dataHref:e,isServerRender:this.isSsr,parseJSON:!0,inflightCache:A?{}:this.sdc,persistCache:!d,isPrefetch:!1,unstable_skipClientCache:p});return{cacheKey:t.cacheKey,props:t.json||{}}}return{headers:{},props:await this.getInitialProps(T.Component,{pathname:r,query:n,asPath:o,locale:s,locales:this.locales,defaultLocale:this.defaultLocale})}});return T.__N_SSP&&O.dataHref&&I&&delete this.sdc[I],this.isPreview||!T.__N_SSG||h||W(Object.assign({},O,{isBackground:!0,persistCache:!1,inflightCache:this.sbc})).catch(()=>{}),w.pageProps=Object.assign({},w.pageProps),T.props=w,T.route=b,T.query=n,T.resolvedAs=i,this.components[b]=T,T}catch(e){return this.handleRouteInfoError((0,l.getProperError)(e),r,n,o,u)}}set(e,t,r){return this.state=e,this.sub(t,this.components["/_app"].Component,r)}beforePopState(e){this._bps=e}onlyAHashChange(e){if(!this.asPath)return!1;let[t,r]=this.asPath.split("#",2),[n,o]=e.split("#",2);return!!o&&t===n&&r===o||t===n&&r!==o}scrollToHash(e){let[,t=""]=e.split("#",2);(0,x.handleSmoothScroll)(()=>{if(""===t||"top"===t){window.scrollTo(0,0);return}let e=decodeURIComponent(t),r=document.getElementById(e);if(r){r.scrollIntoView();return}let n=document.getElementsByName(e)[0];n&&n.scrollIntoView()},{onlyHashChange:this.onlyAHashChange(e)})}urlIsNew(e){return this.asPath!==e}async prefetch(e,t,r){if(void 0===t&&(t=e),void 0===r&&(r={}),(0,w.isBot)(window.navigator.userAgent))return;let n=(0,h.parseRelativeUrl)(e),o=n.pathname,{pathname:i,query:u}=n,l=i,s=await this.pageLoader.getPageList(),c=t,f=void 0!==r.locale?r.locale||void 0:this.locale,d=await D({asPath:t,locale:f,router:this});n.pathname=F(n.pathname,s),(0,p.isDynamicRoute)(n.pathname)&&(i=n.pathname,n.pathname=i,Object.assign(u,(0,_.getRouteMatcher)((0,m.getRouteRegex)(n.pathname))((0,b.parsePath)(t).pathname)||{}),d||(e=(0,g.formatWithValidation)(n)));let E=await B({fetchData:()=>W({dataHref:this.pageLoader.getDataHref({href:(0,g.formatWithValidation)({pathname:l,query:u}),skipInterpolation:!0,asPath:c,locale:f}),hasMiddleware:!0,isServerRender:!1,parseJSON:!0,inflightCache:this.sdc,persistCache:!this.isPreview,isPrefetch:!0}),asPath:t,locale:f,router:this});if((null==E?void 0:E.effect.type)==="rewrite"&&(n.pathname=E.effect.resolvedHref,i=E.effect.resolvedHref,u={...u,...E.effect.parsedAs.query},c=E.effect.parsedAs.pathname,e=(0,g.formatWithValidation)(n)),(null==E?void 0:E.effect.type)==="redirect-external")return;let y=(0,a.removeTrailingSlash)(i);await this._bfl(t,c,r.locale,!0)&&(this.components[o]={__appRouter:!0}),await Promise.all([this.pageLoader._isSsg(y).then(t=>!!t&&W({dataHref:(null==E?void 0:E.json)?null==E?void 0:E.dataHref:this.pageLoader.getDataHref({href:e,asPath:c,locale:f}),isServerRender:!1,parseJSON:!0,inflightCache:this.sdc,persistCache:!this.isPreview,isPrefetch:!0,unstable_skipClientCache:r.unstable_skipClientCache||r.priority&&!0}).then(()=>!1).catch(()=>!1)),this.pageLoader[r.priority?"loadPage":"prefetch"](y)])}async fetchComponent(e){let t=V({route:e,router:this});try{let r=await this.pageLoader.loadPage(e);return t(),r}catch(e){throw t(),e}}_getData(e){let t=!1,r=()=>{t=!0};return this.clc=r,e().then(e=>{if(r===this.clc&&(this.clc=null),t){let e=Object.defineProperty(Error("Loading initial props cancelled"),"__NEXT_ERROR_CODE",{value:"E405",enumerable:!1,configurable:!0});throw e.cancelled=!0,e}return e})}getInitialProps(e,t){let{Component:r}=this.components["/_app"],n=this._wrapApp(r);return t.AppTree=n,(0,d.loadGetInitialProps)(r,{AppTree:n,Component:e,router:this,ctx:t})}get route(){return this.state.route}get pathname(){return this.state.pathname}get query(){return this.state.query}get asPath(){return this.state.asPath}get locale(){return this.state.locale}get isFallback(){return this.state.isFallback}get isPreview(){return this.state.isPreview}constructor(e,t,r,{initialProps:n,pageLoader:o,App:i,wrapApp:u,Component:l,err:s,subscription:c,isFallback:f,locale:_,locales:m,defaultLocale:b,domainLocales:E,isPreview:y}){this.sdc={},this.sbc={},this.isFirstPopStateEvent=!0,this._key=G(),this.onPopState=e=>{let t;let{isFirstPopStateEvent:r}=this;this.isFirstPopStateEvent=!1;let n=e.state;if(!n){let{pathname:e,query:t}=this;this.changeState("replaceState",(0,g.formatWithValidation)({pathname:(0,R.addBasePath)(e),query:t}),(0,d.getURL)());return}if(n.__NA){window.location.reload();return}if(!n.__N||r&&this.locale===n.options.locale&&n.as===this.asPath)return;let{url:o,as:a,options:i,key:u}=n;this._key=u;let{pathname:l}=(0,h.parseRelativeUrl)(o);(!this.isSsr||a!==(0,R.addBasePath)(this.asPath)||l!==(0,R.addBasePath)(this.pathname))&&(!this._bps||this._bps(n))&&this.change("replaceState",o,a,Object.assign({},i,{shallow:i.shallow&&this._shallow,locale:i.locale||this.defaultLocale,_h:0}),t)};let P=(0,a.removeTrailingSlash)(e);this.components={},"/_error"!==e&&(this.components[P]={Component:l,initial:!0,props:n,err:s,__N_SSG:n&&n.__N_SSG,__N_SSP:n&&n.__N_SSP}),this.components["/_app"]={Component:i,styleSheets:[]},this.events=z.events,this.pageLoader=o;let v=(0,p.isDynamicRoute)(e)&&self.__NEXT_DATA__.autoExport;if(this.basePath="",this.sub=c,this.clc=null,this._wrapApp=u,this.isSsr=!0,this.isLocaleDomain=!1,this.isReady=!!(self.__NEXT_DATA__.gssp||self.__NEXT_DATA__.gip||self.__NEXT_DATA__.isExperimentalCompile||self.__NEXT_DATA__.appGip&&!self.__NEXT_DATA__.gsp||!v&&!self.location.search),this.state={route:P,pathname:e,query:t,asPath:v?e:r,isPreview:!!y,locale:void 0,isFallback:f},this._initialMatchesMiddlewarePromise=Promise.resolve(!1),!r.startsWith("//")){let n={locale:_},o=(0,d.getURL)();this._initialMatchesMiddlewarePromise=D({router:this,locale:_,asPath:o}).then(a=>(n._shouldResolveHref=r!==e,this.changeState("replaceState",a?o:(0,g.formatWithValidation)({pathname:(0,R.addBasePath)(e),query:t}),o,n),a))}window.addEventListener("popstate",this.onPopState)}}z.events=(0,f.default)()},6288:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getRouteMatcher",{enumerable:!0,get:function(){return o}});let n=r(2735);function o(e){let{re:t,groups:r}=e;return e=>{let o=t.exec(e);if(!o)return!1;let a=e=>{try{return decodeURIComponent(e)}catch(e){throw Object.defineProperty(new n.DecodeError("failed to decode param"),"__NEXT_ERROR_CODE",{value:"E528",enumerable:!1,configurable:!0})}},i={};for(let[e,t]of Object.entries(r)){let r=o[t.pos];void 0!==r&&(t.repeat?i[e]=r.split("/").map(e=>a(e)):i[e]=a(r))}return i}}},6392:(e,t)=>{"use strict";function r(e){let{ampFirst:t=!1,hybrid:r=!1,hasQuery:n=!1}=void 0===e?{}:e;return t||r&&n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return r}})},6545:(e,t)=>{"use strict";function r(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return r}})},7125:(e,t)=>{"use strict";function r(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return r}})},7168:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ImageConfigContext",{enumerable:!0,get:function(){return a}});let n=r(4252)._(r(4232)),o=r(2080),a=n.default.createContext(o.imageConfigDefault)},7258:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{BailoutToCSRError:function(){return n},isBailoutToCSRError:function(){return o}});let r="BAILOUT_TO_CLIENT_SIDE_RENDERING";class n extends Error{constructor(e){super("Bail out to client-side rendering: "+e),this.reason=e,this.digest=r}}function o(e){return"object"==typeof e&&null!==e&&"digest"in e&&e.digest===r}},7327:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(8757),self.__next_set_public_path__=e=>{r.p=e},("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7369:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removePathPrefix",{enumerable:!0,get:function(){return o}});let n=r(7411);function o(e,t){if(!(0,n.pathHasPrefix)(e,t))return e;let r=e.slice(t.length);return r.startsWith("/")?r:"/"+r}},7411:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return o}});let n=r(8963);function o(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,n.parsePath)(e);return r===t||r.startsWith(t+"/")}},7426:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isDynamicRoute",{enumerable:!0,get:function(){return i}});let n=r(522),o=/\/[^/]*\[[^/]+\][^/]*(?=\/|$)/,a=/\/\[[^/]+\](?=\/|$)/;function i(e,t){return(void 0===t&&(t=!0),(0,n.isInterceptionRouteAppPath)(e)&&(e=(0,n.extractInterceptionRouteInformation)(e).interceptedRoute),t)?a.test(e):o.test(e)}},7537:(e,t)=>{"use strict";function r(e,t){if(void 0===t&&(t={}),t.onlyHashChange){e();return}let r=document.documentElement,n=r.style.scrollBehavior;r.style.scrollBehavior="auto",t.dontForceLayout||r.getClientRects(),e(),r.style.scrollBehavior=n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return r}})},7667:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RouteAnnouncer:function(){return l},default:function(){return s}});let n=r(4252),o=r(7876),a=n._(r(4232)),i=r(5045),u={border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",top:0,width:"1px",whiteSpace:"nowrap",wordWrap:"normal"},l=()=>{let{asPath:e}=(0,i.useRouter)(),[t,r]=a.default.useState(""),n=a.default.useRef(e);return a.default.useEffect(()=>{if(n.current!==e){if(n.current=e,document.title)r(document.title);else{var t;let n=document.querySelector("h1");r((null!=(t=null==n?void 0:n.innerText)?t:null==n?void 0:n.textContent)||e)}}},[e]),(0,o.jsx)("p",{"aria-live":"assertive",id:"__next-route-announcer__",role:"alert",style:u,children:t})},s=l;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7693:(e,t,r)=>{"use strict";function n(e,t){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeLocale",{enumerable:!0,get:function(){return n}}),r(8963),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7835:(e,t)=>{"use strict";function r(e){return"("===e[0]&&e.endsWith(")")}function n(e){return e.startsWith("@")&&"@children"!==e}function o(e,t){if(e.includes(a)){let e=JSON.stringify(t);return"{}"!==e?a+"?"+e:a}return e}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DEFAULT_SEGMENT_KEY:function(){return i},PAGE_SEGMENT_KEY:function(){return a},addSearchParamsIfPageSegment:function(){return o},isGroupSegment:function(){return r},isParallelRouteSegment:function(){return n}});let a="__PAGE__",i="__DEFAULT__"},8089:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{copyNextErrorCode:function(){return n},createDigestWithErrorCode:function(){return r},extractNextErrorCode:function(){return o}});let r=(e,t)=>"object"==typeof e&&null!==e&&"__NEXT_ERROR_CODE"in e?`${t}@${e.__NEXT_ERROR_CODE}`:t,n=(e,t)=>{let r=o(e);r&&"object"==typeof t&&null!==t&&Object.defineProperty(t,"__NEXT_ERROR_CODE",{value:r,enumerable:!1,configurable:!0})},o=e=>"object"==typeof e&&null!==e&&"__NEXT_ERROR_CODE"in e&&"string"==typeof e.__NEXT_ERROR_CODE?e.__NEXT_ERROR_CODE:"object"==typeof e&&null!==e&&"digest"in e&&"string"==typeof e.digest?e.digest.split("@").find(e=>e.startsWith("E")):void 0},8188:(e,t,r)=>{"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return i},isEqualNode:function(){return a}});let o=r(8446);function a(e,t){if(e instanceof HTMLElement&&t instanceof HTMLElement){let r=t.getAttribute("nonce");if(r&&!e.getAttribute("nonce")){let n=t.cloneNode(!0);return n.setAttribute("nonce",""),n.nonce=r,r===e.nonce&&e.isEqualNode(n)}}return e.isEqualNode(t)}function i(){return{mountedInstances:new Set,updateHead:e=>{let t={};e.forEach(e=>{if("link"===e.type&&e.props["data-optimized-fonts"]){if(document.querySelector('style[data-href="'+e.props["data-href"]+'"]'))return;e.props.href=e.props["data-href"],e.props["data-href"]=void 0}let r=t[e.type]||[];r.push(e),t[e.type]=r});let r=t.title?t.title[0]:null,o="";if(r){let{children:e}=r.props;o="string"==typeof e?e:Array.isArray(e)?e.join(""):""}o!==document.title&&(document.title=o),["meta","base","link","style","script"].forEach(e=>{n(e,t[e]||[])})}}}n=(e,t)=>{let r=document.querySelector("head");if(!r)return;let n=new Set(r.querySelectorAll(""+e+"[data-next-head]"));if("meta"===e){let e=r.querySelector("meta[charset]");null!==e&&n.add(e)}let i=[];for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return d}});let n=r(4252),o=r(8549),a=r(2680),i=n._(r(9692)),u=r(6080),l=r(7426),s=r(3264),c=r(7125),f=r(1071);r(5927);class d{getPageList(){return(0,f.getClientBuildManifest)().then(e=>e.sortedPages)}getMiddleware(){return window.__MIDDLEWARE_MATCHERS=[],window.__MIDDLEWARE_MATCHERS}getDataHref(e){let{asPath:t,href:r,locale:n}=e,{pathname:f,query:d,search:p}=(0,s.parseRelativeUrl)(r),{pathname:h}=(0,s.parseRelativeUrl)(t),_=(0,c.removeTrailingSlash)(f);if("/"!==_[0])throw Object.defineProperty(Error('Route name should start with a "/", got "'+_+'"'),"__NEXT_ERROR_CODE",{value:"E303",enumerable:!1,configurable:!0});return(e=>{let t=(0,i.default)((0,c.removeTrailingSlash)((0,u.addLocale)(e,n)),".json");return(0,o.addBasePath)("/_next/data/"+this.buildId+t+p,!0)})(e.skipInterpolation?h:(0,l.isDynamicRoute)(_)?(0,a.interpolateAs)(f,h,d).result:_)}_isSsg(e){return this.promisedSsgManifest.then(t=>t.has(e))}loadPage(e){return this.routeLoader.loadRoute(e).then(e=>{if("component"in e)return{page:e.component,mod:e.exports,styleSheets:e.styles.map(e=>({href:e.href,text:e.content}))};throw e.error})}prefetch(e){return this.routeLoader.prefetch(e)}constructor(e,t){this.routeLoader=(0,f.createRouteLoader)(t),this.buildId=e,this.assetPrefix=t,this.promisedSsgManifest=new Promise(e=>{window.__SSG_MANIFEST?e(window.__SSG_MANIFEST):window.__SSG_MANIFEST_CB=()=>{e(window.__SSG_MANIFEST)}})}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8266:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getSortedRouteObjects:function(){return n.getSortedRouteObjects},getSortedRoutes:function(){return n.getSortedRoutes},isDynamicRoute:function(){return o.isDynamicRoute}});let n=r(4304),o=r(7426)},8286:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"BloomFilter",{enumerable:!0,get:function(){return r}});class r{static from(e,t){void 0===t&&(t=1e-4);let n=new r(e.length,t);for(let t of e)n.add(t);return n}export(){return{numItems:this.numItems,errorRate:this.errorRate,numBits:this.numBits,numHashes:this.numHashes,bitArray:this.bitArray}}import(e){this.numItems=e.numItems,this.errorRate=e.errorRate,this.numBits=e.numBits,this.numHashes=e.numHashes,this.bitArray=e.bitArray}add(e){this.getHashValues(e).forEach(e=>{this.bitArray[e]=1})}contains(e){return this.getHashValues(e).every(e=>this.bitArray[e])}getHashValues(e){let t=[];for(let r=1;r<=this.numHashes;r++){let n=function(e){let t=0;for(let r=0;r>>13,t=Math.imul(t,0x5bd1e995);return t>>>0}(""+e+r)%this.numBits;t.push(n)}return t}constructor(e,t=1e-4){this.numItems=e,this.errorRate=t,this.numBits=Math.ceil(-(e*Math.log(t))/(Math.log(2)*Math.log(2))),this.numHashes=Math.ceil(this.numBits/e*Math.log(2)),this.bitArray=Array(this.numBits).fill(0)}}},8365:(e,t,r)=>{"use strict";function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function o(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var o={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if("default"!==i&&Object.prototype.hasOwnProperty.call(e,i)){var u=a?Object.getOwnPropertyDescriptor(e,i):null;u&&(u.get||u.set)?Object.defineProperty(o,i,u):o[i]=e[i]}return o.default=e,r&&r.set(e,o),o}r.r(t),r.d(t,{_:()=>o})},8409:(e,t)=>{"use strict";function r(e){return e.split("/").map(e=>encodeURIComponent(e)).join("/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"encodeURIPath",{enumerable:!0,get:function(){return r}})},8446:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"setAttributesFromProps",{enumerable:!0,get:function(){return a}});let r={acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv",noModule:"noModule"},n=["onLoad","onReady","dangerouslySetInnerHTML","children","onError","strategy","stylesheets"];function o(e){return["async","defer","noModule"].includes(e)}function a(e,t){for(let[a,i]of Object.entries(t)){if(!t.hasOwnProperty(a)||n.includes(a)||void 0===i)continue;let u=r[a]||a.toLowerCase();"SCRIPT"===e.tagName&&o(u)?e[u]=!!i:e.setAttribute(u,String(i)),(!1===i||"SCRIPT"===e.tagName&&o(u)&&(!i||"false"===i))&&(e.setAttribute(u,""),e.removeAttribute(u))}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8549:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return a}});let n=r(2982),o=r(9178);function a(e,t){return(0,o.normalizePathTrailingSlash)((0,n.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8757:(e,t)=>{"use strict";function r(){return""}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getDeploymentIdQueryOrEmptyString",{enumerable:!0,get:function(){return r}})},8880:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AmpStateContext",{enumerable:!0,get:function(){return n}});let n=r(4252)._(r(4232)).default.createContext({})},8906:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addLocale",{enumerable:!0,get:function(){return a}});let n=r(2982),o=r(7411);function a(e,t,r,a){if(!t||t===r)return e;let i=e.toLowerCase();return!a&&((0,o.pathHasPrefix)(i,"/api")||(0,o.pathHasPrefix)(i,"/"+t.toLowerCase()))?e:(0,n.addPathPrefix)(e,"/"+t)}},8963:(e,t)=>{"use strict";function r(e){let t=e.indexOf("#"),r=e.indexOf("?"),n=r>-1&&(t<0||r-1?{pathname:e.substring(0,n?r:t),query:n?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return r}})},9042:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PathParamsContext:function(){return i},PathnameContext:function(){return a},SearchParamsContext:function(){return o}});let n=r(4232),o=(0,n.createContext)(null),a=(0,n.createContext)(null),i=(0,n.createContext)(null)},9098:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"resolveHref",{enumerable:!0,get:function(){return f}});let n=r(2587),o=r(9737),a=r(451),i=r(2735),u=r(9178),l=r(800),s=r(8266),c=r(2680);function f(e,t,r){let f;let d="string"==typeof t?t:(0,o.formatWithValidation)(t),p=d.match(/^[a-zA-Z]{1,}:\/\//),h=p?d.slice(p[0].length):d;if((h.split("?",1)[0]||"").match(/(\/\/|\\)/)){console.error("Invalid href '"+d+"' passed to next/router in page: '"+e.pathname+"'. Repeated forward-slashes (//) or backslashes \\ are not valid in the href.");let t=(0,i.normalizeRepeatedSlashes)(h);d=(p?p[0]:"")+t}if(!(0,l.isLocalURL)(d))return r?[d]:d;try{f=new URL(d.startsWith("#")?e.asPath:e.pathname,"http://n")}catch(e){f=new URL("/","http://n")}try{let e=new URL(d,f);e.pathname=(0,u.normalizePathTrailingSlash)(e.pathname);let t="";if((0,s.isDynamicRoute)(e.pathname)&&e.searchParams&&r){let r=(0,n.searchParamsToUrlQuery)(e.searchParams),{result:i,params:u}=(0,c.interpolateAs)(e.pathname,e.pathname,r);i&&(t=(0,o.formatWithValidation)({pathname:i,hash:e.hash,query:(0,a.omit)(r,u)}))}let i=e.origin===f.origin?e.href.slice(e.origin.length):e.href;return r?[i,t||i]:i}catch(e){return r?[d]:d}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9178:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return a}});let n=r(7125),o=r(8963),a=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:r,hash:a}=(0,o.parsePath)(e);return""+(0,n.removeTrailingSlash)(t)+r+a};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9218:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}}),r(4252);let n=r(7876);r(4232);let o=r(5045);function a(e){function t(t){return(0,n.jsx)(e,{router:(0,o.useRouter)(),...t})}return t.getInitialProps=e.getInitialProps,t.origGetInitialProps=e.origGetInitialProps,t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9308:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ACTION_SUFFIX:function(){return f},APP_DIR_ALIAS:function(){return I},CACHE_ONE_YEAR:function(){return v},DOT_NEXT_ALIAS:function(){return C},ESLINT_DEFAULT_DIRS:function(){return $},GSP_NO_RETURNED_VALUE:function(){return G},GSSP_COMPONENT_MEMBER_ERROR:function(){return z},GSSP_NO_RETURNED_VALUE:function(){return q},INFINITE_CACHE:function(){return O},INSTRUMENTATION_HOOK_FILENAME:function(){return T},MATCHED_PATH_HEADER:function(){return o},MIDDLEWARE_FILENAME:function(){return S},MIDDLEWARE_LOCATION_REGEXP:function(){return j},NEXT_BODY_SUFFIX:function(){return h},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return R},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return m},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return g},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return P},NEXT_CACHE_TAGS_HEADER:function(){return _},NEXT_CACHE_TAG_MAX_ITEMS:function(){return E},NEXT_CACHE_TAG_MAX_LENGTH:function(){return y},NEXT_DATA_SUFFIX:function(){return d},NEXT_INTERCEPTION_MARKER_PREFIX:function(){return n},NEXT_META_SUFFIX:function(){return p},NEXT_QUERY_PARAM_PREFIX:function(){return r},NEXT_RESUME_HEADER:function(){return b},NON_STANDARD_NODE_ENV:function(){return Y},PAGES_DIR_ALIAS:function(){return A},PRERENDER_REVALIDATE_HEADER:function(){return a},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return i},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return k},ROOT_DIR_ALIAS:function(){return w},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return U},RSC_ACTION_ENCRYPTION_ALIAS:function(){return D},RSC_ACTION_PROXY_ALIAS:function(){return M},RSC_ACTION_VALIDATE_ALIAS:function(){return x},RSC_CACHE_WRAPPER_ALIAS:function(){return L},RSC_MOD_REF_PROXY_ALIAS:function(){return N},RSC_PREFETCH_SUFFIX:function(){return u},RSC_SEGMENTS_DIR_SUFFIX:function(){return l},RSC_SEGMENT_SUFFIX:function(){return s},RSC_SUFFIX:function(){return c},SERVER_PROPS_EXPORT_ERROR:function(){return W},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return B},SERVER_PROPS_SSG_CONFLICT:function(){return H},SERVER_RUNTIME:function(){return Q},SSG_FALLBACK_EXPORT_ERROR:function(){return K},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return F},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return X},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return V},WEBPACK_LAYERS:function(){return Z},WEBPACK_RESOURCE_QUERIES:function(){return ee}});let r="nxtP",n="nxtI",o="x-matched-path",a="x-prerender-revalidate",i="x-prerender-revalidate-if-generated",u=".prefetch.rsc",l=".segments",s=".segment.rsc",c=".rsc",f=".action",d=".json",p=".meta",h=".body",_="x-next-cache-tags",m="x-next-revalidated-tags",g="x-next-revalidate-tag-token",b="next-resume",E=128,y=256,P=1024,R="_N_T_",v=31536e3,O=0xfffffffe,S="middleware",j=`(?:src/)?${S}`,T="instrumentation",A="private-next-pages",C="private-dot-next",w="private-next-root-dir",I="private-next-app-dir",N="private-next-rsc-mod-ref-proxy",x="private-next-rsc-action-validate",M="private-next-rsc-server-reference",L="private-next-rsc-cache-wrapper",D="private-next-rsc-action-encryption",U="private-next-rsc-action-client-wrapper",k="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",F="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",B="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",H="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",X="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",W="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",G="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",q="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",V="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",z="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",Y='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',K="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",$=["app","pages","components","lib","src"],Q={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},J={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",instrument:"instrument",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",pagesDirBrowser:"pages-dir-browser",pagesDirEdge:"pages-dir-edge",pagesDirNode:"pages-dir-node"},Z={...J,GROUP:{builtinReact:[J.reactServerComponents,J.actionBrowser],serverOnly:[J.reactServerComponents,J.actionBrowser,J.instrument,J.middleware],neutralTarget:[J.api],clientOnly:[J.serverSideRendering,J.appPagesBrowser],bundled:[J.reactServerComponents,J.actionBrowser,J.serverSideRendering,J.appPagesBrowser,J.shared,J.instrument,J.middleware],appPages:[J.reactServerComponents,J.serverSideRendering,J.appPagesBrowser,J.actionBrowser]}},ee={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},9468:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return c}});let n=r(4252),o=r(7876),a=n._(r(4232)),i=n._(r(3748));r(5912);let u={400:"Bad Request",404:"This page could not be found",405:"Method Not Allowed",500:"Internal Server Error"};function l(e){let{req:t,res:r,err:n}=e;return{statusCode:r&&r.statusCode?r.statusCode:n?n.statusCode:404,hostname:window.location.hostname}}let s={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{lineHeight:"48px"},h1:{display:"inline-block",margin:"0 20px 0 0",paddingRight:23,fontSize:24,fontWeight:500,verticalAlign:"top"},h2:{fontSize:14,fontWeight:400,lineHeight:"28px"},wrap:{display:"inline-block"}};class c extends a.default.Component{render(){let{statusCode:e,withDarkMode:t=!0}=this.props,r=this.props.title||u[e]||"An unexpected error has occurred";return(0,o.jsxs)("div",{style:s.error,children:[(0,o.jsx)(i.default,{children:(0,o.jsx)("title",{children:e?e+": "+r:"Application error: a client-side exception has occurred"})}),(0,o.jsxs)("div",{style:s.desc,children:[(0,o.jsx)("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}"+(t?"@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}":"")}}),e?(0,o.jsx)("h1",{className:"next-error-h1",style:s.h1,children:e}):null,(0,o.jsx)("div",{style:s.wrap,children:(0,o.jsxs)("h2",{style:s.h2,children:[this.props.title||e?r:(0,o.jsxs)(o.Fragment,{children:["Application error: a client-side exception has occurred"," ",!!this.props.hostname&&(0,o.jsxs)(o.Fragment,{children:["while loading ",this.props.hostname]})," ","(see the browser console for more information)"]}),"."]})})]})]})}}c.displayName="ErrorPage",c.getInitialProps=l,c.origGetInitialProps=l,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9482:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return r}});let r=e=>{}},9501:(e,t)=>{"use strict";function r(e){return Object.prototype.toString.call(e)}function n(e){if("[object Object]"!==r(e))return!1;let t=Object.getPrototypeOf(e);return null===t||t.hasOwnProperty("isPrototypeOf")}Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getObjectClassLabel:function(){return r},isPlainObject:function(){return n}})},9692:(e,t)=>{"use strict";function r(e,t){return void 0===t&&(t=""),("/"===e?"/index":/^\/index(\/|$)/.test(e)?"/index"+e:e)+t}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r}})},9737:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),!function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{formatUrl:function(){return a},formatWithValidation:function(){return u},urlObjectKeys:function(){return i}});let n=r(8365)._(r(2587)),o=/https?|ftp|gopher|file/;function a(e){let{auth:t,hostname:r}=e,a=e.protocol||"",i=e.pathname||"",u=e.hash||"",l=e.query||"",s=!1;t=t?encodeURIComponent(t).replace(/%3A/i,":")+"@":"",e.host?s=t+e.host:r&&(s=t+(~r.indexOf(":")?"["+r+"]":r),e.port&&(s+=":"+e.port)),l&&"object"==typeof l&&(l=String(n.urlQueryToSearchParams(l)));let c=e.search||l&&"?"+l||"";return a&&!a.endsWith(":")&&(a+=":"),e.slashes||(!a||o.test(a))&&!1!==s?(s="//"+(s||""),i&&"/"!==i[0]&&(i="/"+i)):s||(s=""),u&&"#"!==u[0]&&(u="#"+u),c&&"?"!==c[0]&&(c="?"+c),""+a+s+(i=i.replace(/[?#]/g,encodeURIComponent))+(c=c.replace("#","%23"))+u}let i=["auth","hash","host","hostname","href","path","pathname","port","protocol","query","search","slashes"];function u(e){return a(e)}},9742:e=>{var t,r,n,o=e.exports={};function a(){throw Error("setTimeout has not been defined")}function i(){throw Error("clearTimeout has not been defined")}function u(e){if(t===setTimeout)return setTimeout(e,0);if((t===a||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:a}catch(e){t=a}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(e){r=i}}();var l=[],s=!1,c=-1;function f(){s&&n&&(s=!1,n.length?l=n.concat(l):c=-1,l.length&&d())}function d(){if(!s){var e=u(f);s=!0;for(var t=l.length;t;){for(n=l,l=[];++c1)for(var r=1;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return l}});let n=r(4252),o=r(7876),a=n._(r(4232)),i=r(2735);async function u(e){let{Component:t,ctx:r}=e;return{pageProps:await (0,i.loadGetInitialProps)(t,r)}}class l extends a.default.Component{render(){let{Component:e,pageProps:t}=this.props;return(0,o.jsx)(e,{...t})}}l.origGetInitialProps=u,l.getInitialProps=u,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9909:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Portal",{enumerable:!0,get:function(){return a}});let n=r(4232),o=r(8477),a=e=>{let{children:t,type:r}=e,[a,i]=(0,n.useState)(null);return(0,n.useEffect)(()=>{let e=document.createElement(r);return document.body.appendChild(e),i(e),()=>{document.body.removeChild(e)}},[r]),a?(0,o.createPortal)(t,a):null};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}},e=>{var t=t=>e(e.s=t);e.O(0,[593],()=>t(1113)),_N_E=e.O()}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/main-app-a763a7d9993e9efd.js b/services/v1/media/feedback/static/_next/static/chunks/main-app-a763a7d9993e9efd.js new file mode 100644 index 0000000000000000000000000000000000000000..81f3a0de482bf930eaa1446d9b1430b3e056a22d --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/main-app-a763a7d9993e9efd.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[358],{148:(e,s,n)=>{Promise.resolve().then(n.t.bind(n,7033,23)),Promise.resolve().then(n.t.bind(n,4547,23)),Promise.resolve().then(n.t.bind(n,4835,23)),Promise.resolve().then(n.t.bind(n,2328,23)),Promise.resolve().then(n.t.bind(n,5244,23)),Promise.resolve().then(n.t.bind(n,3866,23)),Promise.resolve().then(n.t.bind(n,7539,23)),Promise.resolve().then(n.t.bind(n,6213,23))}},e=>{var s=s=>e(e.s=s);e.O(0,[441,587],()=>(s(7200),s(148))),_N_E=e.O()}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/pages/_app-eef484fc49b57a90.js b/services/v1/media/feedback/static/_next/static/chunks/pages/_app-eef484fc49b57a90.js new file mode 100644 index 0000000000000000000000000000000000000000..58573a7f741719b16699ba589ef10b2cad0a79e8 --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/pages/_app-eef484fc49b57a90.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[636],{326:(_,n,p)=>{(window.__NEXT_P=window.__NEXT_P||[]).push(["/_app",function(){return p(9761)}])}},_=>{var n=n=>_(_.s=n);_.O(0,[593,792],()=>(n(326),n(5045))),_N_E=_.O()}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/pages/_error-5933f280f2bada68.js b/services/v1/media/feedback/static/_next/static/chunks/pages/_error-5933f280f2bada68.js new file mode 100644 index 0000000000000000000000000000000000000000..f2fa197294d1afd93594b5c4d11a50b4ee8359ac --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/pages/_error-5933f280f2bada68.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[731],{2164:(_,n,e)=>{(window.__NEXT_P=window.__NEXT_P||[]).push(["/_error",function(){return e(9468)}])}},_=>{var n=n=>_(_.s=n);_.O(0,[636,593,792],()=>n(2164)),_N_E=_.O()}]); \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/chunks/polyfills-42372ed130431b0a.js b/services/v1/media/feedback/static/_next/static/chunks/polyfills-42372ed130431b0a.js new file mode 100644 index 0000000000000000000000000000000000000000..ab422b94a4fbe76275d31c0bf7ef334768b39cae --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/chunks/polyfills-42372ed130431b0a.js @@ -0,0 +1 @@ +!function(){var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function e(t){var e={exports:{}};return t(e,e.exports),e.exports}var r,n,o=function(t){return t&&t.Math===Math&&t},i=o("object"==typeof globalThis&&globalThis)||o("object"==typeof window&&window)||o("object"==typeof self&&self)||o("object"==typeof t&&t)||o("object"==typeof t&&t)||function(){return this}()||Function("return this")(),a=function(t){try{return!!t()}catch(t){return!0}},u=!a(function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}),s=!a(function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}),c=Function.prototype.call,f=s?c.bind(c):function(){return c.apply(c,arguments)},l={}.propertyIsEnumerable,h=Object.getOwnPropertyDescriptor,p=h&&!l.call({1:2},1)?function(t){var e=h(this,t);return!!e&&e.enumerable}:l,v={f:p},d=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},g=Function.prototype,y=g.call,m=s&&g.bind.bind(y,y),b=s?m:function(t){return function(){return y.apply(t,arguments)}},w=b({}.toString),S=b("".slice),E=function(t){return S(w(t),8,-1)},O=Object,x=b("".split),R=a(function(){return!O("z").propertyIsEnumerable(0)})?function(t){return"String"===E(t)?x(t,""):O(t)}:O,P=function(t){return null==t},A=TypeError,j=function(t){if(P(t))throw new A("Can't call method on "+t);return t},k=function(t){return R(j(t))},I="object"==typeof document&&document.all,T=void 0===I&&void 0!==I?function(t){return"function"==typeof t||t===I}:function(t){return"function"==typeof t},M=function(t){return"object"==typeof t?null!==t:T(t)},L=function(t,e){return arguments.length<2?T(r=i[t])?r:void 0:i[t]&&i[t][e];var r},U=b({}.isPrototypeOf),N=i.navigator,C=N&&N.userAgent,_=C?String(C):"",F=i.process,B=i.Deno,D=F&&F.versions||B&&B.version,z=D&&D.v8;z&&(n=(r=z.split("."))[0]>0&&r[0]<4?1:+(r[0]+r[1])),!n&&_&&(!(r=_.match(/Edge\/(\d+)/))||r[1]>=74)&&(r=_.match(/Chrome\/(\d+)/))&&(n=+r[1]);var W=n,q=i.String,H=!!Object.getOwnPropertySymbols&&!a(function(){var t=Symbol("symbol detection");return!q(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&W&&W<41}),$=H&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,K=Object,G=$?function(t){return"symbol"==typeof t}:function(t){var e=L("Symbol");return T(e)&&U(e.prototype,K(t))},V=String,Y=function(t){try{return V(t)}catch(t){return"Object"}},X=TypeError,J=function(t){if(T(t))return t;throw new X(Y(t)+" is not a function")},Q=function(t,e){var r=t[e];return P(r)?void 0:J(r)},Z=TypeError,tt=Object.defineProperty,et=function(t,e){try{tt(i,t,{value:e,configurable:!0,writable:!0})}catch(r){i[t]=e}return e},rt=e(function(t){var e="__core-js_shared__",r=t.exports=i[e]||et(e,{});(r.versions||(r.versions=[])).push({version:"3.38.1",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE",source:"https://github.com/zloirock/core-js"})}),nt=function(t,e){return rt[t]||(rt[t]=e||{})},ot=Object,it=function(t){return ot(j(t))},at=b({}.hasOwnProperty),ut=Object.hasOwn||function(t,e){return at(it(t),e)},st=0,ct=Math.random(),ft=b(1..toString),lt=function(t){return"Symbol("+(void 0===t?"":t)+")_"+ft(++st+ct,36)},ht=i.Symbol,pt=nt("wks"),vt=$?ht.for||ht:ht&&ht.withoutSetter||lt,dt=function(t){return ut(pt,t)||(pt[t]=H&&ut(ht,t)?ht[t]:vt("Symbol."+t)),pt[t]},gt=TypeError,yt=dt("toPrimitive"),mt=function(t,e){if(!M(t)||G(t))return t;var r,n=Q(t,yt);if(n){if(void 0===e&&(e="default"),r=f(n,t,e),!M(r)||G(r))return r;throw new gt("Can't convert object to primitive value")}return void 0===e&&(e="number"),function(t,e){var r,n;if("string"===e&&T(r=t.toString)&&!M(n=f(r,t)))return n;if(T(r=t.valueOf)&&!M(n=f(r,t)))return n;if("string"!==e&&T(r=t.toString)&&!M(n=f(r,t)))return n;throw new Z("Can't convert object to primitive value")}(t,e)},bt=function(t){var e=mt(t,"string");return G(e)?e:e+""},wt=i.document,St=M(wt)&&M(wt.createElement),Et=function(t){return St?wt.createElement(t):{}},Ot=!u&&!a(function(){return 7!==Object.defineProperty(Et("div"),"a",{get:function(){return 7}}).a}),xt=Object.getOwnPropertyDescriptor,Rt={f:u?xt:function(t,e){if(t=k(t),e=bt(e),Ot)try{return xt(t,e)}catch(t){}if(ut(t,e))return d(!f(v.f,t,e),t[e])}},Pt=u&&a(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype}),At=String,jt=TypeError,kt=function(t){if(M(t))return t;throw new jt(At(t)+" is not an object")},It=TypeError,Tt=Object.defineProperty,Mt=Object.getOwnPropertyDescriptor,Lt="enumerable",Ut="configurable",Nt="writable",Ct={f:u?Pt?function(t,e,r){if(kt(t),e=bt(e),kt(r),"function"==typeof t&&"prototype"===e&&"value"in r&&Nt in r&&!r[Nt]){var n=Mt(t,e);n&&n[Nt]&&(t[e]=r.value,r={configurable:Ut in r?r[Ut]:n[Ut],enumerable:Lt in r?r[Lt]:n[Lt],writable:!1})}return Tt(t,e,r)}:Tt:function(t,e,r){if(kt(t),e=bt(e),kt(r),Ot)try{return Tt(t,e,r)}catch(t){}if("get"in r||"set"in r)throw new It("Accessors not supported");return"value"in r&&(t[e]=r.value),t}},_t=u?function(t,e,r){return Ct.f(t,e,d(1,r))}:function(t,e,r){return t[e]=r,t},Ft=Function.prototype,Bt=u&&Object.getOwnPropertyDescriptor,Dt=ut(Ft,"name"),zt={EXISTS:Dt,PROPER:Dt&&"something"===function(){}.name,CONFIGURABLE:Dt&&(!u||u&&Bt(Ft,"name").configurable)},Wt=b(Function.toString);T(rt.inspectSource)||(rt.inspectSource=function(t){return Wt(t)});var qt,Ht,$t,Kt=rt.inspectSource,Gt=i.WeakMap,Vt=T(Gt)&&/native code/.test(String(Gt)),Yt=nt("keys"),Xt=function(t){return Yt[t]||(Yt[t]=lt(t))},Jt={},Qt="Object already initialized",Zt=i.TypeError;if(Vt||rt.state){var te=rt.state||(rt.state=new(0,i.WeakMap));te.get=te.get,te.has=te.has,te.set=te.set,qt=function(t,e){if(te.has(t))throw new Zt(Qt);return e.facade=t,te.set(t,e),e},Ht=function(t){return te.get(t)||{}},$t=function(t){return te.has(t)}}else{var ee=Xt("state");Jt[ee]=!0,qt=function(t,e){if(ut(t,ee))throw new Zt(Qt);return e.facade=t,_t(t,ee,e),e},Ht=function(t){return ut(t,ee)?t[ee]:{}},$t=function(t){return ut(t,ee)}}var re,ne={set:qt,get:Ht,has:$t,enforce:function(t){return $t(t)?Ht(t):qt(t,{})},getterFor:function(t){return function(e){var r;if(!M(e)||(r=Ht(e)).type!==t)throw new Zt("Incompatible receiver, "+t+" required");return r}}},oe=e(function(t){var e=zt.CONFIGURABLE,r=ne.enforce,n=ne.get,o=String,i=Object.defineProperty,s=b("".slice),c=b("".replace),f=b([].join),l=u&&!a(function(){return 8!==i(function(){},"length",{value:8}).length}),h=String(String).split("String"),p=t.exports=function(t,n,a){"Symbol("===s(o(n),0,7)&&(n="["+c(o(n),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),a&&a.getter&&(n="get "+n),a&&a.setter&&(n="set "+n),(!ut(t,"name")||e&&t.name!==n)&&(u?i(t,"name",{value:n,configurable:!0}):t.name=n),l&&a&&ut(a,"arity")&&t.length!==a.arity&&i(t,"length",{value:a.arity});try{a&&ut(a,"constructor")&&a.constructor?u&&i(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var p=r(t);return ut(p,"source")||(p.source=f(h,"string"==typeof n?n:"")),t};Function.prototype.toString=p(function(){return T(this)&&n(this).source||Kt(this)},"toString")}),ie=function(t,e,r,n){n||(n={});var o=n.enumerable,i=void 0!==n.name?n.name:e;if(T(r)&&oe(r,i,n),n.global)o?t[e]=r:et(e,r);else{try{n.unsafe?t[e]&&(o=!0):delete t[e]}catch(t){}o?t[e]=r:Ct.f(t,e,{value:r,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return t},ae=Math.ceil,ue=Math.floor,se=Math.trunc||function(t){var e=+t;return(e>0?ue:ae)(e)},ce=function(t){var e=+t;return e!=e||0===e?0:se(e)},fe=Math.max,le=Math.min,he=function(t,e){var r=ce(t);return r<0?fe(r+e,0):le(r,e)},pe=Math.min,ve=function(t){var e=ce(t);return e>0?pe(e,9007199254740991):0},de=function(t){return ve(t.length)},ge=function(t){return function(e,r,n){var o=k(e),i=de(o);if(0===i)return!t&&-1;var a,u=he(n,i);if(t&&r!=r){for(;i>u;)if((a=o[u++])!=a)return!0}else for(;i>u;u++)if((t||u in o)&&o[u]===r)return t||u||0;return!t&&-1}},ye={includes:ge(!0),indexOf:ge(!1)},me=ye.indexOf,be=b([].push),we=function(t,e){var r,n=k(t),o=0,i=[];for(r in n)!ut(Jt,r)&&ut(n,r)&&be(i,r);for(;e.length>o;)ut(n,r=e[o++])&&(~me(i,r)||be(i,r));return i},Se=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ee=Se.concat("length","prototype"),Oe={f:Object.getOwnPropertyNames||function(t){return we(t,Ee)}},xe={f:Object.getOwnPropertySymbols},Re=b([].concat),Pe=L("Reflect","ownKeys")||function(t){var e=Oe.f(kt(t)),r=xe.f;return r?Re(e,r(t)):e},Ae=function(t,e,r){for(var n=Pe(e),o=Ct.f,i=Rt.f,a=0;aa;)Ct.f(t,r=o[a++],n[r]);return t},Be={f:Fe},De=L("document","documentElement"),ze="prototype",We="script",qe=Xt("IE_PROTO"),He=function(){},$e=function(t){return"<"+We+">"+t+""},Ke=function(t){t.write($e("")),t.close();var e=t.parentWindow.Object;return t=null,e},Ge=function(){try{re=new ActiveXObject("htmlfile")}catch(t){}var t,e,r;Ge="undefined"!=typeof document?document.domain&&re?Ke(re):(e=Et("iframe"),r="java"+We+":",e.style.display="none",De.appendChild(e),e.src=String(r),(t=e.contentWindow.document).open(),t.write($e("document.F=Object")),t.close(),t.F):Ke(re);for(var n=Se.length;n--;)delete Ge[ze][Se[n]];return Ge()};Jt[qe]=!0;var Ve=Object.create||function(t,e){var r;return null!==t?(He[ze]=kt(t),r=new He,He[ze]=null,r[qe]=t):r=Ge(),void 0===e?r:Be.f(r,e)},Ye=Ct.f,Xe=dt("unscopables"),Je=Array.prototype;void 0===Je[Xe]&&Ye(Je,Xe,{configurable:!0,value:Ve(null)});var Qe=function(t){Je[Xe][t]=!0};Ce({target:"Array",proto:!0},{at:function(t){var e=it(this),r=de(e),n=ce(t),o=n>=0?n:r+n;return o<0||o>=r?void 0:e[o]}}),Qe("at");var Ze=function(t,e){return b(i[t].prototype[e])},tr=(Ze("Array","at"),TypeError),er=function(t,e){if(!delete t[e])throw new tr("Cannot delete property "+Y(e)+" of "+Y(t))},rr=Math.min,nr=[].copyWithin||function(t,e){var r=it(this),n=de(r),o=he(t,n),i=he(e,n),a=arguments.length>2?arguments[2]:void 0,u=rr((void 0===a?n:he(a,n))-i,n-o),s=1;for(i0;)i in r?r[o]=r[i]:er(r,o),o+=s,i+=s;return r};Ce({target:"Array",proto:!0},{copyWithin:nr}),Qe("copyWithin"),Ze("Array","copyWithin"),Ce({target:"Array",proto:!0},{fill:function(t){for(var e=it(this),r=de(e),n=arguments.length,o=he(n>1?arguments[1]:void 0,r),i=n>2?arguments[2]:void 0,a=void 0===i?r:he(i,r);a>o;)e[o++]=t;return e}}),Qe("fill"),Ze("Array","fill");var or=function(t){if("Function"===E(t))return b(t)},ir=or(or.bind),ar=function(t,e){return J(t),void 0===e?t:s?ir(t,e):function(){return t.apply(e,arguments)}},ur=Array.isArray||function(t){return"Array"===E(t)},sr={};sr[dt("toStringTag")]="z";var cr="[object z]"===String(sr),fr=dt("toStringTag"),lr=Object,hr="Arguments"===E(function(){return arguments}()),pr=cr?E:function(t){var e,r,n;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(r=function(t,e){try{return t[e]}catch(t){}}(e=lr(t),fr))?r:hr?E(e):"Object"===(n=E(e))&&T(e.callee)?"Arguments":n},vr=function(){},dr=L("Reflect","construct"),gr=/^\s*(?:class|function)\b/,yr=b(gr.exec),mr=!gr.test(vr),br=function(t){if(!T(t))return!1;try{return dr(vr,[],t),!0}catch(t){return!1}},wr=function(t){if(!T(t))return!1;switch(pr(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return mr||!!yr(gr,Kt(t))}catch(t){return!0}};wr.sham=!0;var Sr=!dr||a(function(){var t;return br(br.call)||!br(Object)||!br(function(){t=!0})||t})?wr:br,Er=dt("species"),Or=Array,xr=function(t,e){return new(function(t){var e;return ur(t)&&(Sr(e=t.constructor)&&(e===Or||ur(e.prototype))||M(e)&&null===(e=e[Er]))&&(e=void 0),void 0===e?Or:e}(t))(0===e?0:e)},Rr=b([].push),Pr=function(t){var e=1===t,r=2===t,n=3===t,o=4===t,i=6===t,a=7===t,u=5===t||i;return function(s,c,f,l){for(var h,p,v=it(s),d=R(v),g=de(d),y=ar(c,f),m=0,b=l||xr,w=e?b(s,g):r||a?b(s,0):void 0;g>m;m++)if((u||m in d)&&(p=y(h=d[m],m,v),t))if(e)w[m]=p;else if(p)switch(t){case 3:return!0;case 5:return h;case 6:return m;case 2:Rr(w,h)}else switch(t){case 4:return!1;case 7:Rr(w,h)}return i?-1:n||o?o:w}},Ar={forEach:Pr(0),map:Pr(1),filter:Pr(2),some:Pr(3),every:Pr(4),find:Pr(5),findIndex:Pr(6),filterReject:Pr(7)},jr=Ar.find,kr="find",Ir=!0;kr in[]&&Array(1)[kr](function(){Ir=!1}),Ce({target:"Array",proto:!0,forced:Ir},{find:function(t){return jr(this,t,arguments.length>1?arguments[1]:void 0)}}),Qe(kr),Ze("Array","find");var Tr=Ar.findIndex,Mr="findIndex",Lr=!0;Mr in[]&&Array(1)[Mr](function(){Lr=!1}),Ce({target:"Array",proto:!0,forced:Lr},{findIndex:function(t){return Tr(this,t,arguments.length>1?arguments[1]:void 0)}}),Qe(Mr),Ze("Array","findIndex");var Ur=TypeError,Nr=function(t){if(t>9007199254740991)throw Ur("Maximum allowed index exceeded");return t},Cr=function(t,e,r,n,o,i,a,u){for(var s,c,f=o,l=0,h=!!a&&ar(a,u);l0&&ur(s)?(c=de(s),f=Cr(t,e,s,c,f,i-1)-1):(Nr(f+1),t[f]=s),f++),l++;return f},_r=Cr;Ce({target:"Array",proto:!0},{flatMap:function(t){var e,r=it(this),n=de(r);return J(t),(e=xr(r,0)).length=_r(e,r,r,n,0,1,t,arguments.length>1?arguments[1]:void 0),e}}),Qe("flatMap"),Ze("Array","flatMap"),Ce({target:"Array",proto:!0},{flat:function(){var t=arguments.length?arguments[0]:void 0,e=it(this),r=de(e),n=xr(e,0);return n.length=_r(n,e,e,r,0,void 0===t?1:ce(t)),n}}),Qe("flat"),Ze("Array","flat");var Fr,Br,Dr,zr=String,Wr=function(t){if("Symbol"===pr(t))throw new TypeError("Cannot convert a Symbol value to a string");return zr(t)},qr=b("".charAt),Hr=b("".charCodeAt),$r=b("".slice),Kr=function(t){return function(e,r){var n,o,i=Wr(j(e)),a=ce(r),u=i.length;return a<0||a>=u?t?"":void 0:(n=Hr(i,a))<55296||n>56319||a+1===u||(o=Hr(i,a+1))<56320||o>57343?t?qr(i,a):n:t?$r(i,a,a+2):o-56320+(n-55296<<10)+65536}},Gr={codeAt:Kr(!1),charAt:Kr(!0)},Vr=!a(function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}),Yr=Xt("IE_PROTO"),Xr=Object,Jr=Xr.prototype,Qr=Vr?Xr.getPrototypeOf:function(t){var e=it(t);if(ut(e,Yr))return e[Yr];var r=e.constructor;return T(r)&&e instanceof r?r.prototype:e instanceof Xr?Jr:null},Zr=dt("iterator"),tn=!1;[].keys&&("next"in(Dr=[].keys())?(Br=Qr(Qr(Dr)))!==Object.prototype&&(Fr=Br):tn=!0);var en=!M(Fr)||a(function(){var t={};return Fr[Zr].call(t)!==t});en&&(Fr={}),T(Fr[Zr])||ie(Fr,Zr,function(){return this});var rn={IteratorPrototype:Fr,BUGGY_SAFARI_ITERATORS:tn},nn=Ct.f,on=dt("toStringTag"),an=function(t,e,r){t&&!r&&(t=t.prototype),t&&!ut(t,on)&&nn(t,on,{configurable:!0,value:e})},un={},sn=rn.IteratorPrototype,cn=function(){return this},fn=function(t,e,r,n){var o=e+" Iterator";return t.prototype=Ve(sn,{next:d(+!n,r)}),an(t,o,!1),un[o]=cn,t},ln=function(t,e,r){try{return b(J(Object.getOwnPropertyDescriptor(t,e)[r]))}catch(t){}},hn=String,pn=TypeError,vn=function(t){if(function(t){return M(t)||null===t}(t))return t;throw new pn("Can't set "+hn(t)+" as a prototype")},dn=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,r={};try{(t=ln(Object.prototype,"__proto__","set"))(r,[]),e=r instanceof Array}catch(t){}return function(r,n){return j(r),vn(n),M(r)?(e?t(r,n):r.__proto__=n,r):r}}():void 0),gn=zt.PROPER,yn=zt.CONFIGURABLE,mn=rn.IteratorPrototype,bn=rn.BUGGY_SAFARI_ITERATORS,wn=dt("iterator"),Sn="keys",En="values",On="entries",xn=function(){return this},Rn=function(t,e,r,n,o,i,a){fn(r,e,n);var u,s,c,l=function(t){if(t===o&&g)return g;if(!bn&&t&&t in v)return v[t];switch(t){case Sn:case En:case On:return function(){return new r(this,t)}}return function(){return new r(this)}},h=e+" Iterator",p=!1,v=t.prototype,d=v[wn]||v["@@iterator"]||o&&v[o],g=!bn&&d||l(o),y="Array"===e&&v.entries||d;if(y&&(u=Qr(y.call(new t)))!==Object.prototype&&u.next&&(Qr(u)!==mn&&(dn?dn(u,mn):T(u[wn])||ie(u,wn,xn)),an(u,h,!0)),gn&&o===En&&d&&d.name!==En&&(yn?_t(v,"name",En):(p=!0,g=function(){return f(d,this)})),o)if(s={values:l(En),keys:i?g:l(Sn),entries:l(On)},a)for(c in s)(bn||p||!(c in v))&&ie(v,c,s[c]);else Ce({target:e,proto:!0,forced:bn||p},s);return v[wn]!==g&&ie(v,wn,g,{name:o}),un[e]=g,s},Pn=function(t,e){return{value:t,done:e}},An=Gr.charAt,jn="String Iterator",kn=ne.set,In=ne.getterFor(jn);Rn(String,"String",function(t){kn(this,{type:jn,string:Wr(t),index:0})},function(){var t,e=In(this),r=e.string,n=e.index;return n>=r.length?Pn(void 0,!0):(t=An(r,n),e.index+=t.length,Pn(t,!1))});var Tn=function(t,e,r){var n,o;kt(t);try{if(!(n=Q(t,"return"))){if("throw"===e)throw r;return r}n=f(n,t)}catch(t){o=!0,n=t}if("throw"===e)throw r;if(o)throw n;return kt(n),r},Mn=function(t,e,r,n){try{return n?e(kt(r)[0],r[1]):e(r)}catch(e){Tn(t,"throw",e)}},Ln=dt("iterator"),Un=Array.prototype,Nn=function(t){return void 0!==t&&(un.Array===t||Un[Ln]===t)},Cn=function(t,e,r){u?Ct.f(t,e,d(0,r)):t[e]=r},_n=dt("iterator"),Fn=function(t){if(!P(t))return Q(t,_n)||Q(t,"@@iterator")||un[pr(t)]},Bn=TypeError,Dn=function(t,e){var r=arguments.length<2?Fn(t):e;if(J(r))return kt(f(r,t));throw new Bn(Y(t)+" is not iterable")},zn=Array,Wn=function(t){var e=it(t),r=Sr(this),n=arguments.length,o=n>1?arguments[1]:void 0,i=void 0!==o;i&&(o=ar(o,n>2?arguments[2]:void 0));var a,u,s,c,l,h,p=Fn(e),v=0;if(!p||this===zn&&Nn(p))for(a=de(e),u=r?new this(a):zn(a);a>v;v++)h=i?o(e[v],v):e[v],Cn(u,v,h);else for(u=r?new this:[],l=(c=Dn(e,p)).next;!(s=f(l,c)).done;v++)h=i?Mn(c,o,[s.value,v],!0):s.value,Cn(u,v,h);return u.length=v,u},qn=dt("iterator"),Hn=!1;try{var $n=0,Kn={next:function(){return{done:!!$n++}},return:function(){Hn=!0}};Kn[qn]=function(){return this},Array.from(Kn,function(){throw 2})}catch(t){}var Gn=function(t,e){try{if(!e&&!Hn)return!1}catch(t){return!1}var r=!1;try{var n={};n[qn]=function(){return{next:function(){return{done:r=!0}}}},t(n)}catch(t){}return r},Vn=!Gn(function(t){Array.from(t)});Ce({target:"Array",stat:!0,forced:Vn},{from:Wn});var Yn=i,Xn=ye.includes,Jn=a(function(){return!Array(1).includes()});Ce({target:"Array",proto:!0,forced:Jn},{includes:function(t){return Xn(this,t,arguments.length>1?arguments[1]:void 0)}}),Qe("includes"),Ze("Array","includes");var Qn=Ct.f,Zn="Array Iterator",to=ne.set,eo=ne.getterFor(Zn),ro=Rn(Array,"Array",function(t,e){to(this,{type:Zn,target:k(t),index:0,kind:e})},function(){var t=eo(this),e=t.target,r=t.index++;if(!e||r>=e.length)return t.target=null,Pn(void 0,!0);switch(t.kind){case"keys":return Pn(r,!1);case"values":return Pn(e[r],!1)}return Pn([r,e[r]],!1)},"values"),no=un.Arguments=un.Array;if(Qe("keys"),Qe("values"),Qe("entries"),u&&"values"!==no.name)try{Qn(no,"name",{value:"values"})}catch(t){}cr||ie(Object.prototype,"toString",cr?{}.toString:function(){return"[object "+pr(this)+"]"},{unsafe:!0}),Ze("Array","values");var oo=Array,io=a(function(){function t(){}return!(oo.of.call(t)instanceof t)});Ce({target:"Array",stat:!0,forced:io},{of:function(){for(var t=0,e=arguments.length,r=new(Sr(this)?this:oo)(e);e>t;)Cn(r,t,arguments[t++]);return r.length=e,r}});var ao=dt("hasInstance"),uo=Function.prototype;ao in uo||Ct.f(uo,ao,{value:oe(function(t){if(!T(this)||!M(t))return!1;var e=this.prototype;return M(e)?U(e,t):t instanceof this},ao)}),dt("hasInstance");var so=function(t,e,r){return r.get&&oe(r.get,e,{getter:!0}),r.set&&oe(r.set,e,{setter:!0}),Ct.f(t,e,r)},co=zt.EXISTS,fo=Function.prototype,lo=b(fo.toString),ho=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,po=b(ho.exec);u&&!co&&so(fo,"name",{configurable:!0,get:function(){try{return po(ho,lo(this))[1]}catch(t){return""}}});var vo=b([].slice),go=Oe.f,yo="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],mo={f:function(t){return yo&&"Window"===E(t)?function(t){try{return go(t)}catch(t){return vo(yo)}}(t):go(k(t))}},bo=a(function(){if("function"==typeof ArrayBuffer){var t=new ArrayBuffer(8);Object.isExtensible(t)&&Object.defineProperty(t,"a",{value:8})}}),wo=Object.isExtensible,So=a(function(){wo(1)})||bo?function(t){return!!M(t)&&(!bo||"ArrayBuffer"!==E(t))&&(!wo||wo(t))}:wo,Eo=!a(function(){return Object.isExtensible(Object.preventExtensions({}))}),Oo=e(function(t){var e=Ct.f,r=!1,n=lt("meta"),o=0,i=function(t){e(t,n,{value:{objectID:"O"+o++,weakData:{}}})},a=t.exports={enable:function(){a.enable=function(){},r=!0;var t=Oe.f,e=b([].splice),o={};o[n]=1,t(o).length&&(Oe.f=function(r){for(var o=t(r),i=0,a=o.length;ii;i++)if((u=y(t[i]))&&U(Po,u))return u;return new Ro(!1)}n=Dn(t,o)}for(s=h?t.next:n.next;!(c=f(s,n)).done;){try{u=y(c.value)}catch(t){Tn(n,"throw",t)}if("object"==typeof u&&u&&U(Po,u))return u}return new Ro(!1)},jo=TypeError,ko=function(t,e){if(U(e,t))return t;throw new jo("Incorrect invocation")},Io=function(t,e,r){var n,o;return dn&&T(n=e.constructor)&&n!==r&&M(o=n.prototype)&&o!==r.prototype&&dn(t,o),t},To=function(t,e,r){var n=-1!==t.indexOf("Map"),o=-1!==t.indexOf("Weak"),u=n?"set":"add",s=i[t],c=s&&s.prototype,f=s,l={},h=function(t){var e=b(c[t]);ie(c,t,"add"===t?function(t){return e(this,0===t?0:t),this}:"delete"===t?function(t){return!(o&&!M(t))&&e(this,0===t?0:t)}:"get"===t?function(t){return o&&!M(t)?void 0:e(this,0===t?0:t)}:"has"===t?function(t){return!(o&&!M(t))&&e(this,0===t?0:t)}:function(t,r){return e(this,0===t?0:t,r),this})};if(Ue(t,!T(s)||!(o||c.forEach&&!a(function(){(new s).entries().next()}))))f=r.getConstructor(e,t,n,u),Oo.enable();else if(Ue(t,!0)){var p=new f,v=p[u](o?{}:-0,1)!==p,d=a(function(){p.has(1)}),g=Gn(function(t){new s(t)}),y=!o&&a(function(){for(var t=new s,e=5;e--;)t[u](e,e);return!t.has(-0)});g||((f=e(function(t,e){ko(t,c);var r=Io(new s,t,f);return P(e)||Ao(e,r[u],{that:r,AS_ENTRIES:n}),r})).prototype=c,c.constructor=f),(d||y)&&(h("delete"),h("has"),n&&h("get")),(y||v)&&h(u),o&&c.clear&&delete c.clear}return l[t]=f,Ce({global:!0,constructor:!0,forced:f!==s},l),an(f,t),o||r.setStrong(f,t,n),f},Mo=function(t,e,r){for(var n in e)ie(t,n,e[n],r);return t},Lo=dt("species"),Uo=function(t){var e=L(t);u&&e&&!e[Lo]&&so(e,Lo,{configurable:!0,get:function(){return this}})},No=Oo.fastKey,Co=ne.set,_o=ne.getterFor,Fo={getConstructor:function(t,e,r,n){var o=t(function(t,o){ko(t,i),Co(t,{type:e,index:Ve(null),first:null,last:null,size:0}),u||(t.size=0),P(o)||Ao(o,t[n],{that:t,AS_ENTRIES:r})}),i=o.prototype,a=_o(e),s=function(t,e,r){var n,o,i=a(t),s=c(t,e);return s?s.value=r:(i.last=s={index:o=No(e,!0),key:e,value:r,previous:n=i.last,next:null,removed:!1},i.first||(i.first=s),n&&(n.next=s),u?i.size++:t.size++,"F"!==o&&(i.index[o]=s)),t},c=function(t,e){var r,n=a(t),o=No(e);if("F"!==o)return n.index[o];for(r=n.first;r;r=r.next)if(r.key===e)return r};return Mo(i,{clear:function(){for(var t=a(this),e=t.first;e;)e.removed=!0,e.previous&&(e.previous=e.previous.next=null),e=e.next;t.first=t.last=null,t.index=Ve(null),u?t.size=0:this.size=0},delete:function(t){var e=this,r=a(e),n=c(e,t);if(n){var o=n.next,i=n.previous;delete r.index[n.index],n.removed=!0,i&&(i.next=o),o&&(o.previous=i),r.first===n&&(r.first=o),r.last===n&&(r.last=i),u?r.size--:e.size--}return!!n},forEach:function(t){for(var e,r=a(this),n=ar(t,arguments.length>1?arguments[1]:void 0);e=e?e.next:r.first;)for(n(e.value,e.key,this);e&&e.removed;)e=e.previous},has:function(t){return!!c(this,t)}}),Mo(i,r?{get:function(t){var e=c(this,t);return e&&e.value},set:function(t,e){return s(this,0===t?0:t,e)}}:{add:function(t){return s(this,t=0===t?0:t,t)}}),u&&so(i,"size",{configurable:!0,get:function(){return a(this).size}}),o},setStrong:function(t,e,r){var n=e+" Iterator",o=_o(e),i=_o(n);Rn(t,e,function(t,e){Co(this,{type:n,target:t,state:o(t),kind:e,last:null})},function(){for(var t=i(this),e=t.kind,r=t.last;r&&r.removed;)r=r.previous;return t.target&&(t.last=r=r?r.next:t.state.first)?Pn("keys"===e?r.key:"values"===e?r.value:[r.key,r.value],!1):(t.target=null,Pn(void 0,!0))},r?"entries":"values",!r,!0),Uo(e)}};To("Map",function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},Fo);var Bo=Map.prototype,Do={Map:Map,set:b(Bo.set),get:b(Bo.get),has:b(Bo.has),remove:b(Bo.delete),proto:Bo},zo=Do.Map,Wo=Do.has,qo=Do.get,Ho=Do.set,$o=b([].push),Ko=a(function(){return 1!==zo.groupBy("ab",function(t){return t}).get("a").length});Ce({target:"Map",stat:!0,forced:Ko},{groupBy:function(t,e){j(t),J(e);var r=new zo,n=0;return Ao(t,function(t){var o=e(t,n++);Wo(r,o)?$o(qo(r,o),t):Ho(r,o,[t])}),r}});var Go={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Vo=Et("span").classList,Yo=Vo&&Vo.constructor&&Vo.constructor.prototype,Xo=Yo===Object.prototype?void 0:Yo,Jo=dt("iterator"),Qo=ro.values,Zo=function(t,e){if(t){if(t[Jo]!==Qo)try{_t(t,Jo,Qo)}catch(e){t[Jo]=Qo}if(an(t,e,!0),Go[e])for(var r in ro)if(t[r]!==ro[r])try{_t(t,r,ro[r])}catch(e){t[r]=ro[r]}}};for(var ti in Go)Zo(i[ti]&&i[ti].prototype,ti);Zo(Xo,"DOMTokenList");var ei=function(t,e,r){return function(n){var o=it(n),i=arguments.length,a=i>1?arguments[1]:void 0,u=void 0!==a,s=u?ar(a,i>2?arguments[2]:void 0):void 0,c=new t,f=0;return Ao(o,function(t){var n=u?s(t,f++):t;r?e(c,kt(n)[0],n[1]):e(c,n)}),c}};Ce({target:"Map",stat:!0,forced:!0},{from:ei(Do.Map,Do.set,!0)});var ri=function(t,e,r){return function(){for(var n=new t,o=arguments.length,i=0;i1?arguments[1]:void 0);return!1!==di(e,function(t,n){if(!r(t,n,e))return!1},!0)}});var gi=Do.Map,yi=Do.set;Ce({target:"Map",proto:!0,real:!0,forced:!0},{filter:function(t){var e=oi(this),r=ar(t,arguments.length>1?arguments[1]:void 0),n=new gi;return di(e,function(t,o){r(t,o,e)&&yi(n,o,t)}),n}}),Ce({target:"Map",proto:!0,real:!0,forced:!0},{find:function(t){var e=oi(this),r=ar(t,arguments.length>1?arguments[1]:void 0),n=di(e,function(t,n){if(r(t,n,e))return{value:t}},!0);return n&&n.value}}),Ce({target:"Map",proto:!0,real:!0,forced:!0},{findKey:function(t){var e=oi(this),r=ar(t,arguments.length>1?arguments[1]:void 0),n=di(e,function(t,n){if(r(t,n,e))return{key:n}},!0);return n&&n.key}}),Ce({target:"Map",proto:!0,real:!0,forced:!0},{includes:function(t){return!0===di(oi(this),function(e){if((r=e)===(n=t)||r!=r&&n!=n)return!0;var r,n},!0)}});var mi=Do.Map;Ce({target:"Map",stat:!0,forced:!0},{keyBy:function(t,e){var r=new(T(this)?this:mi);J(e);var n=J(r.set);return Ao(t,function(t){f(n,r,e(t),t)}),r}}),Ce({target:"Map",proto:!0,real:!0,forced:!0},{keyOf:function(t){var e=di(oi(this),function(e,r){if(e===t)return{key:r}},!0);return e&&e.key}});var bi=Do.Map,wi=Do.set;Ce({target:"Map",proto:!0,real:!0,forced:!0},{mapKeys:function(t){var e=oi(this),r=ar(t,arguments.length>1?arguments[1]:void 0),n=new bi;return di(e,function(t,o){wi(n,r(t,o,e),t)}),n}});var Si=Do.Map,Ei=Do.set;Ce({target:"Map",proto:!0,real:!0,forced:!0},{mapValues:function(t){var e=oi(this),r=ar(t,arguments.length>1?arguments[1]:void 0),n=new Si;return di(e,function(t,o){Ei(n,o,r(t,o,e))}),n}});var Oi=Do.set;Ce({target:"Map",proto:!0,real:!0,arity:1,forced:!0},{merge:function(t){for(var e=oi(this),r=arguments.length,n=0;n1?arguments[1]:void 0);return!0===di(e,function(t,n){if(r(t,n,e))return!0},!0)}});var Ri=TypeError,Pi=Do.get,Ai=Do.has,ji=Do.set;Ce({target:"Map",proto:!0,real:!0,forced:!0},{update:function(t,e){var r=oi(this),n=arguments.length;J(e);var o=Ai(r,t);if(!o&&n<3)throw new Ri("Updating absent value");var i=o?Pi(r,t):J(n>2?arguments[2]:void 0)(t,r);return ji(r,t,e(i,t,r)),r}});var ki=TypeError,Ii=function(t,e){var r,n=kt(this),o=J(n.get),i=J(n.has),a=J(n.set),u=arguments.length>2?arguments[2]:void 0;if(!T(e)&&!T(u))throw new ki("At least one callback required");return f(i,n,t)?(r=f(o,n,t),T(e)&&(r=e(r),f(a,n,t,r))):T(u)&&(r=u(),f(a,n,t,r)),r};Ce({target:"Map",proto:!0,real:!0,forced:!0},{upsert:Ii}),Ce({target:"Map",proto:!0,real:!0,name:"upsert",forced:!0},{updateOrInsert:Ii});var Ti=b(1..valueOf),Mi="\t\n\v\f\r                 \u2028\u2029\ufeff",Li=b("".replace),Ui=RegExp("^["+Mi+"]+"),Ni=RegExp("(^|[^"+Mi+"])["+Mi+"]+$"),Ci=function(t){return function(e){var r=Wr(j(e));return 1&t&&(r=Li(r,Ui,"")),2&t&&(r=Li(r,Ni,"$1")),r}},_i={start:Ci(1),end:Ci(2),trim:Ci(3)},Fi=Oe.f,Bi=Rt.f,Di=Ct.f,zi=_i.trim,Wi="Number",qi=i[Wi],Hi=qi.prototype,$i=i.TypeError,Ki=b("".slice),Gi=b("".charCodeAt),Vi=Ue(Wi,!qi(" 0o1")||!qi("0b1")||qi("+0x1")),Yi=function(t){var e,r=arguments.length<1?0:qi(function(t){var e=mt(t,"number");return"bigint"==typeof e?e:function(t){var e,r,n,o,i,a,u,s,c=mt(t,"number");if(G(c))throw new $i("Cannot convert a Symbol value to a number");if("string"==typeof c&&c.length>2)if(c=zi(c),43===(e=Gi(c,0))||45===e){if(88===(r=Gi(c,2))||120===r)return NaN}else if(48===e){switch(Gi(c,1)){case 66:case 98:n=2,o=49;break;case 79:case 111:n=8,o=55;break;default:return+c}for(a=(i=Ki(c,2)).length,u=0;uo)return NaN;return parseInt(i,n)}return+c}(e)}(t));return U(Hi,e=this)&&a(function(){Ti(e)})?Io(Object(r),this,Yi):r};Yi.prototype=Hi,Vi&&(Hi.constructor=Yi),Ce({global:!0,constructor:!0,wrap:!0,forced:Vi},{Number:Yi}),Vi&&function(t,e){for(var r,n=u?Fi(e):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),o=0;n.length>o;o++)ut(e,r=n[o])&&!ut(t,r)&&Di(t,r,Bi(e,r))}(Yn[Wi],qi),Ce({target:"Number",stat:!0,nonConfigurable:!0,nonWritable:!0},{EPSILON:Math.pow(2,-52)});var Xi=i.isFinite;Ce({target:"Number",stat:!0},{isFinite:Number.isFinite||function(t){return"number"==typeof t&&Xi(t)}});var Ji=Math.floor,Qi=Number.isInteger||function(t){return!M(t)&&isFinite(t)&&Ji(t)===t};Ce({target:"Number",stat:!0},{isInteger:Qi}),Ce({target:"Number",stat:!0},{isNaN:function(t){return t!=t}});var Zi=Math.abs;Ce({target:"Number",stat:!0},{isSafeInteger:function(t){return Qi(t)&&Zi(t)<=9007199254740991}}),Ce({target:"Number",stat:!0,nonConfigurable:!0,nonWritable:!0},{MAX_SAFE_INTEGER:9007199254740991}),Ce({target:"Number",stat:!0,nonConfigurable:!0,nonWritable:!0},{MIN_SAFE_INTEGER:-9007199254740991});var ta=_i.trim,ea=b("".charAt),ra=i.parseFloat,na=i.Symbol,oa=na&&na.iterator,ia=1/ra(Mi+"-0")!=-Infinity||oa&&!a(function(){ra(Object(oa))})?function(t){var e=ta(Wr(t)),r=ra(e);return 0===r&&"-"===ea(e,0)?-0:r}:ra;Ce({target:"Number",stat:!0,forced:Number.parseFloat!==ia},{parseFloat:ia});var aa=_i.trim,ua=i.parseInt,sa=i.Symbol,ca=sa&&sa.iterator,fa=/^[+-]?0x/i,la=b(fa.exec),ha=8!==ua(Mi+"08")||22!==ua(Mi+"0x16")||ca&&!a(function(){ua(Object(ca))})?function(t,e){var r=aa(Wr(t));return ua(r,e>>>0||(la(fa,r)?16:10))}:ua;Ce({target:"Number",stat:!0,forced:Number.parseInt!==ha},{parseInt:ha});var pa=b(v.f),va=b([].push),da=u&&a(function(){var t=Object.create(null);return t[2]=2,!pa(t,2)}),ga=function(t){return function(e){for(var r,n=k(e),o=_e(n),i=da&&null===Qr(n),a=o.length,s=0,c=[];a>s;)r=o[s++],u&&!(i?r in n:pa(n,r))||va(c,t?[r,n[r]]:n[r]);return c}},ya={entries:ga(!0),values:ga(!1)},ma=ya.entries;Ce({target:"Object",stat:!0},{entries:function(t){return ma(t)}}),Ce({target:"Object",stat:!0,sham:!u},{getOwnPropertyDescriptors:function(t){for(var e,r,n=k(t),o=Rt.f,i=Pe(n),a={},u=0;i.length>u;)void 0!==(r=o(n,e=i[u++]))&&Cn(a,e,r);return a}});var ba=a(function(){_e(1)});Ce({target:"Object",stat:!0,forced:ba},{keys:function(t){return _e(it(t))}});var wa=Object.is||function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e};Ce({target:"Object",stat:!0},{is:wa});var Sa=ya.values;Ce({target:"Object",stat:!0},{values:function(t){return Sa(t)}}),Ce({target:"Object",stat:!0},{hasOwn:ut});var Ea=Function.prototype,Oa=Ea.apply,xa=Ea.call,Ra="object"==typeof Reflect&&Reflect.apply||(s?xa.bind(Oa):function(){return xa.apply(Oa,arguments)}),Pa=!a(function(){Reflect.apply(function(){})});Ce({target:"Reflect",stat:!0,forced:Pa},{apply:function(t,e,r){return Ra(J(t),e,kt(r))}});var Aa=Function,ja=b([].concat),ka=b([].join),Ia={},Ta=s?Aa.bind:function(t){var e=J(this),r=e.prototype,n=vo(arguments,1),o=function(){var r=ja(n,vo(arguments));return this instanceof o?function(t,e,r){if(!ut(Ia,e)){for(var n=[],o=0;ob)","g");return"b"!==t.exec("b").groups.a||"bc"!=="b".replace(t,"$c")}),gs=Oe.f,ys=ne.enforce,ms=dt("match"),bs=i.RegExp,ws=bs.prototype,Ss=i.SyntaxError,Es=b(ws.exec),Os=b("".charAt),xs=b("".replace),Rs=b("".indexOf),Ps=b("".slice),As=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,js=/a/g,ks=/a/g,Is=new bs(js)!==js,Ts=cs.MISSED_STICKY,Ms=cs.UNSUPPORTED_Y,Ls=u&&(!Is||Ts||ps||ds||a(function(){return ks[ms]=!1,bs(js)!==js||bs(ks)===ks||"/a/i"!==String(bs(js,"i"))}));if(Ue("RegExp",Ls)){for(var Us=function(t,e){var r,n,o,i,a,u,s=U(ws,this),c=es(t),f=void 0===e,l=[],h=t;if(!s&&c&&f&&t.constructor===Us)return t;if((c||U(ws,t))&&(t=t.source,f&&(e=os(h))),t=void 0===t?"":Wr(t),e=void 0===e?"":Wr(e),h=t,ps&&"dotAll"in js&&(n=!!e&&Rs(e,"s")>-1)&&(e=xs(e,/s/g,"")),r=e,Ts&&"sticky"in js&&(o=!!e&&Rs(e,"y")>-1)&&Ms&&(e=xs(e,/y/g,"")),ds&&(i=function(t){for(var e,r=t.length,n=0,o="",i=[],a=Ve(null),u=!1,s=!1,c=0,f="";n<=r;n++){if("\\"===(e=Os(t,n)))e+=Os(t,++n);else if("]"===e)u=!1;else if(!u)switch(!0){case"["===e:u=!0;break;case"("===e:if(o+=e,"?:"===Ps(t,n+1,n+3))continue;Es(As,Ps(t,n+1))&&(n+=2,s=!0),c++;continue;case">"===e&&s:if(""===f||ut(a,f))throw new Ss("Invalid capture group name");a[f]=!0,i[i.length]=[f,c],s=!1,f="";continue}s?f+=e:o+=e}return[o,i]}(t),t=i[0],l=i[1]),a=Io(bs(t,e),s?this:ws,Us),(n||o||l.length)&&(u=ys(a),n&&(u.dotAll=!0,u.raw=Us(function(t){for(var e,r=t.length,n=0,o="",i=!1;n<=r;n++)"\\"!==(e=Os(t,n))?i||"."!==e?("["===e?i=!0:"]"===e&&(i=!1),o+=e):o+="[\\s\\S]":o+=e+Os(t,++n);return o}(t),r)),o&&(u.sticky=!0),l.length&&(u.groups=l)),t!==h)try{_t(a,"source",""===h?"(?:)":h)}catch(t){}return a},Ns=gs(bs),Cs=0;Ns.length>Cs;)ls(Us,bs,Ns[Cs++]);ws.constructor=Us,Us.prototype=ws,ie(i,"RegExp",Us,{constructor:!0})}Uo("RegExp");var _s=zt.PROPER,Fs="toString",Bs=RegExp.prototype,Ds=Bs[Fs];(a(function(){return"/a/b"!==Ds.call({source:"a",flags:"b"})})||_s&&Ds.name!==Fs)&&ie(Bs,Fs,function(){var t=kt(this);return"/"+Wr(t.source)+"/"+Wr(os(t))},{unsafe:!0});var zs=ne.get,Ws=RegExp.prototype,qs=TypeError;u&&ps&&so(Ws,"dotAll",{configurable:!0,get:function(){if(this!==Ws){if("RegExp"===E(this))return!!zs(this).dotAll;throw new qs("Incompatible receiver, RegExp required")}}});var Hs=ne.get,$s=nt("native-string-replace",String.prototype.replace),Ks=RegExp.prototype.exec,Gs=Ks,Vs=b("".charAt),Ys=b("".indexOf),Xs=b("".replace),Js=b("".slice),Qs=function(){var t=/a/,e=/b*/g;return f(Ks,t,"a"),f(Ks,e,"a"),0!==t.lastIndex||0!==e.lastIndex}(),Zs=cs.BROKEN_CARET,tc=void 0!==/()??/.exec("")[1];(Qs||tc||Zs||ps||ds)&&(Gs=function(t){var e,r,n,o,i,a,u,s=this,c=Hs(s),l=Wr(t),h=c.raw;if(h)return h.lastIndex=s.lastIndex,e=f(Gs,h,l),s.lastIndex=h.lastIndex,e;var p=c.groups,v=Zs&&s.sticky,d=f(rs,s),g=s.source,y=0,m=l;if(v&&(d=Xs(d,"y",""),-1===Ys(d,"g")&&(d+="g"),m=Js(l,s.lastIndex),s.lastIndex>0&&(!s.multiline||s.multiline&&"\n"!==Vs(l,s.lastIndex-1))&&(g="(?: "+g+")",m=" "+m,y++),r=new RegExp("^(?:"+g+")",d)),tc&&(r=new RegExp("^"+g+"$(?!\\s)",d)),Qs&&(n=s.lastIndex),o=f(Ks,v?r:s,m),v?o?(o.input=Js(o.input,y),o[0]=Js(o[0],y),o.index=s.lastIndex,s.lastIndex+=o[0].length):s.lastIndex=0:Qs&&o&&(s.lastIndex=s.global?o.index+o[0].length:n),tc&&o&&o.length>1&&f($s,o[0],r,function(){for(i=1;i]*>)/g,Oc=/\$([$&'`]|\d{1,2})/g,xc=function(t,e,r,n,o,i){var a=r+t.length,u=n.length,s=Oc;return void 0!==o&&(o=it(o),s=Ec),wc(i,s,function(i,s){var c;switch(bc(s,0)){case"$":return"$";case"&":return t;case"`":return Sc(e,0,r);case"'":return Sc(e,a);case"<":c=o[Sc(s,1,-1)];break;default:var f=+s;if(0===f)return i;if(f>u){var l=mc(f/10);return 0===l?i:l<=u?void 0===n[l-1]?bc(s,1):n[l-1]+bc(s,1):i}c=n[f-1]}return void 0===c?"":c})},Rc=dt("replace"),Pc=Math.max,Ac=Math.min,jc=b([].concat),kc=b([].push),Ic=b("".indexOf),Tc=b("".slice),Mc="$0"==="a".replace(/./,"$0"),Lc=!!/./[Rc]&&""===/./[Rc]("a","$0"),Uc=!a(function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$")});pc("replace",function(t,e,r){var n=Lc?"$":"$0";return[function(t,r){var n=j(this),o=P(t)?void 0:Q(t,Rc);return o?f(o,t,n,r):f(e,Wr(n),t,r)},function(t,o){var i=kt(this),a=Wr(t);if("string"==typeof o&&-1===Ic(o,n)&&-1===Ic(o,"$<")){var u=r(e,i,a,o);if(u.done)return u.value}var s=T(o);s||(o=Wr(o));var c,f=i.global;f&&(c=i.unicode,i.lastIndex=0);for(var l,h=[];null!==(l=yc(i,a))&&(kc(h,l),f);)""===Wr(l[0])&&(i.lastIndex=dc(a,ve(i.lastIndex),c));for(var p,v="",d=0,g=0;g=d&&(v+=Tc(a,d,b)+y,d=b+m.length)}return v+Tc(a,d)}]},!Uc||!Mc||Lc),pc("search",function(t,e,r){return[function(e){var r=j(this),n=P(e)?void 0:Q(e,t);return n?f(n,e,r):new RegExp(e)[t](Wr(r))},function(t){var n=kt(this),o=Wr(t),i=r(e,n,o);if(i.done)return i.value;var a=n.lastIndex;wa(a,0)||(n.lastIndex=0);var u=yc(n,o);return wa(n.lastIndex,a)||(n.lastIndex=a),null===u?-1:u.index}]});var Nc=dt("species"),Cc=function(t,e){var r,n=kt(t).constructor;return void 0===n||P(r=kt(n)[Nc])?e:La(r)},_c=cs.UNSUPPORTED_Y,Fc=Math.min,Bc=b([].push),Dc=b("".slice),zc=!a(function(){var t=/(?:)/,e=t.exec;t.exec=function(){return e.apply(this,arguments)};var r="ab".split(t);return 2!==r.length||"a"!==r[0]||"b"!==r[1]}),Wc="c"==="abbc".split(/(b)*/)[1]||4!=="test".split(/(?:)/,-1).length||2!=="ab".split(/(?:ab)*/).length||4!==".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length;pc("split",function(t,e,r){var n="0".split(void 0,0).length?function(t,r){return void 0===t&&0===r?[]:f(e,this,t,r)}:e;return[function(e,r){var o=j(this),i=P(e)?void 0:Q(e,t);return i?f(i,e,o,r):f(n,Wr(o),e,r)},function(t,o){var i=kt(this),a=Wr(t);if(!Wc){var u=r(n,i,a,o,n!==e);if(u.done)return u.value}var s=Cc(i,RegExp),c=i.unicode,f=new s(_c?"^(?:"+i.source+")":i,(i.ignoreCase?"i":"")+(i.multiline?"m":"")+(i.unicode?"u":"")+(_c?"g":"y")),l=void 0===o?4294967295:o>>>0;if(0===l)return[];if(0===a.length)return null===yc(f,a)?[a]:[];for(var h=0,p=0,v=[];p0;(n>>>=1)&&(e+=e))1&n&&(r+=e);return r},Kc=b($c),Gc=b("".slice),Vc=Math.ceil,Yc=function(t){return function(e,r,n){var o,i,a=Wr(j(e)),u=ve(r),s=a.length,c=void 0===n?" ":Wr(n);return u<=s||""===c?a:((i=Kc(c,Vc((o=u-s)/c.length))).length>o&&(i=Gc(i,0,o)),t?a+i:i+a)}},Xc={start:Yc(!1),end:Yc(!0)},Jc=Xc.start,Qc=Array,Zc=RegExp.escape,tf=b("".charAt),ef=b("".charCodeAt),rf=b(1.1.toString),nf=b([].join),of=/^[0-9a-z]/i,af=/^[$()*+./?[\\\]^{|}]/,uf=RegExp("^[!\"#%&',\\-:;<=>@`~"+Mi+"]"),sf=b(of.exec),cf={"\t":"t","\n":"n","\v":"v","\f":"f","\r":"r"},ff=function(t){var e=rf(ef(t,0),16);return e.length<3?"\\x"+Jc(e,2,"0"):"\\u"+Jc(e,4,"0")},lf=!Zc||"\\x61b"!==Zc("ab");Ce({target:"RegExp",stat:!0,forced:lf},{escape:function(t){!function(t){if("string"==typeof t)return t;throw new qc("Argument is not a string")}(t);for(var e=t.length,r=Qc(e),n=0;n=56320||n+1>=e||56320!=(64512&ef(t,n+1))?r[n]=ff(o):(r[n]=o,r[++n]=tf(t,n))}}return nf(r,"")}}),To("Set",function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},Fo);var hf=Set.prototype,pf={Set:Set,add:b(hf.add),has:b(hf.has),remove:b(hf.delete),proto:hf},vf=pf.has,df=function(t){return vf(t),t},gf=pf.Set,yf=pf.proto,mf=b(yf.forEach),bf=b(yf.keys),wf=bf(new gf).next,Sf=function(t,e,r){return r?ci({iterator:bf(t),next:wf},e):mf(t,e)},Ef=pf.Set,Of=pf.add,xf=function(t){var e=new Ef;return Sf(t,function(t){Of(e,t)}),e},Rf=ln(pf.proto,"size","get")||function(t){return t.size},Pf="Invalid size",Af=RangeError,jf=TypeError,kf=Math.max,If=function(t,e){this.set=t,this.size=kf(e,0),this.has=J(t.has),this.keys=J(t.keys)};If.prototype={getIterator:function(){return{iterator:t=kt(f(this.keys,this.set)),next:t.next,done:!1};var t},includes:function(t){return f(this.has,this.set,t)}};var Tf=function(t){kt(t);var e=+t.size;if(e!=e)throw new jf(Pf);var r=ce(e);if(r<0)throw new Af(Pf);return new If(t,r)},Mf=pf.has,Lf=pf.remove,Uf=function(t){var e=df(this),r=Tf(t),n=xf(e);return Rf(e)<=r.size?Sf(e,function(t){r.includes(t)&&Lf(n,t)}):ci(r.getIterator(),function(t){Mf(e,t)&&Lf(n,t)}),n},Nf=function(t){return{size:t,has:function(){return!1},keys:function(){return{next:function(){return{done:!0}}}}}},Cf=function(t){var e=L("Set");try{(new e)[t](Nf(0));try{return(new e)[t](Nf(-1)),!1}catch(t){return!0}}catch(t){return!1}};Ce({target:"Set",proto:!0,real:!0,forced:!Cf("difference")},{difference:Uf});var _f=pf.Set,Ff=pf.add,Bf=pf.has,Df=function(t){var e=df(this),r=Tf(t),n=new _f;return Rf(e)>r.size?ci(r.getIterator(),function(t){Bf(e,t)&&Ff(n,t)}):Sf(e,function(t){r.includes(t)&&Ff(n,t)}),n},zf=!Cf("intersection")||a(function(){return"3,2"!==String(Array.from(new Set([1,2,3]).intersection(new Set([3,2]))))});Ce({target:"Set",proto:!0,real:!0,forced:zf},{intersection:Df});var Wf=pf.has,qf=function(t){var e=df(this),r=Tf(t);if(Rf(e)<=r.size)return!1!==Sf(e,function(t){if(r.includes(t))return!1},!0);var n=r.getIterator();return!1!==ci(n,function(t){if(Wf(e,t))return Tn(n,"normal",!1)})};Ce({target:"Set",proto:!0,real:!0,forced:!Cf("isDisjointFrom")},{isDisjointFrom:qf});var Hf=function(t){var e=df(this),r=Tf(t);return!(Rf(e)>r.size)&&!1!==Sf(e,function(t){if(!r.includes(t))return!1},!0)};Ce({target:"Set",proto:!0,real:!0,forced:!Cf("isSubsetOf")},{isSubsetOf:Hf});var $f=pf.has,Kf=function(t){var e=df(this),r=Tf(t);if(Rf(e)1?arguments[1]:void 0);return!1!==Sf(e,function(t){if(!r(t,t,e))return!1},!0)}});var el=dt("iterator"),rl=Object,nl=L("Set"),ol=function(t){return function(t){return M(t)&&"number"==typeof t.size&&T(t.has)&&T(t.keys)}(t)?t:function(t){if(P(t))return!1;var e=rl(t);return void 0!==e[el]||"@@iterator"in e||ut(un,pr(e))}(t)?new nl(t):t};Ce({target:"Set",proto:!0,real:!0,forced:!0},{difference:function(t){return f(Uf,this,ol(t))}});var il=pf.Set,al=pf.add;Ce({target:"Set",proto:!0,real:!0,forced:!0},{filter:function(t){var e=df(this),r=ar(t,arguments.length>1?arguments[1]:void 0),n=new il;return Sf(e,function(t){r(t,t,e)&&al(n,t)}),n}}),Ce({target:"Set",proto:!0,real:!0,forced:!0},{find:function(t){var e=df(this),r=ar(t,arguments.length>1?arguments[1]:void 0),n=Sf(e,function(t){if(r(t,t,e))return{value:t}},!0);return n&&n.value}}),Ce({target:"Set",proto:!0,real:!0,forced:!0},{intersection:function(t){return f(Df,this,ol(t))}}),Ce({target:"Set",proto:!0,real:!0,forced:!0},{isDisjointFrom:function(t){return f(qf,this,ol(t))}}),Ce({target:"Set",proto:!0,real:!0,forced:!0},{isSubsetOf:function(t){return f(Hf,this,ol(t))}}),Ce({target:"Set",proto:!0,real:!0,forced:!0},{isSupersetOf:function(t){return f(Kf,this,ol(t))}});var ul=b([].join),sl=b([].push);Ce({target:"Set",proto:!0,real:!0,forced:!0},{join:function(t){var e=df(this),r=void 0===t?",":Wr(t),n=[];return Sf(e,function(t){sl(n,t)}),ul(n,r)}});var cl=pf.Set,fl=pf.add;Ce({target:"Set",proto:!0,real:!0,forced:!0},{map:function(t){var e=df(this),r=ar(t,arguments.length>1?arguments[1]:void 0),n=new cl;return Sf(e,function(t){fl(n,r(t,t,e))}),n}});var ll=TypeError;Ce({target:"Set",proto:!0,real:!0,forced:!0},{reduce:function(t){var e=df(this),r=arguments.length<2,n=r?void 0:arguments[1];if(J(t),Sf(e,function(o){r?(r=!1,n=o):n=t(n,o,o,e)}),r)throw new ll("Reduce of empty set with no initial value");return n}}),Ce({target:"Set",proto:!0,real:!0,forced:!0},{some:function(t){var e=df(this),r=ar(t,arguments.length>1?arguments[1]:void 0);return!0===Sf(e,function(t){if(r(t,t,e))return!0},!0)}}),Ce({target:"Set",proto:!0,real:!0,forced:!0},{symmetricDifference:function(t){return f(Xf,this,ol(t))}}),Ce({target:"Set",proto:!0,real:!0,forced:!0},{union:function(t){return f(Qf,this,ol(t))}});var hl=dt("species"),pl=dt("isConcatSpreadable"),vl=W>=51||!a(function(){var t=[];return t[pl]=!1,t.concat()[0]!==t}),dl=function(t){if(!M(t))return!1;var e=t[pl];return void 0!==e?!!e:ur(t)},gl=!(vl&&(W>=51||!a(function(){var t=[];return(t.constructor={})[hl]=function(){return{foo:1}},1!==t.concat(Boolean).foo})));Ce({target:"Array",proto:!0,arity:1,forced:gl},{concat:function(t){var e,r,n,o,i,a=it(this),u=xr(a,0),s=0;for(e=-1,n=arguments.length;e1?arguments[1]:void 0,n=e.length,o=void 0===r?n:ip(ve(r),n),i=Wr(t);return op(e,o-i.length,o)===i}}),Ze("String","endsWith");var sp=RangeError,cp=String.fromCharCode,fp=String.fromCodePoint,lp=b([].join);Ce({target:"String",stat:!0,arity:1,forced:!!fp&&1!==fp.length},{fromCodePoint:function(t){for(var e,r=[],n=arguments.length,o=0;n>o;){if(e=+arguments[o++],he(e,1114111)!==e)throw new sp(e+" is not a valid code point");r[o]=e<65536?cp(e):cp(55296+((e-=65536)>>10),e%1024+56320)}return lp(r,"")}});var hp=b("".indexOf);Ce({target:"String",proto:!0,forced:!rp("includes")},{includes:function(t){return!!~hp(Wr(j(this)),Wr(tp(t)),arguments.length>1?arguments[1]:void 0)}}),Ze("String","includes"),b(un.String);var pp=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(_),vp=Xc.start;Ce({target:"String",proto:!0,forced:pp},{padStart:function(t){return vp(this,t,arguments.length>1?arguments[1]:void 0)}}),Ze("String","padStart");var dp=Xc.end;Ce({target:"String",proto:!0,forced:pp},{padEnd:function(t){return dp(this,t,arguments.length>1?arguments[1]:void 0)}}),Ze("String","padEnd");var gp=b([].push),yp=b([].join);Ce({target:"String",stat:!0},{raw:function(t){var e=k(it(t).raw),r=de(e);if(!r)return"";for(var n=arguments.length,o=[],i=0;;){if(gp(o,Wr(e[i++])),i===r)return yp(o,"");i1?arguments[1]:void 0,e.length)),n=Wr(t);return bp(e,r,r+n.length)===n}}),Ze("String","startsWith");var Op=zt.PROPER,xp=function(t){return a(function(){return!!Mi[t]()||"​…᠎"!=="​…᠎"[t]()||Op&&Mi[t].name!==t})},Rp=_i.start,Pp=xp("trimStart")?function(){return Rp(this)}:"".trimStart;Ce({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Pp},{trimLeft:Pp}),Ce({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Pp},{trimStart:Pp}),Ze("String","trimLeft");var Ap=_i.end,jp=xp("trimEnd")?function(){return Ap(this)}:"".trimEnd;Ce({target:"String",proto:!0,name:"trimEnd",forced:"".trimRight!==jp},{trimRight:jp}),Ce({target:"String",proto:!0,name:"trimEnd",forced:"".trimEnd!==jp},{trimEnd:jp}),Ze("String","trimRight");var kp=Object.getOwnPropertyDescriptor,Ip=function(t){if(!u)return i[t];var e=kp(i,t);return e&&e.value},Tp=dt("iterator"),Mp=!a(function(){var t=new URL("b?a=1&b=2&c=3","https://a"),e=t.searchParams,r=new URLSearchParams("a=1&a=2&b=3"),n="";return t.pathname="c%20d",e.forEach(function(t,r){e.delete("b"),n+=r+t}),r.delete("a",2),r.delete("b",void 0),!e.size&&!u||!e.sort||"https://a/c%20d?a=1&c=3"!==t.href||"3"!==e.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!e[Tp]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==n||"x"!==new URL("https://x",void 0).host}),Lp=TypeError,Up=function(t,e){if(t0;)t[o]=t[--o];o!==i++&&(t[o]=n)}else for(var a=Np(r/2),u=Cp(vo(t,0,a),e),s=Cp(vo(t,a),e),c=u.length,f=s.length,l=0,h=0;l0&&0!=(t&r);r>>=1)e++;return e},pv=function(t){var e=null;switch(t.length){case 1:e=t[0];break;case 2:e=(31&t[0])<<6|63&t[1];break;case 3:e=(15&t[0])<<12|(63&t[1])<<6|63&t[2];break;case 4:e=(7&t[0])<<18|(63&t[1])<<12|(63&t[2])<<6|63&t[3]}return e>1114111?null:e},vv=function(t){for(var e=(t=nv(t,cv," ")).length,r="",n=0;ne){r+="%",n++;continue}var i=lv(t,n+1);if(i!=i){r+=o,n++;continue}n+=2;var a=hv(i);if(0===a)o=Jp(i);else{if(1===a||a>4){r+="�",n++;continue}for(var u=[i],s=1;se||"%"!==tv(t,n));){var c=lv(t,n+1);if(c!=c){n+=3;break}if(c>191||c<128)break;rv(u,c),n+=2,s++}if(u.length!==a){r+="�";continue}var f=pv(u);null===f?r+="�":o=Qp(f)}}r+=o,n++}return r},dv=/[!'()~]|%20/g,gv={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},yv=function(t){return gv[t]},mv=function(t){return nv(Xp(t),dv,yv)},bv=fn(function(t,e){zp(this,{type:Dp,target:Wp(t).entries,index:0,kind:e})},Bp,function(){var t=qp(this),e=t.target,r=t.index++;if(!e||r>=e.length)return t.target=null,Pn(void 0,!0);var n=e[r];switch(t.kind){case"keys":return Pn(n.key,!1);case"values":return Pn(n.value,!1)}return Pn([n.key,n.value],!1)},!0),wv=function(t){this.entries=[],this.url=null,void 0!==t&&(M(t)?this.parseObject(t):this.parseQuery("string"==typeof t?"?"===tv(t,0)?uv(t,1):t:Wr(t)))};wv.prototype={type:Bp,bindURL:function(t){this.url=t,this.update()},parseObject:function(t){var e,r,n,o,i,a,u,s=this.entries,c=Fn(t);if(c)for(r=(e=Dn(t,c)).next;!(n=f(r,e)).done;){if(o=Dn(kt(n.value)),(a=f(i=o.next,o)).done||(u=f(i,o)).done||!f(i,o).done)throw new Yp("Expected sequence with length 2");rv(s,{key:Wr(a.value),value:Wr(u.value)})}else for(var l in t)ut(t,l)&&rv(s,{key:l,value:Wr(t[l])})},parseQuery:function(t){if(t)for(var e,r,n=this.entries,o=av(t,"&"),i=0;i0?arguments[0]:void 0));u||(this.size=t.entries.length)},Ev=Sv.prototype;if(Mo(Ev,{append:function(t,e){var r=Wp(this);Up(arguments.length,2),rv(r.entries,{key:Wr(t),value:Wr(e)}),u||this.length++,r.updateURL()},delete:function(t){for(var e=Wp(this),r=Up(arguments.length,1),n=e.entries,o=Wr(t),i=r<2?void 0:arguments[1],a=void 0===i?i:Wr(i),s=0;se.key?1:-1}),t.updateURL()},forEach:function(t){for(var e,r=Wp(this).entries,n=ar(t,arguments.length>1?arguments[1]:void 0),o=0;o1?Rv(arguments[1]):{})}}),T($p)){var Pv=function(t){return ko(this,Gp),new $p(t,arguments.length>1?Rv(arguments[1]):{})};Gp.constructor=Pv,Pv.prototype=Gp,Ce({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Pv})}}var Av={URLSearchParams:Sv,getState:Wp},jv=URLSearchParams,kv=jv.prototype,Iv=b(kv.append),Tv=b(kv.delete),Mv=b(kv.forEach),Lv=b([].push),Uv=new jv("a=1&a=2&b=3");Uv.delete("a",1),Uv.delete("b",void 0),Uv+""!="a=2"&&ie(kv,"delete",function(t){var e=arguments.length,r=e<2?void 0:arguments[1];if(e&&void 0===r)return Tv(this,t);var n=[];Mv(this,function(t,e){Lv(n,{key:e,value:t})}),Up(e,1);for(var o,i=Wr(t),a=Wr(r),u=0,s=0,c=!1,f=n.length;uo;)for(var s,c=R(arguments[o++]),l=i?$v(_e(c),i(c)):_e(c),h=l.length,p=0;h>p;)s=l[p++],u&&!f(a,c,s)||(r[s]=c[s]);return r}:qv,Gv=2147483647,Vv=/[^\0-\u007E]/,Yv=/[.\u3002\uFF0E\uFF61]/g,Xv="Overflow: input needs wider integers to process",Jv=RangeError,Qv=b(Yv.exec),Zv=Math.floor,td=String.fromCharCode,ed=b("".charCodeAt),rd=b([].join),nd=b([].push),od=b("".replace),id=b("".split),ad=b("".toLowerCase),ud=function(t){return t+22+75*(t<26)},sd=function(t,e,r){var n=0;for(t=r?Zv(t/700):t>>1,t+=Zv(t/e);t>455;)t=Zv(t/35),n+=36;return Zv(n+36*t/(t+38))},cd=function(t){var e=[];t=function(t){for(var e=[],r=0,n=t.length;r=55296&&o<=56319&&r=i&&nZv((Gv-a)/l))throw new Jv(Xv);for(a+=(f-i)*l,i=f,r=0;rGv)throw new Jv(Xv);if(n===i){for(var h=a,p=36;;){var v=p<=u?1:p>=u+26?26:p-u;if(h?@[\\\]^|]/,qd=/[\0\t\n\r #/:<>?@[\\\]^|]/,Hd=/^[\u0000-\u0020]+/,$d=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,Kd=/[\t\n\r]/g,Gd=function(t){var e,r,n,o;if("number"==typeof t){for(e=[],r=0;r<4;r++)Td(e,t%256),t=md(t/256);return Ed(e,".")}if("object"==typeof t){for(e="",n=function(t){for(var e=null,r=1,n=null,o=0,i=0;i<8;i++)0!==t[i]?(o>r&&(e=n,r=o),n=null,o=0):(null===n&&(n=i),++o);return o>r?n:e}(t),r=0;r<8;r++)o&&0===t[r]||(o&&(o=!1),n===r?(e+=r?":":"::",o=!0):(e+=Od(t[r],16),r<7&&(e+=":")));return"["+e+"]"}return t},Vd={},Yd=Kv({},Vd,{" ":1,'"':1,"<":1,">":1,"`":1}),Xd=Kv({},Yd,{"#":1,"?":1,"{":1,"}":1}),Jd=Kv({},Xd,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Qd=function(t,e){var r=fd(t,0);return r>32&&r<127&&!ut(e,t)?t:encodeURIComponent(t)},Zd={ftp:21,file:null,http:80,https:443,ws:80,wss:443},tg=function(t,e){var r;return 2===t.length&&Sd(Nd,wd(t,0))&&(":"===(r=wd(t,1))||!e&&"|"===r)},eg=function(t){var e;return t.length>1&&tg(kd(t,0,2))&&(2===t.length||"/"===(e=wd(t,2))||"\\"===e||"?"===e||"#"===e)},rg=function(t){return"."===t||"%2e"===Id(t)},ng={},og={},ig={},ag={},ug={},sg={},cg={},fg={},lg={},hg={},pg={},vg={},dg={},gg={},yg={},mg={},bg={},wg={},Sg={},Eg={},Og={},xg=function(t,e,r){var n,o,i,a=Wr(t);if(e){if(o=this.parse(a))throw new gd(o);this.searchParams=null}else{if(void 0!==r&&(n=new xg(r,!0)),o=this.parse(a,null,n))throw new gd(o);(i=vd(new pd)).bindURL(this),this.searchParams=i}};xg.prototype={type:"URL",parse:function(t,e,r){var n,o,i,a,u,s=this,c=e||ng,f=0,l="",h=!1,p=!1,v=!1;for(t=Wr(t),e||(s.scheme="",s.username="",s.password="",s.host=null,s.port=null,s.path=[],s.query=null,s.fragment=null,s.cannotBeABaseURL=!1,t=Pd(t,Hd,""),t=Pd(t,$d,"$1")),t=Pd(t,Kd,""),n=Wn(t);f<=n.length;){switch(o=n[f],c){case ng:if(!o||!Sd(Nd,o)){if(e)return Md;c=ig;continue}l+=Id(o),c=og;break;case og:if(o&&(Sd(Cd,o)||"+"===o||"-"===o||"."===o))l+=Id(o);else{if(":"!==o){if(e)return Md;l="",c=ig,f=0;continue}if(e&&(s.isSpecial()!==ut(Zd,l)||"file"===l&&(s.includesCredentials()||null!==s.port)||"file"===s.scheme&&!s.host))return;if(s.scheme=l,e)return void(s.isSpecial()&&Zd[s.scheme]===s.port&&(s.port=null));l="","file"===s.scheme?c=gg:s.isSpecial()&&r&&r.scheme===s.scheme?c=ag:s.isSpecial()?c=fg:"/"===n[f+1]?(c=ug,f++):(s.cannotBeABaseURL=!0,Rd(s.path,""),c=Sg)}break;case ig:if(!r||r.cannotBeABaseURL&&"#"!==o)return Md;if(r.cannotBeABaseURL&&"#"===o){s.scheme=r.scheme,s.path=vo(r.path),s.query=r.query,s.fragment="",s.cannotBeABaseURL=!0,c=Og;break}c="file"===r.scheme?gg:sg;continue;case ag:if("/"!==o||"/"!==n[f+1]){c=sg;continue}c=lg,f++;break;case ug:if("/"===o){c=hg;break}c=wg;continue;case sg:if(s.scheme=r.scheme,o===Wv)s.username=r.username,s.password=r.password,s.host=r.host,s.port=r.port,s.path=vo(r.path),s.query=r.query;else if("/"===o||"\\"===o&&s.isSpecial())c=cg;else if("?"===o)s.username=r.username,s.password=r.password,s.host=r.host,s.port=r.port,s.path=vo(r.path),s.query="",c=Eg;else{if("#"!==o){s.username=r.username,s.password=r.password,s.host=r.host,s.port=r.port,s.path=vo(r.path),s.path.length--,c=wg;continue}s.username=r.username,s.password=r.password,s.host=r.host,s.port=r.port,s.path=vo(r.path),s.query=r.query,s.fragment="",c=Og}break;case cg:if(!s.isSpecial()||"/"!==o&&"\\"!==o){if("/"!==o){s.username=r.username,s.password=r.password,s.host=r.host,s.port=r.port,c=wg;continue}c=hg}else c=lg;break;case fg:if(c=lg,"/"!==o||"/"!==wd(l,f+1))continue;f++;break;case lg:if("/"!==o&&"\\"!==o){c=hg;continue}break;case hg:if("@"===o){h&&(l="%40"+l),h=!0,i=Wn(l);for(var d=0;d65535)return Ud;s.port=s.isSpecial()&&m===Zd[s.scheme]?null:m,l=""}if(e)return;c=bg;continue}return Ud}l+=o;break;case gg:if(s.scheme="file","/"===o||"\\"===o)c=yg;else{if(!r||"file"!==r.scheme){c=wg;continue}switch(o){case Wv:s.host=r.host,s.path=vo(r.path),s.query=r.query;break;case"?":s.host=r.host,s.path=vo(r.path),s.query="",c=Eg;break;case"#":s.host=r.host,s.path=vo(r.path),s.query=r.query,s.fragment="",c=Og;break;default:eg(Ed(vo(n,f),""))||(s.host=r.host,s.path=vo(r.path),s.shortenPath()),c=wg;continue}}break;case yg:if("/"===o||"\\"===o){c=mg;break}r&&"file"===r.scheme&&!eg(Ed(vo(n,f),""))&&(tg(r.path[0],!0)?Rd(s.path,r.path[0]):s.host=r.host),c=wg;continue;case mg:if(o===Wv||"/"===o||"\\"===o||"?"===o||"#"===o){if(!e&&tg(l))c=wg;else if(""===l){if(s.host="",e)return;c=bg}else{if(a=s.parseHost(l))return a;if("localhost"===s.host&&(s.host=""),e)return;l="",c=bg}continue}l+=o;break;case bg:if(s.isSpecial()){if(c=wg,"/"!==o&&"\\"!==o)continue}else if(e||"?"!==o)if(e||"#"!==o){if(o!==Wv&&(c=wg,"/"!==o))continue}else s.fragment="",c=Og;else s.query="",c=Eg;break;case wg:if(o===Wv||"/"===o||"\\"===o&&s.isSpecial()||!e&&("?"===o||"#"===o)){if(".."===(u=Id(u=l))||"%2e."===u||".%2e"===u||"%2e%2e"===u?(s.shortenPath(),"/"===o||"\\"===o&&s.isSpecial()||Rd(s.path,"")):rg(l)?"/"===o||"\\"===o&&s.isSpecial()||Rd(s.path,""):("file"===s.scheme&&!s.path.length&&tg(l)&&(s.host&&(s.host=""),l=wd(l,0)+":"),Rd(s.path,l)),l="","file"===s.scheme&&(o===Wv||"?"===o||"#"===o))for(;s.path.length>1&&""===s.path[0];)Ad(s.path);"?"===o?(s.query="",c=Eg):"#"===o&&(s.fragment="",c=Og)}else l+=Qd(o,Xd);break;case Sg:"?"===o?(s.query="",c=Eg):"#"===o?(s.fragment="",c=Og):o!==Wv&&(s.path[0]+=Qd(o,Vd));break;case Eg:e||"#"!==o?o!==Wv&&("'"===o&&s.isSpecial()?s.query+="%27":s.query+="#"===o?"%23":Qd(o,Vd)):(s.fragment="",c=Og);break;case Og:o!==Wv&&(s.fragment+=Qd(o,Yd))}f++}},parseHost:function(t){var e,r,n;if("["===wd(t,0)){if("]"!==wd(t,t.length-1))return Ld;if(e=function(t){var e,r,n,o,i,a,u,s=[0,0,0,0,0,0,0,0],c=0,f=null,l=0,h=function(){return wd(t,l)};if(":"===h()){if(":"!==wd(t,1))return;l+=2,f=++c}for(;h();){if(8===c)return;if(":"!==h()){for(e=r=0;r<4&&Sd(zd,h());)e=16*e+yd(h(),16),l++,r++;if("."===h()){if(0===r)return;if(l-=r,c>6)return;for(n=0;h();){if(o=null,n>0){if(!("."===h()&&n<4))return;l++}if(!Sd(_d,h()))return;for(;Sd(_d,h());){if(i=yd(h(),10),null===o)o=i;else{if(0===o)return;o=10*o+i}if(o>255)return;l++}s[c]=256*s[c]+o,2!=++n&&4!==n||c++}if(4!==n)return;break}if(":"===h()){if(l++,!h())return}else if(h())return;s[c++]=e}else{if(null!==f)return;l++,f=++c}}if(null!==f)for(a=c-f,c=7;0!==c&&a>0;)u=s[c],s[c--]=s[f+a-1],s[f+--a]=u;else if(8!==c)return;return s}(kd(t,1,-1)),!e)return Ld;this.host=e}else if(this.isSpecial()){if(t=function(t){var e,r,n=[],o=id(od(ad(t),Yv,"."),".");for(e=0;e4)return t;for(r=[],n=0;n1&&"0"===wd(o,0)&&(i=Sd(Fd,o)?16:8,o=kd(o,8===i?1:2)),""===o)a=0;else{if(!Sd(10===i?Dd:8===i?Bd:zd,o))return t;a=yd(o,i)}Rd(r,a)}for(n=0;n=bd(256,5-e))return null}else if(a>255)return null;for(u=xd(r),n=0;n1?arguments[1]:void 0,n=ld(e,new xg(t,!1,r));u||(e.href=n.serialize(),e.origin=n.getOrigin(),e.protocol=n.getProtocol(),e.username=n.getUsername(),e.password=n.getPassword(),e.host=n.getHost(),e.hostname=n.getHostname(),e.port=n.getPort(),e.pathname=n.getPathname(),e.search=n.getSearch(),e.searchParams=n.getSearchParams(),e.hash=n.getHash())},Pg=Rg.prototype,Ag=function(t,e){return{get:function(){return hd(this)[t]()},set:e&&function(t){return hd(this)[e](t)},configurable:!0,enumerable:!0}};if(u&&(so(Pg,"href",Ag("serialize","setHref")),so(Pg,"origin",Ag("getOrigin")),so(Pg,"protocol",Ag("getProtocol","setProtocol")),so(Pg,"username",Ag("getUsername","setUsername")),so(Pg,"password",Ag("getPassword","setPassword")),so(Pg,"host",Ag("getHost","setHost")),so(Pg,"hostname",Ag("getHostname","setHostname")),so(Pg,"port",Ag("getPort","setPort")),so(Pg,"pathname",Ag("getPathname","setPathname")),so(Pg,"search",Ag("getSearch","setSearch")),so(Pg,"searchParams",Ag("getSearchParams")),so(Pg,"hash",Ag("getHash","setHash"))),ie(Pg,"toJSON",function(){return hd(this).serialize()},{enumerable:!0}),ie(Pg,"toString",function(){return hd(this).serialize()},{enumerable:!0}),dd){var jg=dd.createObjectURL,kg=dd.revokeObjectURL;jg&&ie(Rg,"createObjectURL",ar(jg,dd)),kg&&ie(Rg,"revokeObjectURL",ar(kg,dd))}an(Rg,"URL"),Ce({global:!0,constructor:!0,forced:!Mp,sham:!u},{URL:Rg});var Ig=L("URL"),Tg=Mp&&a(function(){Ig.canParse()}),Mg=a(function(){return 1!==Ig.canParse.length});Ce({target:"URL",stat:!0,forced:!Tg||Mg},{canParse:function(t){var e=Up(arguments.length,1),r=Wr(t),n=e<2||void 0===arguments[1]?void 0:Wr(arguments[1]);try{return!!new Ig(r,n)}catch(t){return!1}}});var Lg=L("URL");Ce({target:"URL",stat:!0,forced:!Mp},{parse:function(t){var e=Up(arguments.length,1),r=Wr(t),n=e<2||void 0===arguments[1]?void 0:Wr(arguments[1]);try{return new Lg(r,n)}catch(t){return null}}}),Ce({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return f(URL.prototype.toString,this)}});var Ug=WeakMap.prototype,Ng={WeakMap:WeakMap,set:b(Ug.set),get:b(Ug.get),has:b(Ug.has),remove:b(Ug.delete)},Cg=Ng.has,_g=function(t){return Cg(t),t},Fg=Ng.get,Bg=Ng.has,Dg=Ng.set;Ce({target:"WeakMap",proto:!0,real:!0,forced:!0},{emplace:function(t,e){var r,n,o=_g(this);return Bg(o,t)?(r=Fg(o,t),"update"in e&&(r=e.update(r,t,o),Dg(o,t,r)),r):(n=e.insert(t,o),Dg(o,t,n),n)}}),Ce({target:"WeakMap",stat:!0,forced:!0},{from:ei(Ng.WeakMap,Ng.set,!0)}),Ce({target:"WeakMap",stat:!0,forced:!0},{of:ri(Ng.WeakMap,Ng.set,!0)});var zg=Ng.remove;Ce({target:"WeakMap",proto:!0,real:!0,forced:!0},{deleteAll:function(){for(var t,e=_g(this),r=!0,n=0,o=arguments.length;n2&&(n=r,M(o=arguments[2])&&"cause"in o&&_t(n,"cause",o.cause));var s=[];return Ao(t,ny,{that:s}),_t(r,"errors",s),r};dn?dn(oy,ry):Ae(oy,ry,{name:!0});var iy=oy.prototype=Ve(ry.prototype,{constructor:d(1,oy),message:d(1,""),name:d(1,"AggregateError")});Ce({global:!0,constructor:!0,arity:2},{AggregateError:oy});var ay,uy,sy,cy,fy=function(t){return _.slice(0,t.length)===t},ly=fy("Bun/")?"BUN":fy("Cloudflare-Workers")?"CLOUDFLARE":fy("Deno/")?"DENO":fy("Node.js/")?"NODE":i.Bun&&"string"==typeof Bun.version?"BUN":i.Deno&&"object"==typeof Deno.version?"DENO":"process"===E(i.process)?"NODE":i.window&&i.document?"BROWSER":"REST",hy="NODE"===ly,py=/(?:ipad|iphone|ipod).*applewebkit/i.test(_),vy=i.setImmediate,dy=i.clearImmediate,gy=i.process,yy=i.Dispatch,my=i.Function,by=i.MessageChannel,wy=i.String,Sy=0,Ey={},Oy="onreadystatechange";a(function(){ay=i.location});var xy=function(t){if(ut(Ey,t)){var e=Ey[t];delete Ey[t],e()}},Ry=function(t){return function(){xy(t)}},Py=function(t){xy(t.data)},Ay=function(t){i.postMessage(wy(t),ay.protocol+"//"+ay.host)};vy&&dy||(vy=function(t){Up(arguments.length,1);var e=T(t)?t:my(t),r=vo(arguments,1);return Ey[++Sy]=function(){Ra(e,void 0,r)},uy(Sy),Sy},dy=function(t){delete Ey[t]},hy?uy=function(t){gy.nextTick(Ry(t))}:yy&&yy.now?uy=function(t){yy.now(Ry(t))}:by&&!py?(cy=(sy=new by).port2,sy.port1.onmessage=Py,uy=ar(cy.postMessage,cy)):i.addEventListener&&T(i.postMessage)&&!i.importScripts&&ay&&"file:"!==ay.protocol&&!a(Ay)?(uy=Ay,i.addEventListener("message",Py,!1)):uy=Oy in Et("script")?function(t){De.appendChild(Et("script"))[Oy]=function(){De.removeChild(this),xy(t)}}:function(t){setTimeout(Ry(t),0)});var jy={set:vy,clear:dy},ky=function(){this.head=null,this.tail=null};ky.prototype={add:function(t){var e={item:t,next:null},r=this.tail;r?r.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return null===(this.head=t.next)&&(this.tail=null),t.item}};var Iy,Ty,My,Ly,Uy,Ny=ky,Cy=/ipad|iphone|ipod/i.test(_)&&"undefined"!=typeof Pebble,_y=/web0s(?!.*chrome)/i.test(_),Fy=jy.set,By=i.MutationObserver||i.WebKitMutationObserver,Dy=i.document,zy=i.process,Wy=i.Promise,qy=Ip("queueMicrotask");if(!qy){var Hy=new Ny,$y=function(){var t,e;for(hy&&(t=zy.domain)&&t.exit();e=Hy.get();)try{e()}catch(t){throw Hy.head&&Iy(),t}t&&t.enter()};py||hy||_y||!By||!Dy?!Cy&&Wy&&Wy.resolve?((Ly=Wy.resolve(void 0)).constructor=Wy,Uy=ar(Ly.then,Ly),Iy=function(){Uy($y)}):hy?Iy=function(){zy.nextTick($y)}:(Fy=ar(Fy,i),Iy=function(){Fy($y)}):(Ty=!0,My=Dy.createTextNode(""),new By($y).observe(My,{characterData:!0}),Iy=function(){My.data=Ty=!Ty}),qy=function(t){Hy.head||Iy(),Hy.add(t)}}var Ky,Gy,Vy,Yy=qy,Xy=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},Jy=i.Promise,Qy=dt("species"),Zy=!1,tm=T(i.PromiseRejectionEvent),em=Ue("Promise",function(){var t=Kt(Jy),e=t!==String(Jy);if(!e&&66===W)return!0;if(!W||W<51||!/native code/.test(t)){var r=new Jy(function(t){t(1)}),n=function(t){t(function(){},function(){})};if((r.constructor={})[Qy]=n,!(Zy=r.then(function(){})instanceof n))return!0}return!(e||"BROWSER"!==ly&&"DENO"!==ly||tm)}),rm={CONSTRUCTOR:em,REJECTION_EVENT:tm,SUBCLASSING:Zy},nm=TypeError,om=function(t){var e,r;this.promise=new t(function(t,n){if(void 0!==e||void 0!==r)throw new nm("Bad Promise constructor");e=t,r=n}),this.resolve=J(e),this.reject=J(r)},im={f:function(t){return new om(t)}},am=jy.set,um="Promise",sm=rm.CONSTRUCTOR,cm=rm.REJECTION_EVENT,fm=rm.SUBCLASSING,lm=ne.getterFor(um),hm=ne.set,pm=Jy&&Jy.prototype,vm=Jy,dm=pm,gm=i.TypeError,ym=i.document,mm=i.process,bm=im.f,wm=bm,Sm=!!(ym&&ym.createEvent&&i.dispatchEvent),Em="unhandledrejection",Om=function(t){var e;return!(!M(t)||!T(e=t.then))&&e},xm=function(t,e){var r,n,o,i=e.value,a=1===e.state,u=a?t.ok:t.fail,s=t.resolve,c=t.reject,l=t.domain;try{u?(a||(2===e.rejection&&km(e),e.rejection=1),!0===u?r=i:(l&&l.enter(),r=u(i),l&&(l.exit(),o=!0)),r===t.promise?c(new gm("Promise-chain cycle")):(n=Om(r))?f(n,r,s,c):s(r)):c(i)}catch(t){l&&!o&&l.exit(),c(t)}},Rm=function(t,e){t.notified||(t.notified=!0,Yy(function(){for(var r,n=t.reactions;r=n.get();)xm(r,t);t.notified=!1,e&&!t.rejection&&Am(t)}))},Pm=function(t,e,r){var n,o;Sm?((n=ym.createEvent("Event")).promise=e,n.reason=r,n.initEvent(t,!1,!0),i.dispatchEvent(n)):n={promise:e,reason:r},!cm&&(o=i["on"+t])?o(n):t===Em&&function(t,e){try{1===arguments.length?console.error(t):console.error(t,e)}catch(t){}}("Unhandled promise rejection",r)},Am=function(t){f(am,i,function(){var e,r=t.facade,n=t.value;if(jm(t)&&(e=Xy(function(){hy?mm.emit("unhandledRejection",n,r):Pm(Em,r,n)}),t.rejection=hy||jm(t)?2:1,e.error))throw e.value})},jm=function(t){return 1!==t.rejection&&!t.parent},km=function(t){f(am,i,function(){var e=t.facade;hy?mm.emit("rejectionHandled",e):Pm("rejectionhandled",e,t.value)})},Im=function(t,e,r){return function(n){t(e,n,r)}},Tm=function(t,e,r){t.done||(t.done=!0,r&&(t=r),t.value=e,t.state=2,Rm(t,!0))},Mm=function(t,e,r){if(!t.done){t.done=!0,r&&(t=r);try{if(t.facade===e)throw new gm("Promise can't be resolved itself");var n=Om(e);n?Yy(function(){var r={done:!1};try{f(n,e,Im(Mm,r,t),Im(Tm,r,t))}catch(e){Tm(r,e,t)}}):(t.value=e,t.state=1,Rm(t,!1))}catch(e){Tm({done:!1},e,t)}}};if(sm&&(vm=function(t){ko(this,dm),J(t),f(Ky,this);var e=lm(this);try{t(Im(Mm,e),Im(Tm,e))}catch(t){Tm(e,t)}},(Ky=function(t){hm(this,{type:um,done:!1,notified:!1,parent:!1,reactions:new Ny,rejection:!1,state:0,value:null})}).prototype=ie(dm=vm.prototype,"then",function(t,e){var r=lm(this),n=bm(Cc(this,vm));return r.parent=!0,n.ok=!T(t)||t,n.fail=T(e)&&e,n.domain=hy?mm.domain:void 0,0===r.state?r.reactions.add(n):Yy(function(){xm(n,r)}),n.promise}),Gy=function(){var t=new Ky,e=lm(t);this.promise=t,this.resolve=Im(Mm,e),this.reject=Im(Tm,e)},im.f=bm=function(t){return t===vm||void 0===t?new Gy(t):wm(t)},T(Jy)&&pm!==Object.prototype)){Vy=pm.then,fm||ie(pm,"then",function(t,e){var r=this;return new vm(function(t,e){f(Vy,r,t,e)}).then(t,e)},{unsafe:!0});try{delete pm.constructor}catch(t){}dn&&dn(pm,dm)}Ce({global:!0,constructor:!0,wrap:!0,forced:sm},{Promise:vm}),an(vm,um,!1),Uo(um);var Lm=rm.CONSTRUCTOR||!Gn(function(t){Jy.all(t).then(void 0,function(){})});Ce({target:"Promise",stat:!0,forced:Lm},{all:function(t){var e=this,r=im.f(e),n=r.resolve,o=r.reject,i=Xy(function(){var r=J(e.resolve),i=[],a=0,u=1;Ao(t,function(t){var s=a++,c=!1;u++,f(r,e,t).then(function(t){c||(c=!0,i[s]=t,--u||n(i))},o)}),--u||n(i)});return i.error&&o(i.value),r.promise}});var Um=Jy&&Jy.prototype;if(Ce({target:"Promise",proto:!0,forced:rm.CONSTRUCTOR,real:!0},{catch:function(t){return this.then(void 0,t)}}),T(Jy)){var Nm=L("Promise").prototype.catch;Um.catch!==Nm&&ie(Um,"catch",Nm,{unsafe:!0})}Ce({target:"Promise",stat:!0,forced:Lm},{race:function(t){var e=this,r=im.f(e),n=r.reject,o=Xy(function(){var o=J(e.resolve);Ao(t,function(t){f(o,e,t).then(r.resolve,n)})});return o.error&&n(o.value),r.promise}}),Ce({target:"Promise",stat:!0,forced:rm.CONSTRUCTOR},{reject:function(t){var e=im.f(this);return(0,e.reject)(t),e.promise}});var Cm=function(t,e){if(kt(t),M(e)&&e.constructor===t)return e;var r=im.f(t);return(0,r.resolve)(e),r.promise};Ce({target:"Promise",stat:!0,forced:rm.CONSTRUCTOR},{resolve:function(t){return Cm(this,t)}}),Ce({target:"Promise",stat:!0,forced:Lm},{allSettled:function(t){var e=this,r=im.f(e),n=r.resolve,o=r.reject,i=Xy(function(){var r=J(e.resolve),o=[],i=0,a=1;Ao(t,function(t){var u=i++,s=!1;a++,f(r,e,t).then(function(t){s||(s=!0,o[u]={status:"fulfilled",value:t},--a||n(o))},function(t){s||(s=!0,o[u]={status:"rejected",reason:t},--a||n(o))})}),--a||n(o)});return i.error&&o(i.value),r.promise}});var _m="No one promise resolved";Ce({target:"Promise",stat:!0,forced:Lm},{any:function(t){var e=this,r=L("AggregateError"),n=im.f(e),o=n.resolve,i=n.reject,a=Xy(function(){var n=J(e.resolve),a=[],u=0,s=1,c=!1;Ao(t,function(t){var l=u++,h=!1;s++,f(n,e,t).then(function(t){h||c||(c=!0,o(t))},function(t){h||c||(h=!0,a[l]=t,--s||i(new r(a,_m)))})}),--s||i(new r(a,_m))});return a.error&&i(a.value),n.promise}}),Ce({target:"Promise",stat:!0},{withResolvers:function(){var t=im.f(this);return{promise:t.promise,resolve:t.resolve,reject:t.reject}}});var Fm=Jy&&Jy.prototype,Bm=!!Jy&&a(function(){Fm.finally.call({then:function(){}},function(){})});if(Ce({target:"Promise",proto:!0,real:!0,forced:Bm},{finally:function(t){var e=Cc(this,L("Promise")),r=T(t);return this.then(r?function(r){return Cm(e,t()).then(function(){return r})}:t,r?function(r){return Cm(e,t()).then(function(){throw r})}:t)}}),T(Jy)){var Dm=L("Promise").prototype.finally;Fm.finally!==Dm&&ie(Fm,"finally",Dm,{unsafe:!0})}var zm=i.Promise,Wm=!1,qm=!zm||!zm.try||Xy(function(){zm.try(function(t){Wm=8===t},8)}).error||!Wm;Ce({target:"Promise",stat:!0,forced:qm},{try:function(t){var e=arguments.length>1?vo(arguments,1):[],r=im.f(this),n=Xy(function(){return Ra(J(t),void 0,e)});return(n.error?r.reject:r.resolve)(n.value),r.promise}}),Ze("Promise","finally");var Hm="URLSearchParams"in self,$m="Symbol"in self&&"iterator"in Symbol,Km="FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(t){return!1}}(),Gm="FormData"in self,Vm="ArrayBuffer"in self;if(Vm)var Ym=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Xm=ArrayBuffer.isView||function(t){return t&&Ym.indexOf(Object.prototype.toString.call(t))>-1};function Jm(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function Qm(t){return"string"!=typeof t&&(t=String(t)),t}function Zm(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return $m&&(e[Symbol.iterator]=function(){return e}),e}function tb(t){this.map={},t instanceof tb?t.forEach(function(t,e){this.append(e,t)},this):Array.isArray(t)?t.forEach(function(t){this.append(t[0],t[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function eb(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function rb(t){return new Promise(function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}})}function nb(t){var e=new FileReader,r=rb(e);return e.readAsArrayBuffer(t),r}function ob(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function ib(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:Km&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:Gm&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:Hm&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():Vm&&Km&&(e=t)&&DataView.prototype.isPrototypeOf(e)?(this._bodyArrayBuffer=ob(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):Vm&&(ArrayBuffer.prototype.isPrototypeOf(t)||Xm(t))?this._bodyArrayBuffer=ob(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):Hm&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},Km&&(this.blob=function(){var t=eb(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?eb(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(nb)}),this.text=function(){var t=eb(this);if(t)return t;if(this._bodyBlob)return function(t){var e=new FileReader,r=rb(e);return e.readAsText(t),r}(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n-1?e:t}(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function sb(t){var e=new FormData;return t.trim().split("&").forEach(function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}}),e}function cb(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new tb(e.headers),this.url=e.url||"",this._initBody(t)}ub.prototype.clone=function(){return new ub(this,{body:this._bodyInit})},ib.call(ub.prototype),ib.call(cb.prototype),cb.prototype.clone=function(){return new cb(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new tb(this.headers),url:this.url})},cb.error=function(){var t=new cb(null,{status:0,statusText:""});return t.type="error",t};var fb=[301,302,303,307,308];cb.redirect=function(t,e){if(-1===fb.indexOf(e))throw new RangeError("Invalid status code");return new cb(null,{status:e,headers:{location:t}})};var lb=self.DOMException;try{new lb}catch(t){(lb=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack}).prototype=Object.create(Error.prototype),lb.prototype.constructor=lb}function hb(t,e){return new Promise(function(r,n){var o=new ub(t,e);if(o.signal&&o.signal.aborted)return n(new lb("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var t,e,n={status:i.status,statusText:i.statusText,headers:(t=i.getAllResponseHeaders()||"",e=new tb,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}}),e)};n.url="responseURL"in i?i.responseURL:n.headers.get("X-Request-URL"),r(new cb("response"in i?i.response:i.responseText,n))},i.onerror=function(){n(new TypeError("Network request failed"))},i.ontimeout=function(){n(new TypeError("Network request failed"))},i.onabort=function(){n(new lb("Aborted","AbortError"))},i.open(o.method,o.url,!0),"include"===o.credentials?i.withCredentials=!0:"omit"===o.credentials&&(i.withCredentials=!1),"responseType"in i&&Km&&(i.responseType="blob"),o.headers.forEach(function(t,e){i.setRequestHeader(e,t)}),o.signal&&(o.signal.addEventListener("abort",a),i.onreadystatechange=function(){4===i.readyState&&o.signal.removeEventListener("abort",a)}),i.send(void 0===o._bodyInit?null:o._bodyInit)})}hb.polyfill=!0,self.fetch||(self.fetch=hb,self.Headers=tb,self.Request=ub,self.Response=cb);var pb=Object.getOwnPropertySymbols,vb=Object.prototype.hasOwnProperty,db=Object.prototype.propertyIsEnumerable,gb=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(e).map(function(t){return e[t]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(t){n[t]=t}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var r,n,o=function(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),i=1;i{"use strict";var e={},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var a=t[o]={exports:{}},i=!0;try{e[o](a,a.exports,r),i=!1}finally{i&&delete t[o]}return a.exports}r.m=e,(()=>{var e=[];r.O=(t,o,n,a)=>{if(o){a=a||0;for(var i=e.length;i>0&&e[i-1][2]>a;i--)e[i]=e[i-1];e[i]=[o,n,a];return}for(var u=1/0,i=0;i=a)&&Object.keys(r.O).every(e=>r.O[e](o[c]))?o.splice(c--,1):(l=!1,a{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},(()=>{var e,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;r.t=function(o,n){if(1&n&&(o=this(o)),8&n||"object"==typeof o&&o&&(4&n&&o.__esModule||16&n&&"function"==typeof o.then))return o;var a=Object.create(null);r.r(a);var i={};e=e||[null,t({}),t([]),t(t)];for(var u=2&n&&o;"object"==typeof u&&!~e.indexOf(u);u=t(u))Object.getOwnPropertyNames(u).forEach(e=>i[e]=()=>o[e]);return i.default=()=>o,r.d(a,i),a}})(),r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce((t,o)=>(r.f[o](e,t),t),[])),r.u=e=>{},r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={},t="_N_E:";r.l=(o,n,a,i)=>{if(e[o]){e[o].push(n);return}if(void 0!==a)for(var u,l,c=document.getElementsByTagName("script"),d=0;d{u.onerror=u.onload=null,clearTimeout(p);var n=e[o];if(delete e[o],u.parentNode&&u.parentNode.removeChild(u),n&&n.forEach(e=>e(r)),t)return t(r)},p=setTimeout(s.bind(null,void 0,{type:"timeout",target:u}),12e4);u.onerror=s.bind(null,u.onerror),u.onload=s.bind(null,u.onload),l&&document.head.appendChild(u)}})(),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;r.tt=()=>(void 0===e&&(e={createScriptURL:e=>e},"undefined"!=typeof trustedTypes&&trustedTypes.createPolicy&&(e=trustedTypes.createPolicy("nextjs#bundler",e))),e)})(),r.tu=e=>r.tt().createScriptURL(e),r.p="/_next/",(()=>{var e={68:0,830:0,953:0};r.f.j=(t,o)=>{var n=r.o(e,t)?e[t]:void 0;if(0!==n){if(n)o.push(n[2]);else if(/^(68|830|953)$/.test(t))e[t]=0;else{var a=new Promise((r,o)=>n=e[t]=[r,o]);o.push(n[2]=a);var i=r.p+r.u(t),u=Error();r.l(i,o=>{if(r.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var a=o&&("load"===o.type?"missing":o.type),i=o&&o.target&&o.target.src;u.message="Loading chunk "+t+" failed.\n("+a+": "+i+")",u.name="ChunkLoadError",u.type=a,u.request=i,n[1](u)}},"chunk-"+t,t)}}},r.O.j=t=>0===e[t];var t=(t,o)=>{var n,a,[i,u,l]=o,c=0;if(i.some(t=>0!==e[t])){for(n in u)r.o(u,n)&&(r.m[n]=u[n]);if(l)var d=l(r)}for(t&&t(o);c=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-4{margin-top:calc(var(--spacing)*4)}.mb-0{margin-bottom:calc(var(--spacing)*0)}.mb-1{margin-bottom:calc(var(--spacing)*1)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.mb-\[50vh\]{margin-bottom:50vh}.block{display:block}.flex{display:flex}.hidden{display:none}.h-1{height:calc(var(--spacing)*1)}.h-2{height:calc(var(--spacing)*2)}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-10{height:calc(var(--spacing)*10)}.h-20{height:calc(var(--spacing)*20)}.h-\[min\(50vh\,300px\)\]{height:min(50vh,300px)}.h-full{height:100%}.max-h-\[200px\]{max-height:200px}.min-h-\[44px\]{min-height:44px}.min-h-screen{min-height:100vh}.w-2{width:calc(var(--spacing)*2)}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-6{width:calc(var(--spacing)*6)}.w-10{width:calc(var(--spacing)*10)}.w-20{width:calc(var(--spacing)*20)}.w-\[100\%\]{width:100%}.w-\[600px\]{width:600px}.w-full{width:100%}.max-w-full{max-width:100%}.max-w-md{max-width:var(--container-md)}.min-w-\[300px\]{min-width:300px}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.flex-grow{flex-grow:1}.-translate-x-1\/2{--tw-translate-x:calc(calc(1/2*100%)*-1)}.-translate-x-1\/2,.translate-y-0{translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-0{--tw-translate-y:calc(var(--spacing)*0)}.translate-y-20{--tw-translate-y:calc(var(--spacing)*20)}.translate-y-20,.translate-y-full{translate:var(--tw-translate-x)var(--tw-translate-y)}.translate-y-full{--tw-translate-y:100%}.rotate-0{rotate:none}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x)var(--tw-rotate-y)var(--tw-rotate-z)var(--tw-skew-x)var(--tw-skew-y)}.animate-bounce{animation:var(--animate-bounce)}.animate-pulse{animation:var(--animate-pulse)}.cursor-pointer{cursor:pointer}.resize{resize:both}.resize-y{resize:vertical}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-1{gap:calc(var(--spacing)*1)}.gap-1\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e+38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-b-lg{border-bottom-right-radius:var(--radius-lg);border-bottom-left-radius:var(--radius-lg)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-gray-400{border-color:var(--color-gray-400)}.border-green-500{border-color:var(--color-green-500)}.bg-blue-500{background-color:var(--color-blue-500)}.bg-blue-500\/50{background-color:color-mix(in oklab,var(--color-blue-500)50%,transparent)}.bg-gray-500{background-color:var(--color-gray-500)}.bg-gray-500\/50{background-color:color-mix(in oklab,var(--color-gray-500)50%,transparent)}.bg-gray-600{background-color:var(--color-gray-600)}.bg-gray-700\/50{background-color:color-mix(in oklab,var(--color-gray-700)50%,transparent)}.bg-gray-800\/50{background-color:color-mix(in oklab,var(--color-gray-800)50%,transparent)}.bg-gray-900{background-color:var(--color-gray-900)}.bg-green-500{background-color:var(--color-green-500)}.bg-green-500\/50{background-color:color-mix(in oklab,var(--color-green-500)50%,transparent)}.bg-orange-500\/50{background-color:color-mix(in oklab,var(--color-orange-500)50%,transparent)}.bg-red-500{background-color:var(--color-red-500)}.bg-red-500\/90{background-color:color-mix(in oklab,var(--color-red-500)90%,transparent)}.bg-transparent{background-color:#0000}.bg-white\/20{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}.bg-white\/40{background-color:color-mix(in oklab,var(--color-white)40%,transparent)}.p-1{padding:calc(var(--spacing)*1)}.p-1\.5{padding:calc(var(--spacing)*1.5)}.p-2{padding:calc(var(--spacing)*2)}.p-2\.5{padding:calc(var(--spacing)*2.5)}.p-4{padding:calc(var(--spacing)*4)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-6{padding-inline:calc(var(--spacing)*6)}.py-1{padding-block:calc(var(--spacing)*1)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.py-4{padding-block:calc(var(--spacing)*4)}.pr-40{padding-right:calc(var(--spacing)*40)}.pl-6{padding-left:calc(var(--spacing)*6)}.text-center{text-align:center}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.break-words{overflow-wrap:break-word}.text-blue-200{color:var(--color-blue-200)}.text-blue-400{color:var(--color-blue-400)}.text-gray-200{color:var(--color-gray-200)}.text-gray-400{color:var(--color-gray-400)}.text-green-200{color:var(--color-green-200)}.text-orange-200{color:var(--color-orange-200)}.text-white{color:var(--color-white)}.line-through{text-decoration-line:line-through}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.opacity-0{opacity:0}.opacity-100{opacity:1}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.duration-\[5000ms\]{--tw-duration:5s;transition-duration:5s}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-linear{--tw-ease:linear;transition-timing-function:linear}@media (hover:hover){.group-hover\:scale-110:is(:where(.group):hover *){--tw-scale-x:110%;--tw-scale-y:110%;--tw-scale-z:110%;scale:var(--tw-scale-x)var(--tw-scale-y)}.hover\:bg-blue-600:hover{background-color:var(--color-blue-600)}.hover\:bg-gray-500:hover{background-color:var(--color-gray-500)}.hover\:bg-gray-600\/50:hover{background-color:color-mix(in oklab,var(--color-gray-600)50%,transparent)}.hover\:bg-gray-700\/50:hover{background-color:color-mix(in oklab,var(--color-gray-700)50%,transparent)}.hover\:bg-red-600:hover{background-color:var(--color-red-600)}.hover\:bg-white\/20:hover{background-color:color-mix(in oklab,var(--color-white)20%,transparent)}.hover\:text-blue-300:hover{color:var(--color-blue-300)}.hover\:text-white:hover{color:var(--color-white)}.hover\:opacity-80:hover{opacity:.8}}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-blue-500:focus{--tw-ring-color:var(--color-blue-500)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}@media (width>=48rem){.md\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}}@media (width>=64rem){.lg\:top-0{top:calc(var(--spacing)*0)}.lg\:top-4{top:calc(var(--spacing)*4)}.lg\:right-0{right:calc(var(--spacing)*0)}.lg\:bottom-auto{bottom:auto}.lg\:mb-0{margin-bottom:calc(var(--spacing)*0)}.lg\:h-screen{height:100vh}.lg\:w-80{width:calc(var(--spacing)*80)}.lg\:translate-x-0{--tw-translate-x:calc(var(--spacing)*0)}.lg\:translate-x-0,.lg\:translate-x-full{translate:var(--tw-translate-x)var(--tw-translate-y)}.lg\:translate-x-full{--tw-translate-x:100%}.lg\:flex-row{flex-direction:row}.lg\:pr-0{padding-right:calc(var(--spacing)*0)}.lg\:pr-80{padding-right:calc(var(--spacing)*80)}}}:root{--background:#fff;--foreground:#171717}@media (prefers-color-scheme:dark){:root{--background:#0a0a0a;--foreground:#ededed}}body{color:var(--foreground);background:var(--background);font-family:Arial,Helvetica,sans-serif}.canvas-container{width:100%;height:100%;top:0;left:0;position:absolute!important}.video-container{justify-content:center!important}.canvi{z-index:-1}.vjs-marker{z-index:0;cursor:pointer;width:.5rem;height:200%;position:absolute;transform:translate(-50%)}.vjs-marker,.vjs-marker:hover{background:red;border-radius:.25rem}.video-js .vjs-progress-control .vjs-progress-holder{position:relative}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false;initial-value:rotateX(0)}@property --tw-rotate-y{syntax:"*";inherits:false;initial-value:rotateY(0)}@property --tw-rotate-z{syntax:"*";inherits:false;initial-value:rotateZ(0)}@property --tw-skew-x{syntax:"*";inherits:false;initial-value:skewX(0)}@property --tw-skew-y{syntax:"*";inherits:false;initial-value:skewY(0)}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@keyframes pulse{50%{opacity:.5}}@keyframes bounce{0%,to{animation-timing-function:cubic-bezier(.8,0,1,1);transform:translateY(-25%)}50%{animation-timing-function:cubic-bezier(0,0,.2,1);transform:none}} \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/css/998a630a136a8118.css b/services/v1/media/feedback/static/_next/static/css/998a630a136a8118.css new file mode 100644 index 0000000000000000000000000000000000000000..9c22c9a78342c97801daf5d186498f60e05040d1 --- /dev/null +++ b/services/v1/media/feedback/static/_next/static/css/998a630a136a8118.css @@ -0,0 +1 @@ +.vjs-svg-icon{display:inline-block;background-repeat:no-repeat;background-position:50%;fill:currentColor;height:1.8em;width:1.8em}.vjs-svg-icon:before{content:none!important}.vjs-control:focus .vjs-svg-icon,.vjs-svg-icon:hover{filter:drop-shadow(0 0 .25em #fff)}.video-js .vjs-big-play-button .vjs-icon-placeholder:before,.video-js .vjs-modal-dialog,.vjs-button>.vjs-icon-placeholder:before,.vjs-modal-dialog .vjs-modal-dialog-content{position:absolute;top:0;left:0;width:100%;height:100%}.video-js .vjs-big-play-button .vjs-icon-placeholder:before,.vjs-button>.vjs-icon-placeholder:before{text-align:center}@font-face{font-family:VideoJS;src:url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABTsAAsAAAAAIpAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAADsAAABUIIslek9TLzIAAAFEAAAAPgAAAFZRiV32Y21hcAAAAYQAAAEJAAAD5p42+VxnbHlmAAACkAAADtIAABckI4l972hlYWQAABFkAAAAKwAAADYsvIjpaGhlYQAAEZAAAAAdAAAAJA+RCL1obXR4AAARsAAAABcAAAC8Q2YAAGxvY2EAABHIAAAAYAAAAGB7CIGGbWF4cAAAEigAAAAfAAAAIAFAAI9uYW1lAAASSAAAASUAAAIK1cf1oHBvc3QAABNwAAABfAAAAnXdFqh1eJxjYGRgYOBiMGCwY2BycfMJYeDLSSzJY5BiYGGAAJA8MpsxJzM9kYEDxgPKsYBpDiBmg4gCACY7BUgAeJxjYGR7yDiBgZWBgaWQ5RkDA8MvCM0cwxDOeI6BgYmBlZkBKwhIc01hcPjI+FGPHcRdyA4RZgQRADaGCyYAAHic7dPXbcMwAEXRK1vuvffem749XAbKV3bjBA6fXsaIgMMLEWoQJaAEFKNnlELyQ4K27zib5PNF6vl8yld+TKr5kH0+cUw0xv00Hwvx2DResUyFKrV4XoMmLdp06NKjz4AhI8ZMmDJjzoIlK9Zs2LJjz4EjJ85cuHLjziPe/0UWL17mf2tqKLz/9jK9f8tXpGCoRdPKhtS0RqFkWvVQNtSKoVYNtWaoddPXEBqG2jQ9XWgZattQO4baNdSeofYNdWCoQ0MdGerYUCeGOjXUmaHODXVhqEtDXRnq2lA3hro11J2h7g31YKhHQz0Z6tlQL4Z6NdSbod4N9WGoT9MfHF6GmhnZLxyDcRMAAAB4nJ1YC1hU17U+a5/HMA4iA3NmVBDmoQwP5TFnHlFeA4gYiUFRQINoSCBAyK3G2yi+0aipYtFcHYo2xsb4NiY3+VrNxSaX5uvt495ozNdoYoxmem2/L8HGpLc+InB279pnhlGr5mvL4eyz99nrrL32eu1/DQcc/okdYgdHOA6MQKp4r9gx0EcMHMezOalVasW5BM7NcXoSb9fFgE6KtSSBxWz1FYDPG+vMBGcKb9cebu2VS5s2aaTkCvRSf6C7Y+Ppibm5E09v7IDs2/3uZQtbD0zIyppwoHXh/93ukmyYgdePNRp65p5v+3v/9otQl2O7wP34cT88p8Md2YxpYLQZoRcy6FlSBRnwnGAe6BPMSCZo+7NJVqS0cE4uHendzhSnbPH6TDqL1+Nme5LZXkCHnGyoH0kne30WH+gswhm3q+pt/mTas9NLS64GnjmSlTPw0wVQT/ewRaBgxtydy3cuUB9/6SW+vb5yRvr+t0eOfPKJZ/9t3+4tL7xj32Xd3thCxi+ge6ifdsAN+l5+wi5HQ/cCoeull1AszS7CUfEcJzK7sKWJAdJhCd0sPM4+EY7QDm5ov08hXRQXE5bf6PV5Q5+IjW7X7Nku92Ask4l2hCRRD6TPqISiCJeQna3SCFwrhrNzXHzo4yFevBwxpzxk8WCIIfkvVEKVy32SbT8n68gzgaslpaiO2zIGIyuSb7RNf9HSuN26y/7OC1tgEmpiyA6aD4qcgTOiLThwGG0eB694FI8NHLLN6OBlRVaMxNAFS4JdXUG6mW8PwpKuYLCLXKGbu8iwYNdgO06Sn3Th+/vyZAxs8Ro30DjHe9gy8Fywi24OMm7Qyzh3MTZVOMYhLBnoC+J79lpTUyQmorjhnMwlcQ5uPEYGpDjsOkkH49BjQLQBqs3jFtFdJNlksYmoQFDArLh8Xh+Qd6Ghcsb6FUuehDi+U/lqD71K/qiegeV1imcwjl7ExwiSrf4BZyCujV6cVcFo6VX+G9IcPyFjJnUufbU/jzrL1X99as36reXl8K32nFaOr+E8jWJEcJ55DpMVfSMe95/AJaOsGBH2GJCNpiRQbK4C8BjdmQA22QY2j03Em13i2YHqtNLU1NI04Yj2HJgA6fQc6VPNpA/D+Ryks554NnVy2mB72uRUfPLsqR4N0LOBQKArwJYO+5W2fgZX8oC1HR6HjNaQTVIG2FPwnTcXXGZZfNB7TE6pTKZUwaw91XWLAoFFGcnB5PHjsckgBjbWutrL+0h5Y1xw3DRGDumsnXb3MJwXrJIN5U7m0rgJ3yG5w4he5ckFG4pmNEkOm0/xOO4r4yL87wqtQM+hiJIVp+6iG2wPBKD35ElGkDx+UfC2v1mFG1o+M3AjNFty8biKMXwzyxnZLds8wYD2BxmCPHAldPOeLsy/0BugftYhVYFAhO8SqQ0j3oK7dHJZnI/jxmUS4onlxskSF8thmvNZjIrRZwEPxr0lBuLRuz3oy/FOHCsxwOPYh2M+e9u3J5pgPYz9gp6G7C9m0A11F9ddqKMfV+4sbq45/YspOysXvT+3pdFdYNg2fHbW8Dz301MqDVuGrz0Fuh0YMW8mddrpqzST7rV9BcvqPoNvadRndWp0p8HvbiqrFj5yFQ/vNFSXDpxpLEFWp+DcrF3FT1afWshFcmCfeAMjEvO65i0Y6XijQfSRPWx3TV/Df7Km3E1l+kLt56s/rwVzuRusNMhudznkwdLaS+QNdeal2jDPP4l9qHc98vTYZOSkxzD+njBWVWjFPKgipx6DkWvXQiW8OYcewVHE5yukinDMcfGgc0opDltYKDxIGBedkzc6jSfE7tlvESCDFUw0Hx0opS+U0lHCxNottbNWSxX9zZVvEhKWUSyBpaXwBc2a98M6UqPeXAs/GDon8Ax7hsthO8cM5HU7Ad0UvRR9lHmtyQKZ4MAe814X5h9MSUkQmhf96eVJ6p90OjIiqSIjvykvr2l5U55O/fPQKD+jIomYpNyGJQ25uQ2kIikRfAmuBHCPsWqkSDEqgZ5KDI2sifS/R43MbZg0idFHbCPNxXxZws1ACVE6hAhOdJwRkJLFBLPZpRGYJ50pko6XzMkgmSx40ljik6AQcKhFnLcQE6rF7PXFe1Ocoj0T3AXgSgJTDIhHRfHlYZKuSzc6uievOJGXY+i5GJkkTp7UM3y0LqATDbtFcbdBxO7o4T25JYlEjoH0uynUh8rapkxp62QN70svSF+hT4gGPlovlmcm/ComLi7mV4kTykV9NFWjE/QrwgQ4uIcAP0rQF4VZYRP2o3PhHHzfPMJj9Ir+uzKUlrH49ntT18AVvj1sc3YGjUT/Mt2Dxawa8ArcA7bCQIpvfwAYu22vEG/No/5RvPdA7g+AelLrPwzy+LtkLPhnpIxH14m4EYq8eeMHbPEPNm6G7Nv9B4jcFPZ8bJj0SEjP3MPgQdKTqqEoy2v6G32P/Y6dxOv04AxnoAeq+GILvUavtYCBXm+BaIhuodcfrN5B/V2EYMCPh+SxavjGyPwV0x4CJgUPGT0mQaODGBACIJZGsMXwAD0LGXx7l3CdAcKMIKI+f5CepWeD0BvyU/GcdBxPF8SwejC6LGZmAURFdsSWKR5HyHld2kbdIZO1Ixx+bnnzU7n5+blPNV9jnUDWhP2tC68tbN3PVIldsQPxSAcSpjOav7Q05uXn5zW2LLvDXn9B6syscPy9iDLEMmSrJz6nYuWMipukjM0AH8JkGS+XFyMRkzSCH7KD/hwm172SAyZYumHlefr5AddrtA0O0TnwaVZxcRY9Bfukn9Gf05N1r9DV9MoBsJ1f+ZrqUvtPHizJAntWybv7hmqLt6QLuK6ZS9Fqi1jO5rDoWPZXXII5Tgajg53cIXCjDCGIcYrRIY2n6+mXOa/W0bdhau3ryiEYe2FV/5oeaIYK/5w5frCyll6/cYO8DiNhw6t1MBWmznt91QX62UF1N7l0eHBZTRGpKaqpKVIPF9UcIzmReud9TSY75+K899GHbBu6wjoR7RKKZVYiYxSPf5/2wJT5e3NAhmUbVn5KLx1Ujg0+BGvpAIh0DezInTkzF37KVocxrKU3r1+XLtAe2lO3l66kfQfB/unKY+q8N375Ru8bc4pJXfEcESU95q+p8ZNZRTWH1d9FzvUdYXk5rLkcdkEisoKKVHQW/b3GEx6tPaYcoJfOr9wAbSBnv1IHpep0OExr4LPMkpJM+j7sly7UHkOzXjoAZljHCGiyegtNlwljM0v+c19ET9Pvst09a2Mtgcf5/ZSzYO5h1156+eyydfAsxGa9XAuF6vzjh6CssLq6ECysperXX0sX5h5ZdpZe3guxsGIPEtHk/aqXX1hVqP5HYVVVISkrrNqvXorIc+5Ou91Hnr/LcD2afi6eX7UBloOcs7cOpqgGaNfs1g7bNbs9z6wASaylN69d0/TFTIz6Ws8+oGV3mE2612wRTHKcVUbhjKadebloMc+dyXgMVtVK6BwMB/+mVW09igdRBWaRtNQX59d/VD//xdQ0TCiYNj1KT9sq6Wdu5WTbqk3qDXyDaLa1fv621LS01G3z61sD6lH8lAxDLicV921s6Bf92JOYvzNYCL1khbqBXEFUzC521N5NyzNaQIWhjyFyDoBIVrAjmv2UEaLlI+c6zw1jmVIPLLLZZUTj6GxGHW+mq1tgHXR2D85p4Q934+jLbtjVLcyCdS10NVzpHqxp4Q/hK7WopY/NRGx9HGsPGdFjOjcpjBnGYMVqY/4eqT5khWEHWUup2A/pTw7pdWgsWft7ETUERL96nRg0HNFPmCYba6pylECaExX89A9WLUOVB4oKLu/o1oqSYHCgLzBUlAz8hNFDRpeSU1XT+LRmDUgPaKbYdHDn9suF/tu13nHJij0N97LfS0QmqONuyONk7zvUI6Qa0pF9f2+oABL92AT6e0U//z9YqAiWtJLU1JK0gS+1aacwamiNqK067u9ZQ8f1d4qLodMzz3uL89Z68V/Hnr++hXWUuHgw8dfi972PeTyPefu3aNNucemQ74qFuIaJnVkOu4Q+yjuwmmC1FqZpl1i4uzoPxjkpPf3Xv545tl26Rr+dOvUd+omqJzch9dOeU7f10Y64nMcKK137DccIZq2WdXtdZjbEoLSzHwiMtrjYLDxpHQW8gjMX6XFYAE2zSWVD04EGYSs9MbO6sEo20BMEAB4mpvSypsKjZ4Stgzb+c3A9/MQT2+vrBy+qvyFxLUtLlSRF/Ri2wjfZ2dus2Q8lXx4608/jnqK5OOap6NY2PSjYYnECCjiEeLJll/pbmqfeIK+ps3+MxrlEhqmTPipVP7kqlF4VhpEb6r+Q7YOJg38kJ9SHBf3NBl6+9YchfbUjb5ahLSzUM3kPHmwFAsZ5rpai0S7E5xWzZ1j+fW7zsUWP2g5NXTw52ySCTrgG0+lbw60l2Y/CB185CoA8NK+tbRKxfjy6pm5hzQRRR+cMqv1Jbiw6STivtEvt3DRcy0QEh92JlUGo2PG4tSKHl00YD6xc8CK+YPYyy3io2lN8BcSjKRzrIV6ypOAobqxViJPaT9M9Hy5szY33mp7OX/Zu89L/7Ww5vqY2Y8b0pKgoiUhG5cPDPzq8qTV/WkzUOIvXVVA96kmjcBrr3HrYC/Wn+fYP6Z7T1rqy3zknbvqma/FvVk96fNXGkuaXrdHW5JGSxZT/2I/O73v+yNWafMdzc5NdxYurHs6h86e01sLKLz9EBrg+x36rxAaED7hRnAMx7Vzu+9wabh3zG8XLQjx0ablUJzmxdErxYT3kzQSd0SSafVqF5PXgpp0OyYJ1EyNHpGUZmvK575ySzd85JSqF7IBzSAbMM04+MbE58xF3/njXOGecSaermlw2y9PsSQdytLJVr8t+wg+rR8cZYoeNxVIzNdk3Bngi8U5LAlgTFoQnzJCa5EsCgYhCaGL+qPj7TdhG31p9tej3R04N//PXxNwJvyUqwaJqRPJY98TJ5TPndmflRAkAhBfe46sfKW5wizSge08Xb7Ca/GUVs55trngkKkrUS2WPzKttaaqq+idmahugkY+W6fN0I6i3gPt/x88U4wAAeJxjYGRgYADiGU9YXsXz23xl4GZnAIFH7fO+IdMc/WBxDgYmEAUASbMKwAB4nGNgZGBgZwABjj4Ghv//OfoZGBlQgT4ARicDZAAAAHicY2BgYGAfxJijD8Fmu4EqBwCSpgKpAAAAAAAADgBoAH4AzADgAQIBQgFsAZgB7gIuAooC0AL8A2IDjAOoA+AEMASwBNoFCAVaBcAGCAYuBnAGrAb2B04HigfSCCoIcAiGCJwIyAkkCVYJiAmsCfIKIApWCsQLknicY2BkYGDQZ2hmYGcAASYg5gJCBob/YD4DABqrAdAAeJxdkE1qg0AYhl8Tk9AIoVDaVSmzahcF87PMARLIMoFAl0ZHY1BHdBJIT9AT9AQ9RQ9Qeqy+yteNMzDzfM+88w0K4BY/cNAMB6N2bUaPPBLukybCLvleeAAPj8JD+hfhMV7hC3u4wxs7OO4NzQSZcI/8Ltwnfwi75E/hAR7wJTyk/xYeY49fYQ/PztM+jbTZ7LY6OWdBJdX/pqs6NYWa+zMxa13oKrA6Uoerqi/JwtpYxZXJ1coUVmeZUWVlTjq0/tHacjmdxuL90OR8O0UEDYMNdtiSEpz5XQGqzlm30kzUdAYFFOb8R7NOZk0q2lwAyz1i7oAr1xoXvrOgtYhZx8wY5KRV269JZ5yGpmzPTjQhvY9je6vEElPOuJP3mWKnP5M3V+YAAAB4nG2ReVPbMBDF/ULi2EkDBFqO3gdHLxUzDB9IkdexBllydRD49ihO3Ckz7B/a31utZnafkkGyiXnyclxhgB0MMUKKMTLkmGCKV5hhF3vYxxwHOMRrvMERjnGCU7zFO7zHB3zEJ3zGF3zFN5zhHBe4xHf8wE/8wm8w/MEVimTYKv44XR9MSCsUjVoeHE3vjQoNsSZ4mmxZmVWPjSz7jlou6/0qKOWEJdKMtCe793/hQfqxa6XWZHMXFl56RS4TvPXSaDeoy0zUUZB109KstDK8lHo5q6Qi1hcOnqkImubPS6aqRq7mlnaEWabub4iYblba3SRmgldS0+FWdhNtt04F14JUaqkl7tcpOpJtErvNt3Bd9HRT5JWxK25Ldjvp6br4hzfFiIdSmlzTg2fSUzNrLd1LE1ynxq4OVaVoKLjzJ60UPtj1RKzHzsbjly6inVnFBS2MucviPncU7Rr7lfTxRepDs1A2j3ZHRc7PuzFYSfE3ZOd4kjwBy227hA==) format("woff");font-weight:400;font-style:normal}.video-js .vjs-big-play-button .vjs-icon-placeholder:before,.video-js .vjs-play-control .vjs-icon-placeholder,.vjs-icon-play{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-big-play-button .vjs-icon-placeholder:before,.video-js .vjs-play-control .vjs-icon-placeholder:before,.vjs-icon-play:before{content:"\f101"}.vjs-icon-play-circle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-play-circle:before{content:"\f102"}.video-js .vjs-play-control.vjs-playing .vjs-icon-placeholder,.vjs-icon-pause{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-play-control.vjs-playing .vjs-icon-placeholder:before,.vjs-icon-pause:before{content:"\f103"}.video-js .vjs-mute-control.vjs-vol-0 .vjs-icon-placeholder,.vjs-icon-volume-mute{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-mute-control.vjs-vol-0 .vjs-icon-placeholder:before,.vjs-icon-volume-mute:before{content:"\f104"}.video-js .vjs-mute-control.vjs-vol-1 .vjs-icon-placeholder,.vjs-icon-volume-low{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-mute-control.vjs-vol-1 .vjs-icon-placeholder:before,.vjs-icon-volume-low:before{content:"\f105"}.video-js .vjs-mute-control.vjs-vol-2 .vjs-icon-placeholder,.vjs-icon-volume-mid{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-mute-control.vjs-vol-2 .vjs-icon-placeholder:before,.vjs-icon-volume-mid:before{content:"\f106"}.video-js .vjs-mute-control .vjs-icon-placeholder,.vjs-icon-volume-high{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-mute-control .vjs-icon-placeholder:before,.vjs-icon-volume-high:before{content:"\f107"}.video-js .vjs-fullscreen-control .vjs-icon-placeholder,.vjs-icon-fullscreen-enter{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-fullscreen-control .vjs-icon-placeholder:before,.vjs-icon-fullscreen-enter:before{content:"\f108"}.video-js.vjs-fullscreen .vjs-fullscreen-control .vjs-icon-placeholder,.vjs-icon-fullscreen-exit{font-family:VideoJS;font-weight:400;font-style:normal}.video-js.vjs-fullscreen .vjs-fullscreen-control .vjs-icon-placeholder:before,.vjs-icon-fullscreen-exit:before{content:"\f109"}.vjs-icon-spinner{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-spinner:before{content:"\f10a"}.video-js .vjs-subs-caps-button .vjs-icon-placeholder,.video-js .vjs-subtitles-button .vjs-icon-placeholder,.video-js.video-js:lang(en-AU) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-GB) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-IE) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js.video-js:lang(en-NZ) .vjs-subs-caps-button .vjs-icon-placeholder,.vjs-icon-subtitles{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js .vjs-subtitles-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-AU) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-GB) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-IE) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js.video-js:lang(en-NZ) .vjs-subs-caps-button .vjs-icon-placeholder:before,.vjs-icon-subtitles:before{content:"\f10b"}.video-js .vjs-captions-button .vjs-icon-placeholder,.video-js:lang(en) .vjs-subs-caps-button .vjs-icon-placeholder,.video-js:lang(fr-CA) .vjs-subs-caps-button .vjs-icon-placeholder,.vjs-icon-captions{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-captions-button .vjs-icon-placeholder:before,.video-js:lang(en) .vjs-subs-caps-button .vjs-icon-placeholder:before,.video-js:lang(fr-CA) .vjs-subs-caps-button .vjs-icon-placeholder:before,.vjs-icon-captions:before{content:"\f10c"}.vjs-icon-hd{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-hd:before{content:"\f10d"}.video-js .vjs-chapters-button .vjs-icon-placeholder,.vjs-icon-chapters{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-chapters-button .vjs-icon-placeholder:before,.vjs-icon-chapters:before{content:"\f10e"}.vjs-icon-downloading{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-downloading:before{content:"\f10f"}.vjs-icon-file-download{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download:before{content:"\f110"}.vjs-icon-file-download-done{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download-done:before{content:"\f111"}.vjs-icon-file-download-off{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-file-download-off:before{content:"\f112"}.vjs-icon-share{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-share:before{content:"\f113"}.vjs-icon-cog{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-cog:before{content:"\f114"}.vjs-icon-square{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-square:before{content:"\f115"}.video-js .vjs-play-progress,.video-js .vjs-volume-level,.vjs-icon-circle,.vjs-seek-to-live-control .vjs-icon-placeholder{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-play-progress:before,.video-js .vjs-volume-level:before,.vjs-icon-circle:before,.vjs-seek-to-live-control .vjs-icon-placeholder:before{content:"\f116"}.vjs-icon-circle-outline{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-circle-outline:before{content:"\f117"}.vjs-icon-circle-inner-circle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-circle-inner-circle:before{content:"\f118"}.video-js .vjs-control.vjs-close-button .vjs-icon-placeholder,.vjs-icon-cancel{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-control.vjs-close-button .vjs-icon-placeholder:before,.vjs-icon-cancel:before{content:"\f119"}.vjs-icon-repeat{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-repeat:before{content:"\f11a"}.video-js .vjs-play-control.vjs-ended .vjs-icon-placeholder,.vjs-icon-replay{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-play-control.vjs-ended .vjs-icon-placeholder:before,.vjs-icon-replay:before{content:"\f11b"}.video-js .vjs-skip-backward-5 .vjs-icon-placeholder,.vjs-icon-replay-5{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-skip-backward-5 .vjs-icon-placeholder:before,.vjs-icon-replay-5:before{content:"\f11c"}.video-js .vjs-skip-backward-10 .vjs-icon-placeholder,.vjs-icon-replay-10{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-skip-backward-10 .vjs-icon-placeholder:before,.vjs-icon-replay-10:before{content:"\f11d"}.video-js .vjs-skip-backward-30 .vjs-icon-placeholder,.vjs-icon-replay-30{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-skip-backward-30 .vjs-icon-placeholder:before,.vjs-icon-replay-30:before{content:"\f11e"}.video-js .vjs-skip-forward-5 .vjs-icon-placeholder,.vjs-icon-forward-5{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-skip-forward-5 .vjs-icon-placeholder:before,.vjs-icon-forward-5:before{content:"\f11f"}.video-js .vjs-skip-forward-10 .vjs-icon-placeholder,.vjs-icon-forward-10{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-skip-forward-10 .vjs-icon-placeholder:before,.vjs-icon-forward-10:before{content:"\f120"}.video-js .vjs-skip-forward-30 .vjs-icon-placeholder,.vjs-icon-forward-30{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-skip-forward-30 .vjs-icon-placeholder:before,.vjs-icon-forward-30:before{content:"\f121"}.video-js .vjs-audio-button .vjs-icon-placeholder,.vjs-icon-audio{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-audio-button .vjs-icon-placeholder:before,.vjs-icon-audio:before{content:"\f122"}.vjs-icon-next-item{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-next-item:before{content:"\f123"}.vjs-icon-previous-item{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-previous-item:before{content:"\f124"}.vjs-icon-shuffle{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-shuffle:before{content:"\f125"}.vjs-icon-cast{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-cast:before{content:"\f126"}.video-js .vjs-picture-in-picture-control .vjs-icon-placeholder,.vjs-icon-picture-in-picture-enter{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-picture-in-picture-control .vjs-icon-placeholder:before,.vjs-icon-picture-in-picture-enter:before{content:"\f127"}.video-js.vjs-picture-in-picture .vjs-picture-in-picture-control .vjs-icon-placeholder,.vjs-icon-picture-in-picture-exit{font-family:VideoJS;font-weight:400;font-style:normal}.video-js.vjs-picture-in-picture .vjs-picture-in-picture-control .vjs-icon-placeholder:before,.vjs-icon-picture-in-picture-exit:before{content:"\f128"}.vjs-icon-facebook{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-facebook:before{content:"\f129"}.vjs-icon-linkedin{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-linkedin:before{content:"\f12a"}.vjs-icon-twitter{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-twitter:before{content:"\f12b"}.vjs-icon-tumblr{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-tumblr:before{content:"\f12c"}.vjs-icon-pinterest{font-family:VideoJS;font-weight:400;font-style:normal}.vjs-icon-pinterest:before{content:"\f12d"}.video-js .vjs-descriptions-button .vjs-icon-placeholder,.vjs-icon-audio-description{font-family:VideoJS;font-weight:400;font-style:normal}.video-js .vjs-descriptions-button .vjs-icon-placeholder:before,.vjs-icon-audio-description:before{content:"\f12e"}.video-js{display:inline-block;vertical-align:top;box-sizing:border-box;color:#fff;background-color:#000;position:relative;padding:0;font-size:10px;line-height:1;font-weight:400;font-style:normal;font-family:Arial,Helvetica,sans-serif;word-break:normal}.video-js:-moz-full-screen{position:absolute}.video-js:-webkit-full-screen{width:100%!important;height:100%!important}.video-js[tabindex="-1"]{outline:none}.video-js *,.video-js :after,.video-js :before{box-sizing:inherit}.video-js ul{font-family:inherit;font-size:inherit;line-height:inherit;list-style-position:outside;margin:0}.video-js.vjs-1-1,.video-js.vjs-16-9,.video-js.vjs-4-3,.video-js.vjs-9-16,.video-js.vjs-fluid{width:100%;max-width:100%}.video-js.vjs-1-1:not(.vjs-audio-only-mode),.video-js.vjs-16-9:not(.vjs-audio-only-mode),.video-js.vjs-4-3:not(.vjs-audio-only-mode),.video-js.vjs-9-16:not(.vjs-audio-only-mode),.video-js.vjs-fluid:not(.vjs-audio-only-mode){height:0}.video-js.vjs-16-9:not(.vjs-audio-only-mode){padding-top:56.25%}.video-js.vjs-4-3:not(.vjs-audio-only-mode){padding-top:75%}.video-js.vjs-9-16:not(.vjs-audio-only-mode){padding-top:177.7777777778%}.video-js.vjs-1-1:not(.vjs-audio-only-mode){padding-top:100%}.video-js .vjs-tech,.video-js.vjs-fill:not(.vjs-audio-only-mode){width:100%;height:100%}.video-js .vjs-tech{position:absolute;top:0;left:0}.video-js.vjs-audio-only-mode .vjs-tech{display:none}body.vjs-full-window,body.vjs-pip-window{padding:0;margin:0;height:100%}.vjs-full-window .video-js.vjs-fullscreen,body.vjs-pip-window .video-js{position:fixed;overflow:hidden;z-index:1000;left:0;top:0;bottom:0;right:0}.video-js.vjs-fullscreen:not(.vjs-ios-native-fs),body.vjs-pip-window .video-js{width:100%!important;height:100%!important;padding-top:0!important;display:block}.video-js.vjs-fullscreen.vjs-user-inactive{cursor:none}.vjs-pip-container .vjs-pip-text{position:absolute;bottom:10%;font-size:2em;background-color:rgba(0,0,0,.7);padding:.5em;text-align:center;width:100%}.vjs-layout-small.vjs-pip-container .vjs-pip-text,.vjs-layout-tiny.vjs-pip-container .vjs-pip-text,.vjs-layout-x-small.vjs-pip-container .vjs-pip-text{bottom:0;font-size:1.4em}.vjs-hidden{display:none!important}.vjs-disabled{opacity:.5;cursor:default}.video-js .vjs-offscreen{height:1px;left:-9999px;position:absolute;top:0;width:1px}.vjs-lock-showing{display:block!important;opacity:1!important;visibility:visible!important}.vjs-no-js{padding:20px;color:#fff;background-color:#000;font-size:18px;font-family:Arial,Helvetica,sans-serif;text-align:center;width:300px;height:150px;margin:0 auto}.vjs-no-js a,.vjs-no-js a:visited{color:#66A8CC}.video-js .vjs-big-play-button{font-size:3em;line-height:1.5em;height:1.63332em;width:3em;display:block;position:absolute;top:50%;left:50%;padding:0;margin-top:-.81666em;margin-left:-1.5em;cursor:pointer;opacity:1;border:.06666em solid #fff;background-color:#2B333F;background-color:rgba(43,51,63,.7);border-radius:.3em;transition:all .4s}.vjs-big-play-button .vjs-svg-icon{width:1em;height:1em;position:absolute;top:50%;left:50%;line-height:1;transform:translate(-50%,-50%)}.video-js .vjs-big-play-button:focus,.video-js:hover .vjs-big-play-button{border-color:#fff;background-color:#73859f;background-color:rgba(115,133,159,.5);transition:all 0s}.vjs-controls-disabled .vjs-big-play-button,.vjs-error .vjs-big-play-button,.vjs-has-started .vjs-big-play-button,.vjs-using-native-controls .vjs-big-play-button{display:none}.vjs-has-started.vjs-paused.vjs-show-big-play-button-on-pause:not(.vjs-seeking,.vjs-scrubbing,.vjs-error) .vjs-big-play-button{display:block}.video-js button{background:none;border:none;color:inherit;display:inline-block;font-size:inherit;line-height:inherit;text-transform:none;text-decoration:none;transition:none;-webkit-appearance:none;-moz-appearance:none;appearance:none}.video-js.vjs-spatial-navigation-enabled .vjs-button:focus{outline:.0625em solid white;box-shadow:none}.vjs-control .vjs-button{width:100%;height:100%}.video-js .vjs-control.vjs-close-button{cursor:pointer;height:3em;position:absolute;right:0;top:.5em;z-index:2}.video-js .vjs-modal-dialog{background:rgba(0,0,0,.8);background:linear-gradient(180deg,rgba(0,0,0,.8),rgba(255,255,255,0));overflow:auto}.video-js .vjs-modal-dialog>*{box-sizing:border-box}.vjs-modal-dialog .vjs-modal-dialog-content{font-size:1.2em;line-height:1.5;padding:20px 24px;z-index:1}.vjs-menu-button{cursor:pointer}.vjs-menu-button.vjs-disabled{cursor:default}.vjs-workinghover .vjs-menu-button.vjs-disabled:hover .vjs-menu{display:none}.vjs-menu .vjs-menu-content{display:block;padding:0;margin:0;font-family:Arial,Helvetica,sans-serif;overflow:auto}.vjs-menu .vjs-menu-content>*{box-sizing:border-box}.vjs-scrubbing .vjs-control.vjs-menu-button:hover .vjs-menu{display:none}.vjs-menu li{display:flex;justify-content:center;list-style:none;margin:0;padding:.2em 0;line-height:1.4em;font-size:1.2em;text-align:center;text-transform:lowercase}.js-focus-visible .vjs-menu li.vjs-menu-item:hover,.vjs-menu li.vjs-menu-item:focus,.vjs-menu li.vjs-menu-item:hover{background-color:#73859f;background-color:rgba(115,133,159,.5)}.js-focus-visible .vjs-menu li.vjs-selected:hover,.vjs-menu li.vjs-selected,.vjs-menu li.vjs-selected:focus,.vjs-menu li.vjs-selected:hover{background-color:#fff;color:#2B333F}.js-focus-visible .vjs-menu li.vjs-selected:hover .vjs-svg-icon,.vjs-menu li.vjs-selected .vjs-svg-icon,.vjs-menu li.vjs-selected:focus .vjs-svg-icon,.vjs-menu li.vjs-selected:hover .vjs-svg-icon{fill:#000000}.js-focus-visible .vjs-menu :not(.vjs-selected):focus:not(.focus-visible),.video-js .vjs-menu :not(.vjs-selected):focus:not(:focus-visible){background:none}.vjs-menu li.vjs-menu-title{text-align:center;text-transform:uppercase;font-size:1em;line-height:2em;padding:0;margin:0 0 .3em;font-weight:700;cursor:default}.vjs-menu-button-popup .vjs-menu{display:none;position:absolute;bottom:0;width:10em;left:-3em;height:0;margin-bottom:1.5em;border-top-color:rgba(43,51,63,.7)}.vjs-pip-window .vjs-menu-button-popup .vjs-menu{left:unset;right:1em}.vjs-menu-button-popup .vjs-menu .vjs-menu-content{background-color:#2B333F;background-color:rgba(43,51,63,.7);position:absolute;width:100%;bottom:1.5em;max-height:15em}.vjs-layout-tiny .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-x-small .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:5em}.vjs-layout-small .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:10em}.vjs-layout-medium .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:14em}.vjs-layout-huge .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-large .vjs-menu-button-popup .vjs-menu .vjs-menu-content,.vjs-layout-x-large .vjs-menu-button-popup .vjs-menu .vjs-menu-content{max-height:25em}.vjs-menu-button-popup .vjs-menu.vjs-lock-showing,.vjs-workinghover .vjs-menu-button-popup.vjs-hover .vjs-menu{display:block}.video-js .vjs-menu-button-inline{transition:all .4s;overflow:hidden}.video-js .vjs-menu-button-inline:before{width:2.222222222em}.video-js .vjs-menu-button-inline.vjs-slider-active,.video-js .vjs-menu-button-inline:focus,.video-js .vjs-menu-button-inline:hover{width:12em}.vjs-menu-button-inline .vjs-menu{opacity:0;height:100%;width:auto;position:absolute;left:4em;top:0;padding:0;margin:0;transition:all .4s}.vjs-menu-button-inline.vjs-slider-active .vjs-menu,.vjs-menu-button-inline:focus .vjs-menu,.vjs-menu-button-inline:hover .vjs-menu{display:block;opacity:1}.vjs-menu-button-inline .vjs-menu-content{width:auto;height:100%;margin:0;overflow:hidden}.video-js .vjs-control-bar{display:none;width:100%;position:absolute;bottom:0;left:0;right:0;height:3em;background-color:#2B333F;background-color:rgba(43,51,63,.7)}.video-js.vjs-spatial-navigation-enabled .vjs-control-bar{gap:1px}.video-js:not(.vjs-controls-disabled,.vjs-using-native-controls,.vjs-error) .vjs-control-bar.vjs-lock-showing{display:flex!important}.vjs-audio-only-mode .vjs-control-bar,.vjs-has-started .vjs-control-bar{display:flex;visibility:visible;opacity:1;transition:visibility .1s,opacity .1s}.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar{visibility:visible;opacity:0;pointer-events:none;transition:visibility 1s,opacity 1s}.vjs-controls-disabled .vjs-control-bar,.vjs-error .vjs-control-bar,.vjs-using-native-controls .vjs-control-bar{display:none!important}.vjs-audio-only-mode.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar,.vjs-audio.vjs-has-started.vjs-user-inactive.vjs-playing .vjs-control-bar{opacity:1;visibility:visible;pointer-events:auto}.video-js .vjs-control{position:relative;text-align:center;margin:0;padding:0;height:100%;width:4em;flex:none}.video-js .vjs-control.vjs-visible-text{width:auto;padding-left:1em;padding-right:1em}.vjs-button>.vjs-icon-placeholder:before{font-size:1.8em;line-height:1.67}.vjs-button>.vjs-icon-placeholder{display:block}.vjs-button>.vjs-svg-icon{display:inline-block}.video-js .vjs-control:focus,.video-js .vjs-control:focus:before,.video-js .vjs-control:hover:before{text-shadow:0 0 1em white}.video-js :not(.vjs-visible-text)>.vjs-control-text{border:0;clip:rect(0 0 0 0);height:1px;overflow:hidden;padding:0;position:absolute;width:1px}.video-js .vjs-custom-control-spacer{display:none}.video-js .vjs-progress-control{cursor:pointer;flex:auto;display:flex;align-items:center;min-width:4em;touch-action:none}.video-js .vjs-progress-control.disabled{cursor:default}.vjs-live .vjs-progress-control{display:none}.vjs-liveui .vjs-progress-control{display:flex;align-items:center}.video-js .vjs-progress-holder{flex:auto;transition:all .2s;height:.3em}.video-js .vjs-progress-control .vjs-progress-holder{margin:0 10px}.video-js .vjs-progress-control:hover .vjs-progress-holder,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-progress-holder{font-size:1.6666666667em}.video-js .vjs-progress-control:hover .vjs-progress-holder.disabled{font-size:1em}.video-js .vjs-progress-holder .vjs-load-progress,.video-js .vjs-progress-holder .vjs-load-progress div,.video-js .vjs-progress-holder .vjs-play-progress{position:absolute;display:block;height:100%;margin:0;padding:0;width:0}.video-js .vjs-play-progress{background-color:#fff}.video-js .vjs-play-progress:before{font-size:.9em;position:absolute;right:-.5em;line-height:.35em;z-index:1}.vjs-svg-icons-enabled .vjs-play-progress:before{content:none!important}.vjs-play-progress .vjs-svg-icon{position:absolute;top:-.35em;right:-.4em;width:.9em;height:.9em;pointer-events:none;line-height:.15em;z-index:1}.video-js .vjs-load-progress{background:rgba(115,133,159,.5)}.video-js .vjs-load-progress div{background:rgba(115,133,159,.75)}.video-js .vjs-time-tooltip{background-color:#fff;background-color:rgba(255,255,255,.8);border-radius:.3em;color:#000;float:right;font-family:Arial,Helvetica,sans-serif;font-size:1em;padding:6px 8px 8px;pointer-events:none;position:absolute;top:-3.4em;visibility:hidden;z-index:1}.video-js .vjs-progress-holder:focus .vjs-time-tooltip{display:none}.video-js .vjs-progress-control:hover .vjs-progress-holder:focus .vjs-time-tooltip,.video-js .vjs-progress-control:hover .vjs-time-tooltip,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-time-tooltip{display:block;font-size:.6em;visibility:visible}.video-js .vjs-progress-control.disabled:hover .vjs-time-tooltip{font-size:1em}.video-js .vjs-progress-control .vjs-mouse-display{display:none;position:absolute;width:1px;height:100%;background-color:#000;z-index:1}.video-js .vjs-progress-control:hover .vjs-mouse-display,.video-js.vjs-scrubbing.vjs-touch-enabled .vjs-progress-control .vjs-mouse-display{display:block}.video-js.vjs-user-inactive .vjs-progress-control .vjs-mouse-display{visibility:hidden;opacity:0;transition:visibility 1s,opacity 1s}.vjs-mouse-display .vjs-time-tooltip{color:#fff;background-color:#000;background-color:rgba(0,0,0,.8)}.video-js .vjs-slider{position:relative;cursor:pointer;padding:0;margin:0 .45em;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;background-color:#73859f;background-color:rgba(115,133,159,.5)}.video-js .vjs-slider.disabled{cursor:default}.video-js .vjs-slider:focus{text-shadow:0 0 1em white;box-shadow:0 0 1em #fff}.video-js.vjs-spatial-navigation-enabled .vjs-slider:focus{outline:.0625em solid white}.video-js .vjs-mute-control{cursor:pointer;flex:none}.video-js .vjs-volume-control{cursor:pointer;margin-right:1em;display:flex}.video-js .vjs-volume-control.vjs-volume-horizontal{width:5em}.video-js .vjs-volume-panel .vjs-volume-control{visibility:visible;opacity:0;width:1px;height:1px;margin-left:-1px}.video-js .vjs-volume-panel{transition:width 1s}.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active,.video-js .vjs-volume-panel .vjs-volume-control:active,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control,.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control,.video-js .vjs-volume-panel:active .vjs-volume-control,.video-js .vjs-volume-panel:focus .vjs-volume-control{visibility:visible;opacity:1;position:relative;transition:visibility .1s,opacity .1s,height .1s,width .1s,left 0s,top 0s}.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active.vjs-volume-horizontal,.video-js .vjs-volume-panel .vjs-volume-control:active.vjs-volume-horizontal,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel:active .vjs-volume-control.vjs-volume-horizontal,.video-js .vjs-volume-panel:focus .vjs-volume-control.vjs-volume-horizontal{width:5em;height:3em;margin-right:0}.video-js .vjs-volume-panel .vjs-volume-control.vjs-slider-active.vjs-volume-vertical,.video-js .vjs-volume-panel .vjs-volume-control:active.vjs-volume-vertical,.video-js .vjs-volume-panel.vjs-hover .vjs-mute-control~.vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel.vjs-hover .vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel:active .vjs-volume-control.vjs-volume-vertical,.video-js .vjs-volume-panel:focus .vjs-volume-control.vjs-volume-vertical{left:-3.5em;transition:left 0s}.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js .vjs-volume-panel.vjs-volume-panel-horizontal:active{width:10em;transition:width .1s}.video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-mute-toggle-only{width:4em}.video-js .vjs-volume-panel .vjs-volume-control.vjs-volume-vertical{height:8em;width:3em;left:-3000em;transition:visibility 1s,opacity 1s,height 1s 1s,width 1s 1s,left 1s 1s,top 1s 1s}.video-js .vjs-volume-panel .vjs-volume-control.vjs-volume-horizontal{transition:visibility 1s,opacity 1s,height 1s 1s,width 1s,left 1s 1s,top 1s 1s}.video-js .vjs-volume-panel{display:flex}.video-js .vjs-volume-bar{margin:1.35em .45em}.vjs-volume-bar.vjs-slider-horizontal{width:5em;height:.3em}.vjs-volume-bar.vjs-slider-vertical{width:.3em;height:5em;margin:1.35em auto}.video-js .vjs-volume-level{position:absolute;bottom:0;left:0;background-color:#fff}.video-js .vjs-volume-level:before{position:absolute;font-size:.9em;z-index:1}.vjs-slider-vertical .vjs-volume-level{width:.3em}.vjs-slider-vertical .vjs-volume-level:before{top:-.5em;left:-.3em;z-index:1}.vjs-svg-icons-enabled .vjs-volume-level:before{content:none}.vjs-volume-level .vjs-svg-icon{position:absolute;width:.9em;height:.9em;pointer-events:none;z-index:1}.vjs-slider-horizontal .vjs-volume-level{height:.3em}.vjs-slider-horizontal .vjs-volume-level:before{line-height:.35em;right:-.5em}.vjs-slider-horizontal .vjs-volume-level .vjs-svg-icon{right:-.3em;transform:translateY(-50%)}.vjs-slider-vertical .vjs-volume-level .vjs-svg-icon{top:-.55em;transform:translateX(-50%)}.video-js .vjs-volume-panel.vjs-volume-panel-vertical{width:4em}.vjs-volume-bar.vjs-slider-vertical .vjs-volume-level{height:100%}.vjs-volume-bar.vjs-slider-horizontal .vjs-volume-level{width:100%}.video-js .vjs-volume-vertical{width:3em;height:8em;bottom:8em;background-color:#2B333F;background-color:rgba(43,51,63,.7)}.video-js .vjs-volume-horizontal .vjs-menu{left:-2em}.video-js .vjs-volume-tooltip{background-color:#fff;background-color:rgba(255,255,255,.8);border-radius:.3em;color:#000;float:right;font-family:Arial,Helvetica,sans-serif;font-size:1em;padding:6px 8px 8px;pointer-events:none;position:absolute;top:-3.4em;visibility:hidden;z-index:1}.video-js .vjs-volume-control:hover .vjs-progress-holder:focus .vjs-volume-tooltip,.video-js .vjs-volume-control:hover .vjs-volume-tooltip{display:block;font-size:1em;visibility:visible}.video-js .vjs-volume-vertical:hover .vjs-progress-holder:focus .vjs-volume-tooltip,.video-js .vjs-volume-vertical:hover .vjs-volume-tooltip{left:1em;top:-12px}.video-js .vjs-volume-control.disabled:hover .vjs-volume-tooltip{font-size:1em}.video-js .vjs-volume-control .vjs-mouse-display{display:none;position:absolute;width:100%;height:1px;background-color:#000;z-index:1}.video-js .vjs-volume-horizontal .vjs-mouse-display{width:1px;height:100%}.video-js .vjs-volume-control:hover .vjs-mouse-display{display:block}.video-js.vjs-user-inactive .vjs-volume-control .vjs-mouse-display{visibility:hidden;opacity:0;transition:visibility 1s,opacity 1s}.vjs-mouse-display .vjs-volume-tooltip{color:#fff;background-color:#000;background-color:rgba(0,0,0,.8)}.vjs-poster{display:inline-block;vertical-align:middle;cursor:pointer;margin:0;padding:0;position:absolute;top:0;right:0;bottom:0;left:0;height:100%}.vjs-has-started .vjs-poster,.vjs-using-native-controls .vjs-poster{display:none}.vjs-audio.vjs-has-started .vjs-poster,.vjs-has-started.vjs-audio-poster-mode .vjs-poster,.vjs-pip-container.vjs-has-started .vjs-poster{display:block}.vjs-poster img{width:100%;height:100%;object-fit:contain}.video-js .vjs-live-control{display:flex;align-items:flex-start;flex:auto;font-size:1em;line-height:3em}.video-js.vjs-liveui .vjs-live-control,.video-js:not(.vjs-live) .vjs-live-control{display:none}.video-js .vjs-seek-to-live-control{align-items:center;cursor:pointer;flex:none;display:inline-flex;height:100%;padding-left:.5em;padding-right:.5em;font-size:1em;line-height:3em;width:auto;min-width:4em}.video-js.vjs-live:not(.vjs-liveui) .vjs-seek-to-live-control,.video-js:not(.vjs-live) .vjs-seek-to-live-control{display:none}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge{cursor:auto}.vjs-seek-to-live-control .vjs-icon-placeholder{margin-right:.5em;color:#888}.vjs-svg-icons-enabled .vjs-seek-to-live-control{line-height:0}.vjs-seek-to-live-control .vjs-svg-icon{width:1em;height:1em;pointer-events:none;fill:#888888}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge .vjs-icon-placeholder{color:red}.vjs-seek-to-live-control.vjs-control.vjs-at-live-edge .vjs-svg-icon{fill:red}.video-js .vjs-time-control{flex:none;font-size:1em;line-height:3em;min-width:2em;width:auto;padding-left:1em;padding-right:1em}.video-js .vjs-current-time,.video-js .vjs-duration,.vjs-live .vjs-time-control,.vjs-live .vjs-time-divider{display:none}.vjs-time-divider{display:none;line-height:3em}.vjs-normalise-time-controls:not(.vjs-live) .vjs-time-control{display:flex}.video-js .vjs-play-control{cursor:pointer}.video-js .vjs-play-control .vjs-icon-placeholder{flex:none}.vjs-text-track-display{position:absolute;bottom:3em;left:0;right:0;top:0;pointer-events:none}.vjs-error .vjs-text-track-display{display:none}.video-js.vjs-controls-disabled .vjs-text-track-display,.video-js.vjs-user-inactive.vjs-playing .vjs-text-track-display{bottom:1em}.video-js .vjs-text-track{font-size:1.4em;text-align:center;margin-bottom:.1em}.vjs-subtitles{color:#fff}.vjs-captions{color:#fc6}.vjs-tt-cue{display:block}video::-webkit-media-text-track-display{transform:translateY(-3em)}.video-js.vjs-controls-disabled video::-webkit-media-text-track-display,.video-js.vjs-user-inactive.vjs-playing video::-webkit-media-text-track-display{transform:translateY(-1.5em)}.video-js.vjs-force-center-align-cues .vjs-text-track-cue{text-align:center!important;width:80%!important}@supports not (inset:10px){.video-js .vjs-text-track-display>div{top:0;right:0;bottom:0;left:0}}.video-js .vjs-picture-in-picture-control{cursor:pointer;flex:none}.video-js.vjs-audio-only-mode .vjs-picture-in-picture-control,.vjs-pip-window .vjs-picture-in-picture-control{display:none}.video-js .vjs-fullscreen-control{cursor:pointer;flex:none}.video-js.vjs-audio-only-mode .vjs-fullscreen-control,.vjs-pip-window .vjs-fullscreen-control{display:none}.vjs-playback-rate .vjs-playback-rate-value,.vjs-playback-rate>.vjs-menu-button{position:absolute;top:0;left:0;width:100%;height:100%}.vjs-playback-rate .vjs-playback-rate-value{pointer-events:none;font-size:1.5em;line-height:2;text-align:center}.vjs-playback-rate .vjs-menu{width:4em;left:0}.vjs-error .vjs-error-display .vjs-modal-dialog-content{font-size:1.4em;text-align:center}.vjs-loading-spinner{display:none;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);opacity:.85;text-align:left;border:.6em solid rgba(43,51,63,.7);box-sizing:border-box;background-clip:padding-box;width:5em;height:5em;border-radius:50%;visibility:hidden}.vjs-seeking .vjs-loading-spinner,.vjs-waiting .vjs-loading-spinner{display:flex;justify-content:center;align-items:center;animation:vjs-spinner-show 0s linear .3s forwards}.vjs-error .vjs-loading-spinner{display:none}.vjs-loading-spinner:after,.vjs-loading-spinner:before{content:"";position:absolute;box-sizing:inherit;width:inherit;height:inherit;border-radius:inherit;opacity:1;border:inherit;border-color:white transparent transparent}.vjs-seeking .vjs-loading-spinner:after,.vjs-seeking .vjs-loading-spinner:before,.vjs-waiting .vjs-loading-spinner:after,.vjs-waiting .vjs-loading-spinner:before{animation:vjs-spinner-spin 1.1s cubic-bezier(.6,.2,0,.8) infinite,vjs-spinner-fade 1.1s linear infinite}.vjs-seeking .vjs-loading-spinner:before,.vjs-waiting .vjs-loading-spinner:before{border-top-color:rgb(255,255,255)}.vjs-seeking .vjs-loading-spinner:after,.vjs-waiting .vjs-loading-spinner:after{border-top-color:rgb(255,255,255);animation-delay:.44s}@keyframes vjs-spinner-show{to{visibility:visible}}@keyframes vjs-spinner-spin{to{transform:rotate(1turn)}}@keyframes vjs-spinner-fade{0%{border-top-color:#73859f}20%{border-top-color:#73859f}35%{border-top-color:white}60%{border-top-color:#73859f}to{border-top-color:#73859f}}.video-js.vjs-audio-only-mode .vjs-captions-button{display:none}.vjs-chapters-button .vjs-menu ul{width:24em}.video-js.vjs-audio-only-mode .vjs-descriptions-button{display:none}.vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-svg-icon{width:1.5em;height:1.5em}.video-js .vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-menu-item-text .vjs-icon-placeholder{vertical-align:middle;display:inline-block;margin-bottom:-.1em}.video-js .vjs-subs-caps-button+.vjs-menu .vjs-captions-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before{font-family:VideoJS;content:"\f10c";font-size:1.5em;line-height:inherit}.video-js.vjs-audio-only-mode .vjs-subs-caps-button{display:none}.video-js .vjs-audio-button+.vjs-menu .vjs-descriptions-menu-item .vjs-menu-item-text .vjs-icon-placeholder,.video-js .vjs-audio-button+.vjs-menu .vjs-main-desc-menu-item .vjs-menu-item-text .vjs-icon-placeholder{vertical-align:middle;display:inline-block;margin-bottom:-.1em}.video-js .vjs-audio-button+.vjs-menu .vjs-descriptions-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before,.video-js .vjs-audio-button+.vjs-menu .vjs-main-desc-menu-item .vjs-menu-item-text .vjs-icon-placeholder:before{font-family:VideoJS;content:" \f12e";font-size:1.5em;line-height:inherit}.video-js.vjs-layout-small .vjs-current-time,.video-js.vjs-layout-small .vjs-duration,.video-js.vjs-layout-small .vjs-playback-rate,.video-js.vjs-layout-small .vjs-remaining-time,.video-js.vjs-layout-small .vjs-time-divider,.video-js.vjs-layout-small .vjs-volume-control,.video-js.vjs-layout-tiny .vjs-current-time,.video-js.vjs-layout-tiny .vjs-duration,.video-js.vjs-layout-tiny .vjs-playback-rate,.video-js.vjs-layout-tiny .vjs-remaining-time,.video-js.vjs-layout-tiny .vjs-time-divider,.video-js.vjs-layout-tiny .vjs-volume-control,.video-js.vjs-layout-x-small .vjs-current-time,.video-js.vjs-layout-x-small .vjs-duration,.video-js.vjs-layout-x-small .vjs-playback-rate,.video-js.vjs-layout-x-small .vjs-remaining-time,.video-js.vjs-layout-x-small .vjs-time-divider,.video-js.vjs-layout-x-small .vjs-volume-control{display:none}.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-small .vjs-volume-panel.vjs-volume-panel-horizontal:hover,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-tiny .vjs-volume-panel.vjs-volume-panel-horizontal:hover,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-hover,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal:active,.video-js.vjs-layout-x-small .vjs-volume-panel.vjs-volume-panel-horizontal:hover{width:auto}.video-js.vjs-layout-tiny .vjs-progress-control,.video-js.vjs-layout-x-small .vjs-progress-control{display:none}.video-js.vjs-layout-x-small .vjs-custom-control-spacer{flex:auto;display:block}.vjs-modal-dialog.vjs-text-track-settings{background-color:#2B333F;background-color:rgba(43,51,63,.75);color:#fff;height:70%}.vjs-spatial-navigation-enabled .vjs-modal-dialog.vjs-text-track-settings{height:80%}.vjs-error .vjs-text-track-settings{display:none}.vjs-text-track-settings .vjs-modal-dialog-content{display:table}.vjs-text-track-settings .vjs-track-settings-colors,.vjs-text-track-settings .vjs-track-settings-controls,.vjs-text-track-settings .vjs-track-settings-font{display:table-cell}.vjs-text-track-settings .vjs-track-settings-controls{text-align:right;vertical-align:bottom}@supports (display:grid){.vjs-text-track-settings .vjs-modal-dialog-content{display:grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr;padding:20px 24px 0}.vjs-track-settings-controls .vjs-default-button{margin-bottom:20px}.vjs-text-track-settings .vjs-track-settings-controls{grid-column:1/-1}.vjs-layout-small .vjs-text-track-settings .vjs-modal-dialog-content,.vjs-layout-tiny .vjs-text-track-settings .vjs-modal-dialog-content,.vjs-layout-x-small .vjs-text-track-settings .vjs-modal-dialog-content{grid-template-columns:1fr}}.vjs-text-track-settings select{font-size:inherit}.vjs-track-setting>select{margin-right:1em;margin-bottom:.5em}.vjs-text-track-settings fieldset{margin:10px;border:none}.vjs-text-track-settings fieldset span{display:inline-block;padding:0 .6em .8em}.vjs-text-track-settings fieldset span>select{max-width:7.3em}.vjs-text-track-settings legend{color:#fff;font-weight:700;font-size:1.2em}.vjs-text-track-settings .vjs-label{margin:0 .5em .5em 0}.vjs-track-settings-controls button:active,.vjs-track-settings-controls button:focus{outline-style:solid;outline-width:medium;background-image:linear-gradient(0deg,#fff 88%,#73859f)}.vjs-track-settings-controls button:hover{color:rgba(43,51,63,.75)}.vjs-track-settings-controls button{background-color:#fff;background-image:linear-gradient(-180deg,#fff 88%,#73859f);color:#2B333F;cursor:pointer;border-radius:2px}.vjs-track-settings-controls .vjs-default-button{margin-right:1em}.vjs-title-bar{background:rgba(0,0,0,.9);background:linear-gradient(180deg,rgba(0,0,0,.9),rgba(0,0,0,.7) 60%,rgba(0,0,0,0));font-size:1.2em;line-height:1.5;transition:opacity .1s;padding:.666em 1.333em 4em;pointer-events:none;position:absolute;top:0;width:100%}.vjs-error .vjs-title-bar{display:none}.vjs-title-bar-description,.vjs-title-bar-title{margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vjs-title-bar-title{font-weight:700;margin-bottom:.333em}.vjs-playing.vjs-user-inactive .vjs-title-bar{opacity:0;transition:opacity 1s}.video-js .vjs-skip-backward-10,.video-js .vjs-skip-backward-30,.video-js .vjs-skip-backward-5,.video-js .vjs-skip-forward-10,.video-js .vjs-skip-forward-30,.video-js .vjs-skip-forward-5{cursor:pointer}.video-js .vjs-transient-button{position:absolute;height:3em;display:flex;align-items:center;justify-content:center;background-color:rgba(50,50,50,.5);cursor:pointer;opacity:1;transition:opacity 1s}.video-js:not(.vjs-has-started) .vjs-transient-button{display:none}.video-js.not-hover .vjs-transient-button:not(.force-display),.video-js.vjs-user-inactive .vjs-transient-button:not(.force-display){opacity:0}.video-js .vjs-transient-button span{padding:0 .5em}.video-js .vjs-transient-button.vjs-left{left:1em}.video-js .vjs-transient-button.vjs-right{right:1em}.video-js .vjs-transient-button.vjs-top{top:1em}.video-js .vjs-transient-button.vjs-near-top{top:4em}.video-js .vjs-transient-button.vjs-bottom{bottom:4em}.video-js .vjs-transient-button:hover{background-color:rgba(50,50,50,.9)}@media print{.video-js>:not(.vjs-tech):not(.vjs-poster){visibility:hidden}}.vjs-resize-manager{position:absolute;top:0;left:0;width:100%;height:100%;border:none;z-index:-1000}.js-focus-visible .video-js :focus:not(.focus-visible){outline:none}.video-js :focus:not(:focus-visible){outline:none} \ No newline at end of file diff --git a/services/v1/media/feedback/static/_next/static/media/569ce4b8f30dc480-s.p.woff2 b/services/v1/media/feedback/static/_next/static/media/569ce4b8f30dc480-s.p.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..445e0e55cbb80e4a1fd7d429c4384b61b453da2b Binary files /dev/null and b/services/v1/media/feedback/static/_next/static/media/569ce4b8f30dc480-s.p.woff2 differ diff --git a/services/v1/media/feedback/static/_next/static/media/747892c23ea88013-s.woff2 b/services/v1/media/feedback/static/_next/static/media/747892c23ea88013-s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..944424f972b9f9c985163da8096a25b214fa1983 Binary files /dev/null and b/services/v1/media/feedback/static/_next/static/media/747892c23ea88013-s.woff2 differ diff --git a/services/v1/media/feedback/static/_next/static/media/93f479601ee12b01-s.p.woff2 b/services/v1/media/feedback/static/_next/static/media/93f479601ee12b01-s.p.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..68eeb7f4bd4a789bc1600f76e6ebac0a0c170d46 Binary files /dev/null and b/services/v1/media/feedback/static/_next/static/media/93f479601ee12b01-s.p.woff2 differ diff --git a/services/v1/media/feedback/static/_next/static/media/ba015fad6dcf6784-s.woff2 b/services/v1/media/feedback/static/_next/static/media/ba015fad6dcf6784-s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..e36649933f3a206057fe1068cff2e5078f043c59 Binary files /dev/null and b/services/v1/media/feedback/static/_next/static/media/ba015fad6dcf6784-s.woff2 differ diff --git a/services/v1/media/feedback/static/favicon.ico b/services/v1/media/feedback/static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..1bf491a7bfdbd45882f69bf16e1f3be7e209e67a Binary files /dev/null and b/services/v1/media/feedback/static/favicon.ico differ diff --git a/services/v1/media/feedback/static/file.svg b/services/v1/media/feedback/static/file.svg new file mode 100644 index 0000000000000000000000000000000000000000..004145cddf3f9db91b57b9cb596683c8eb420862 --- /dev/null +++ b/services/v1/media/feedback/static/file.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services/v1/media/feedback/static/globe.svg b/services/v1/media/feedback/static/globe.svg new file mode 100644 index 0000000000000000000000000000000000000000..567f17b0d7c7fb662c16d4357dd74830caf2dccb --- /dev/null +++ b/services/v1/media/feedback/static/globe.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services/v1/media/feedback/static/index.html b/services/v1/media/feedback/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..177f72099ebc6d1080c4303faf77643e05c5211c --- /dev/null +++ b/services/v1/media/feedback/static/index.html @@ -0,0 +1,15 @@ +Feedback Magic v1.0
logo

Hola muuundo

\ No newline at end of file diff --git a/services/v1/media/feedback/static/index.txt b/services/v1/media/feedback/static/index.txt new file mode 100644 index 0000000000000000000000000000000000000000..f4d3fe740edfdb6e5ac3de3a95354e2e45f4a090 --- /dev/null +++ b/services/v1/media/feedback/static/index.txt @@ -0,0 +1,20 @@ +1:"$Sreact.fragment" +2:I[5244,[],""] +3:I[3866,[],""] +4:I[7033,[],"ClientPageRoot"] +5:I[7684,["776","static/chunks/0b465130-17d112986620d03b.js","742","static/chunks/9cb54ea0-3a1872b9717ef868.js","821","static/chunks/821-f382ea5118c8252b.js","974","static/chunks/app/page-f3889bc9ae1bdb7d.js"],"default"] +8:I[6213,[],"OutletBoundary"] +b:I[6213,[],"ViewportBoundary"] +d:I[6213,[],"MetadataBoundary"] +f:I[4835,[],""] +:HL["/_next/static/media/569ce4b8f30dc480-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}] +:HL["/_next/static/media/93f479601ee12b01-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}] +:HL["/_next/static/css/6c55a5ad1761972b.css","style"] +:HL["/_next/static/css/998a630a136a8118.css","style"] +0:{"P":null,"b":"IKZmjEopX3I__YqoGlhxM","p":"","c":["",""],"i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/6c55a5ad1761972b.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__variable_4d318d __variable_ea5f4b antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"$undefined",[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]}]]}],{"children":["__PAGE__",["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","searchParams":{},"params":{},"promises":["$@6","$@7"]}],"$undefined",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/998a630a136a8118.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]],["$","$L8",null,{"children":["$L9","$La",null]}]]}],{},null,false]},null,false],["$","$1","h",{"children":[null,["$","$1","IXaxZtthcBrG36U1lSNkw",{"children":[["$","$Lb",null,{"children":"$Lc"}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}],["$","$Ld",null,{"children":"$Le"}]]}],false]],"m":"$undefined","G":["$f","$undefined"],"s":false,"S":true} +6:{} +7:{} +c:[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]] +9:null +a:null +e:[["$","title","0",{"children":"Feedback Magic v1.0"}],["$","meta","1",{"name":"description","content":"Generated by create next app"}],["$","link","2",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"1483x1204"}]] diff --git a/services/v1/media/feedback/static/logo.png b/services/v1/media/feedback/static/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..1bf491a7bfdbd45882f69bf16e1f3be7e209e67a Binary files /dev/null and b/services/v1/media/feedback/static/logo.png differ diff --git a/services/v1/media/feedback/static/next.svg b/services/v1/media/feedback/static/next.svg new file mode 100644 index 0000000000000000000000000000000000000000..5174b28c565c285e3e312ec5178be64fbeca8398 --- /dev/null +++ b/services/v1/media/feedback/static/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services/v1/media/feedback/static/vercel.svg b/services/v1/media/feedback/static/vercel.svg new file mode 100644 index 0000000000000000000000000000000000000000..77053960334e2e34dc584dea8019925c3b4ccca9 --- /dev/null +++ b/services/v1/media/feedback/static/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services/v1/media/feedback/static/window.svg b/services/v1/media/feedback/static/window.svg new file mode 100644 index 0000000000000000000000000000000000000000..b2b2a44f6ebc70c450043c05a002e7a93ba5d651 --- /dev/null +++ b/services/v1/media/feedback/static/window.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/services/v1/media/media_transcribe.py b/services/v1/media/media_transcribe.py new file mode 100644 index 0000000000000000000000000000000000000000..4514a9f24f3ffcd4f92d26cb75a70226671f8351 --- /dev/null +++ b/services/v1/media/media_transcribe.py @@ -0,0 +1,157 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import whisper +import srt +from datetime import timedelta +from whisper.utils import WriteSRT, WriteVTT +from services.file_management import download_file +import logging +from config import LOCAL_STORAGE_PATH + +# Set up logging +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +def process_transcribe_media(media_url, task, include_text, include_srt, include_segments, word_timestamps, response_type, language, job_id, words_per_line=None): + """Transcribe or translate media and return the transcript/translation, SRT or VTT file path.""" + logger.info(f"Starting {task} for media URL: {media_url}") + input_filename = download_file(media_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input")) + logger.info(f"Downloaded media to local file: {input_filename}") + + try: + # Load a larger model for better translation quality + #model_size = "large" if task == "translate" else "base" + model_size = "base" + model = whisper.load_model(model_size) + logger.info(f"Loaded Whisper {model_size} model") + + # Configure transcription/translation options + options = { + "task": task, + "word_timestamps": word_timestamps, + "verbose": False + } + + # Add language specification if provided + if language: + options["language"] = language + + result = model.transcribe(input_filename, **options) + + # For translation task, the result['text'] will be in English + text = None + srt_text = None + segments_json = None + + logger.info(f"Generated {task} output") + + if include_text is True: + text = result['text'] + + if include_srt is True: + srt_subtitles = [] + subtitle_index = 1 + + if words_per_line and words_per_line > 0: + # Collect all words and their timings + all_words = [] + word_timings = [] + + for segment in result['segments']: + words = segment['text'].strip().split() + segment_start = segment['start'] + segment_end = segment['end'] + + # Calculate timing for each word + if words: + duration_per_word = (segment_end - segment_start) / len(words) + for i, word in enumerate(words): + word_start = segment_start + (i * duration_per_word) + word_end = word_start + duration_per_word + all_words.append(word) + word_timings.append((word_start, word_end)) + + # Process words in chunks of words_per_line + current_word = 0 + while current_word < len(all_words): + # Get the next chunk of words + chunk = all_words[current_word:current_word + words_per_line] + + # Calculate timing for this chunk + chunk_start = word_timings[current_word][0] + chunk_end = word_timings[min(current_word + len(chunk) - 1, len(word_timings) - 1)][1] + + # Create the subtitle + srt_subtitles.append(srt.Subtitle( + subtitle_index, + timedelta(seconds=chunk_start), + timedelta(seconds=chunk_end), + ' '.join(chunk) + )) + subtitle_index += 1 + current_word += words_per_line + else: + # Original behavior - one subtitle per segment + for segment in result['segments']: + start = timedelta(seconds=segment['start']) + end = timedelta(seconds=segment['end']) + segment_text = segment['text'].strip() + srt_subtitles.append(srt.Subtitle(subtitle_index, start, end, segment_text)) + subtitle_index += 1 + + srt_text = srt.compose(srt_subtitles) + + if include_segments is True: + segments_json = result['segments'] + + os.remove(input_filename) + logger.info(f"Removed local file: {input_filename}") + logger.info(f"{task.capitalize()} successful, output type: {response_type}") + + if response_type == "direct": + return text, srt_text, segments_json + else: + + if include_text is True: + text_filename = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}.txt") + with open(text_filename, 'w') as f: + f.write(text) + else: + text_file = None + + if include_srt is True: + srt_filename = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}.srt") + with open(srt_filename, 'w') as f: + f.write(srt_text) + else: + srt_filename = None + + if include_segments is True: + segments_filename = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}.json") + with open(segments_filename, 'w') as f: + f.write(str(segments_json)) + else: + segments_filename = None + + return text_filename, srt_filename, segments_filename + + except Exception as e: + logger.error(f"{task.capitalize()} failed: {str(e)}") + raise \ No newline at end of file diff --git a/services/v1/media/metadata.py b/services/v1/media/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..e633f21185003184966a27ba1a53099fd324fdaf --- /dev/null +++ b/services/v1/media/metadata.py @@ -0,0 +1,173 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import subprocess +import json +import logging +from services.file_management import download_file +from config import LOCAL_STORAGE_PATH + +# Set up logging +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +def get_media_metadata(media_url, job_id=None): + """ + Extract metadata from a media file including video/audio properties. + + Args: + media_url (str): URL of the media file to analyze + job_id (str, optional): Unique job identifier + + Returns: + dict: Dictionary containing all available metadata for the media file + """ + logger.info(f"Starting metadata extraction for {media_url}") + + # Download the file + input_filename = download_file(media_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_metadata_input")) + logger.info(f"Downloaded media to local file: {input_filename}") + + try: + # Initialize metadata dictionary + metadata = {} + + # Get file size + metadata['filesize'] = os.path.getsize(input_filename) + metadata['filesize_mb'] = round(metadata['filesize'] / (1024 * 1024), 2) # Convert to MB + + # Run ffprobe to get detailed metadata + ffprobe_command = [ + 'ffprobe', + '-v', 'quiet', + '-print_format', 'json', + '-show_format', + '-show_streams', + input_filename + ] + + logger.info(f"Running ffprobe command: {' '.join(ffprobe_command)}") + result = subprocess.run(ffprobe_command, capture_output=True, text=True) + + if result.returncode != 0: + logger.error(f"Error during ffprobe: {result.stderr}") + raise Exception(f"ffprobe error: {result.stderr}") + + probe_data = json.loads(result.stdout) + + # Get format information + if 'format' in probe_data: + format_data = probe_data['format'] + + # Get duration if available + if 'duration' in format_data: + metadata['duration'] = float(format_data['duration']) + # Format duration as HH:MM:SS.mm + mins, secs = divmod(metadata['duration'], 60) + hours, mins = divmod(mins, 60) + metadata['duration_formatted'] = f"{int(hours):02d}:{int(mins):02d}:{secs:.2f}" + + # Get format/container type + if 'format_name' in format_data: + metadata['format'] = format_data['format_name'] + + # Get overall bitrate if available + if 'bit_rate' in format_data: + metadata['overall_bitrate'] = int(format_data['bit_rate']) + metadata['overall_bitrate_mbps'] = round(metadata['overall_bitrate'] / 1000000, 2) # Convert to Mbps + + # Process streams information + if 'streams' in probe_data: + has_video = False + has_audio = False + + for stream in probe_data['streams']: + stream_type = stream.get('codec_type') + + if stream_type == 'video' and not has_video: + has_video = True + + # Basic video properties + metadata['video_codec'] = stream.get('codec_name', 'unknown') + metadata['video_codec_long'] = stream.get('codec_long_name', 'unknown') + + # Resolution + if 'width' in stream and 'height' in stream: + metadata['width'] = stream['width'] + metadata['height'] = stream['height'] + metadata['resolution'] = f"{stream['width']}x{stream['height']}" + + # Frame rate + if 'r_frame_rate' in stream: + try: + num, den = map(int, stream['r_frame_rate'].split('/')) + if den != 0: # Avoid division by zero + metadata['fps'] = round(num / den, 2) + except (ValueError, ZeroDivisionError): + logger.warning("Unable to parse frame rate") + + # Bitrate + if 'bit_rate' in stream: + metadata['video_bitrate'] = int(stream['bit_rate']) + metadata['video_bitrate_mbps'] = round(metadata['video_bitrate'] / 1000000, 2) # Convert to Mbps + + # Pixel format + if 'pix_fmt' in stream: + metadata['pixel_format'] = stream['pix_fmt'] + + elif stream_type == 'audio' and not has_audio: + has_audio = True + + # Basic audio properties + metadata['audio_codec'] = stream.get('codec_name', 'unknown') + metadata['audio_codec_long'] = stream.get('codec_long_name', 'unknown') + + # Audio channels + if 'channels' in stream: + metadata['audio_channels'] = stream['channels'] + + # Sample rate + if 'sample_rate' in stream: + metadata['audio_sample_rate'] = int(stream['sample_rate']) + metadata['audio_sample_rate_khz'] = round(metadata['audio_sample_rate'] / 1000, 1) # Convert to kHz + + # Bitrate + if 'bit_rate' in stream: + metadata['audio_bitrate'] = int(stream['bit_rate']) + metadata['audio_bitrate_kbps'] = round(metadata['audio_bitrate'] / 1000, 0) # Convert to kbps + + # Add flags indicating presence of streams + metadata['has_video'] = has_video + metadata['has_audio'] = has_audio + + # Clean up the downloaded file + if os.path.exists(input_filename): + os.remove(input_filename) + logger.info(f"Removed temporary file: {input_filename}") + + return metadata + + except Exception as e: + logger.error(f"Metadata extraction failed: {str(e)}") + + # Clean up temporary file if it exists + if 'input_filename' in locals() and os.path.exists(input_filename): + os.remove(input_filename) + + raise \ No newline at end of file diff --git a/services/v1/media/silence.py b/services/v1/media/silence.py new file mode 100644 index 0000000000000000000000000000000000000000..5a34ef04a7f951b9ef37adb73150754717cf6aed --- /dev/null +++ b/services/v1/media/silence.py @@ -0,0 +1,181 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import json +import subprocess +import logging +import re +from services.file_management import download_file +from config import LOCAL_STORAGE_PATH + +# Set up logging +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +def detect_silence(media_url, start_time=None, end_time=None, noise_threshold="-30dB", min_duration=0.5, mono=False, job_id=None): + """ + Detect silence in media files using FFmpeg's silencedetect filter. + + Args: + media_url (str): URL of the media file to analyze + start_time (str, optional): Start time in format HH:MM:SS.mmm + end_time (str, optional): End time in format HH:MM:SS.mmm + noise_threshold (str, optional): Noise tolerance threshold, default "-30dB" + min_duration (float, optional): Minimum silence duration to detect in seconds + mono (bool, optional): Whether to convert stereo to mono before analysis + job_id (str, optional): Unique job identifier + + Returns: + list: List of dictionaries containing silence intervals with start, end, and duration + """ + logger.info(f"Starting silence detection for media URL: {media_url}") + input_filename = download_file(media_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input")) + logger.info(f"Downloaded media to local file: {input_filename}") + + try: + # For reliable silence detection with time constraints, we need a different approach + # We'll use FFmpeg without any time constraints and process the results later + cmd = ['ffmpeg', '-i', input_filename] + + # We won't use audio trim filters as they're causing issues with silence detection + # Instead, we'll filter the results after the analysis is complete + segment_filter = "" + + # Save the start and end times for post-processing + start_seconds = 0 + end_seconds = float('inf') + + if start_time: + try: + # Parse the start time to seconds + h, m, s = start_time.split(':') + start_seconds = int(h) * 3600 + int(m) * 60 + float(s) + logger.info(f"Will filter results starting from {start_seconds} seconds") + except ValueError: + logger.warning(f"Could not parse start time '{start_time}', using 0") + + if end_time: + try: + # Parse the end time to seconds + h, m, s = end_time.split(':') + end_seconds = int(h) * 3600 + int(m) * 60 + float(s) + logger.info(f"Will filter results ending at {end_seconds} seconds") + except ValueError: + logger.warning(f"Could not parse end time '{end_time}', using infinity") + + # Add audio processing options + cmd.extend(['-af']) + + # Build the filter string + filter_string = "" + + # First add the segment filter if needed + filter_string += segment_filter + + # Then add mono conversion if needed + if mono: + filter_string += "pan=mono|c0=0.5*c0+0.5*c1," + + # Add the silencedetect filter + filter_string += f"silencedetect=noise={noise_threshold}:d={min_duration}" + cmd.append(filter_string) + + # Output to null, we only want the filter output + cmd.extend(['-f', 'null', '-']) + + logger.info(f"Running FFmpeg command: {' '.join(cmd)}") + + # Run the FFmpeg command and capture stderr for silence detection output + result = subprocess.run(cmd, stderr=subprocess.PIPE, text=True) + + # Parse the silence detection output + silence_intervals = [] + + # Regular expressions to match the silence detection output + silence_start_pattern = r'silence_start: (\d+\.?\d*)' + silence_end_pattern = r'silence_end: (\d+\.?\d*) \| silence_duration: (\d+\.?\d*)' + + # Find all silence start times + silence_starts = re.findall(silence_start_pattern, result.stderr) + + # Find all silence end times and durations + silence_ends_durations = re.findall(silence_end_pattern, result.stderr) + + # Combine the results into a list of silence intervals + for i, (end, duration) in enumerate(silence_ends_durations): + # For the first silence period, the start time might not be detected correctly + # if the media starts with silence + start = silence_starts[i] if i < len(silence_starts) else "0.0" + + # Convert to float + start_time_float = float(start) + end_time_float = float(end) + duration_float = float(duration) + + # Filter the results based on the specified time range + # Only include silence periods that overlap with our requested range + + # Skip if silence ends before our start time + if end_time_float < start_seconds: + logger.info(f"Skipping silence at {start_time_float}-{end_time_float} as it ends before requested start time {start_seconds}") + continue + + # Skip if silence starts after our end time + if start_time_float > end_seconds: + logger.info(f"Skipping silence at {start_time_float}-{end_time_float} as it starts after requested end time {end_seconds}") + continue + + # Format time as HH:MM:SS.mmm + start_formatted = format_time(start_time_float) + end_formatted = format_time(end_time_float) + + silence_intervals.append({ + "start": start_formatted, + "end": end_formatted, + "duration": round(duration_float, 2) + }) + + # Clean up the downloaded file + os.remove(input_filename) + logger.info(f"Removed local file: {input_filename}") + + return silence_intervals + + except Exception as e: + logger.error(f"Silence detection failed: {str(e)}") + # Make sure to clean up even on error + if os.path.exists(input_filename): + os.remove(input_filename) + raise + +def format_time(seconds): + """ + Format time in seconds to HH:MM:SS.mmm format + + Args: + seconds (float): Time in seconds + + Returns: + str: Formatted time string + """ + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + seconds = seconds % 60 + + return f"{hours:02d}:{minutes:02d}:{seconds:06.3f}" \ No newline at end of file diff --git a/services/v1/s3/upload.py b/services/v1/s3/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..49fc3898d8504a56e7faaf31e3910d9fc11871ca --- /dev/null +++ b/services/v1/s3/upload.py @@ -0,0 +1,174 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import boto3 +import logging +import requests +from urllib.parse import urlparse, unquote, quote +import uuid +import re + +logger = logging.getLogger(__name__) + +def get_s3_client(): + """Create and return an S3 client using environment variables.""" + endpoint_url = os.getenv('S3_ENDPOINT_URL') + access_key = os.getenv('S3_ACCESS_KEY') + secret_key = os.getenv('S3_SECRET_KEY') + region = os.environ.get('S3_REGION', '') + + session = boto3.Session( + aws_access_key_id=access_key, + aws_secret_access_key=secret_key, + region_name=region + ) + + return session.client('s3', endpoint_url=endpoint_url) + +def get_filename_from_url(url): + """Extract filename from URL.""" + path = urlparse(url).path + filename = os.path.basename(unquote(path)) + + # If filename cannot be determined, generate a UUID + if not filename or filename == '': + filename = f"{uuid.uuid4()}" + + return filename + +def stream_upload_to_s3(file_url, custom_filename=None, make_public=False, download_headers=None): + """ + Stream a file from a URL directly to S3 without saving to disk. + + Args: + file_url (str): URL of the file to download + custom_filename (str, optional): Custom filename for the uploaded file + make_public (bool, optional): Whether to make the file publicly accessible + download_headers (dict, optional): Headers to include in the download request for authentication + + Returns: + dict: Information about the uploaded file + """ + try: + # Get S3 configuration + bucket_name = os.environ.get('S3_BUCKET_NAME', '') + endpoint_url = os.getenv('S3_ENDPOINT_URL') + + # Get S3 client + s3_client = get_s3_client() + + # Determine filename (use custom if provided, otherwise extract from URL) + if custom_filename: + filename = custom_filename + else: + filename = get_filename_from_url(file_url) + + # Start a multipart upload + logger.info(f"Starting multipart upload for {filename} to bucket {bucket_name}") + acl = 'public-read' if make_public else 'private' + + multipart_upload = s3_client.create_multipart_upload( + Bucket=bucket_name, + Key=filename, + ACL=acl + ) + + upload_id = multipart_upload['UploadId'] + + # Stream the file from URL + response = requests.get(file_url, stream=True, headers=download_headers) + response.raise_for_status() + + # Process in chunks using multipart upload + chunk_size = 5 * 1024 * 1024 # 5MB chunks (AWS minimum) + parts = [] + part_number = 1 + + buffer = bytearray() + + for chunk in response.iter_content(chunk_size=1024 * 1024): # 1MB read chunks + buffer.extend(chunk) + + # When we have enough data for a part, upload it + if len(buffer) >= chunk_size: + logger.info(f"Uploading part {part_number}") + part = s3_client.upload_part( + Bucket=bucket_name, + Key=filename, + PartNumber=part_number, + UploadId=upload_id, + Body=buffer + ) + + parts.append({ + 'PartNumber': part_number, + 'ETag': part['ETag'] + }) + + part_number += 1 + buffer = bytearray() + + # Upload any remaining data as the final part + if buffer: + logger.info(f"Uploading final part {part_number}") + part = s3_client.upload_part( + Bucket=bucket_name, + Key=filename, + PartNumber=part_number, + UploadId=upload_id, + Body=buffer + ) + + parts.append({ + 'PartNumber': part_number, + 'ETag': part['ETag'] + }) + + # Complete the multipart upload + logger.info("Completing multipart upload") + s3_client.complete_multipart_upload( + Bucket=bucket_name, + Key=filename, + UploadId=upload_id, + MultipartUpload={'Parts': parts} + ) + + # Generate the URL to the uploaded file + if make_public: + # URL encode the filename for the URL only + encoded_filename = quote(filename) + file_url = f"{endpoint_url}/{bucket_name}/{encoded_filename}" + else: + # Generate a pre-signed URL for private files + file_url = s3_client.generate_presigned_url( + 'get_object', + Params={'Bucket': bucket_name, 'Key': filename}, + ExpiresIn=3600 # URL expires in 1 hour + ) + + return { + 'file_url': file_url, + 'filename': filename, # Return the original filename + 'bucket': bucket_name, + 'public': make_public + } + + except Exception as e: + logger.error(f"Error streaming file to S3: {e}") + raise \ No newline at end of file diff --git a/services/v1/video/concatenate.py b/services/v1/video/concatenate.py new file mode 100644 index 0000000000000000000000000000000000000000..07c20eacde82977110c675bcbd4f6f85d1eeb44d --- /dev/null +++ b/services/v1/video/concatenate.py @@ -0,0 +1,67 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import ffmpeg +import requests +from services.file_management import download_file +from config import LOCAL_STORAGE_PATH + +def process_video_concatenate(media_urls, job_id, webhook_url=None): + """Combine multiple videos into one.""" + input_files = [] + output_filename = f"{job_id}.mp4" + output_path = os.path.join(LOCAL_STORAGE_PATH, output_filename) + + try: + # Download all media files + for i, media_item in enumerate(media_urls): + url = media_item['video_url'] + input_filename = download_file(url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input_{i}")) + input_files.append(input_filename) + + # Generate an absolute path concat list file for FFmpeg + concat_file_path = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_concat_list.txt") + with open(concat_file_path, 'w') as concat_file: + for input_file in input_files: + # Write absolute paths to the concat list + concat_file.write(f"file '{os.path.abspath(input_file)}'\n") + + # Use the concat demuxer to concatenate the videos + ( + ffmpeg.input(concat_file_path, format='concat', safe=0). + output(output_path, c='copy'). + run(overwrite_output=True) + ) + + # Clean up input files + for f in input_files: + os.remove(f) + + os.remove(concat_file_path) # Remove the concat list file after the operation + + print(f"Video combination successful: {output_path}") + + # Check if the output file exists locally before upload + if not os.path.exists(output_path): + raise FileNotFoundError(f"Output file {output_path} does not exist after combination.") + + return output_path + except Exception as e: + print(f"Video combination failed: {str(e)}") + raise diff --git a/services/v1/video/cut.py b/services/v1/video/cut.py new file mode 100644 index 0000000000000000000000000000000000000000..4215a277a8f000eebc8275610cf90f9d326fd11f --- /dev/null +++ b/services/v1/video/cut.py @@ -0,0 +1,279 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import json +import subprocess +import logging +import uuid +import tempfile +from services.file_management import download_file +from services.cloud_storage import upload_file +from config import LOCAL_STORAGE_PATH + +# Set up logging +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +def time_to_seconds(time_str): + """ + Convert a time string in format HH:MM:SS[.mmm] to seconds. + + Args: + time_str (str): Time string + + Returns: + float: Time in seconds + """ + try: + parts = time_str.split(':') + if len(parts) == 3: + hours, minutes, seconds = parts + return int(hours) * 3600 + int(minutes) * 60 + float(seconds) + elif len(parts) == 2: + minutes, seconds = parts + return int(minutes) * 60 + float(seconds) + else: + return float(time_str) + except ValueError: + raise ValueError(f"Invalid time format: {time_str}. Expected HH:MM:SS[.mmm]") + +def cut_media(video_url, cuts, job_id=None, video_codec='libx264', video_preset='medium', + video_crf=23, audio_codec='aac', audio_bitrate='128k'): + """ + Cuts specified segments from a video file with customizable encoding settings. + + Args: + video_url (str): URL of the video file to cut + cuts (list): List of dictionaries with 'start' and 'end' timestamps + job_id (str, optional): Unique job identifier + video_codec (str, optional): Video codec to use for encoding (default: 'libx264') + video_preset (str, optional): Encoding preset for speed/quality tradeoff (default: 'medium') + video_crf (int, optional): Constant Rate Factor for quality (0-51, default: 23) + audio_codec (str, optional): Audio codec to use for encoding (default: 'aac') + audio_bitrate (str, optional): Audio bitrate (default: '128k') + + Returns: + str: Path to the processed local file + """ + logger.info(f"Starting video cut operation for {video_url}") + input_filename = download_file(video_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input")) + logger.info(f"Downloaded video to local file: {input_filename}") + + temp_files = [] + + try: + # Get the file extension + _, ext = os.path.splitext(input_filename) + + # Create output filename + output_filename = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_output{ext}") + + # Get the duration of the input file + probe_cmd = [ + 'ffprobe', + '-v', 'error', + '-show_entries', 'format=duration', + '-of', 'default=noprint_wrappers=1:nokey=1', + input_filename + ] + duration_result = subprocess.run(probe_cmd, capture_output=True, text=True) + try: + file_duration = float(duration_result.stdout.strip()) + logger.info(f"File duration: {file_duration} seconds") + except (ValueError, IndexError): + logger.warning("Could not determine file duration, using a large value") + file_duration = 86400 # 24 hours as a fallback + + # Validate and process cuts + cuts_in_seconds = [] + for cut in cuts: + start_seconds = time_to_seconds(cut['start']) + end_seconds = time_to_seconds(cut['end']) + + # Validate cut times + if start_seconds >= end_seconds: + raise ValueError(f"Invalid cut: start time ({cut['start']}) must be before end time ({cut['end']})") + + if start_seconds < 0: + logger.warning(f"Cut start time {cut['start']} is negative, using 0 instead") + start_seconds = 0 + + if end_seconds > file_duration: + logger.warning(f"Cut end time {cut['end']} exceeds file duration, using file duration instead") + end_seconds = file_duration + + # Only add valid cuts + if start_seconds < end_seconds: + cuts_in_seconds.append((start_seconds, end_seconds)) + + # Sort cuts by start time and merge overlapping segments + cuts_in_seconds.sort() + merged_cuts = [] + + if cuts_in_seconds: + current_start, current_end = cuts_in_seconds[0] + for start, end in cuts_in_seconds[1:]: + if start <= current_end: # Overlapping segments + current_end = max(current_end, end) + else: # Non-overlapping, add the previous merged segment + merged_cuts.append((current_start, current_end)) + current_start, current_end = start, end + # Add the last segment + merged_cuts.append((current_start, current_end)) + + logger.info(f"Processing cuts: {merged_cuts}") + + if not merged_cuts: + logger.info("No valid cuts to apply, copying the original file") + cmd = [ + 'ffmpeg', + '-i', input_filename, + '-c', 'copy', + output_filename + ] + subprocess.run(cmd, check=True, capture_output=True, text=True) + else: + # Switch to a different approach: extract segments and concatenate + segment_files = [] + + # Create segments to keep + last_end = 0 + for i, (start, end) in enumerate(merged_cuts): + # If there's a gap between last segment end and current segment start, extract it + if start > last_end: + segment_file = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_segment_{i}{ext}") + segment_files.append(segment_file) + temp_files.append(segment_file) + + # Extract segment from last_end to start + duration = start - last_end + cmd = [ + 'ffmpeg', + '-i', input_filename, + '-ss', str(last_end), + '-t', str(duration), + '-c:v', video_codec, + '-preset', video_preset, + '-crf', str(video_crf), + '-c:a', audio_codec, + '-b:a', audio_bitrate, + '-pix_fmt', 'yuv420p', + '-vsync', 'cfr', + '-r', '30', + '-avoid_negative_ts', 'make_zero', + segment_file + ] + logger.info(f"Extracting segment {i}: {' '.join(cmd)}") + process = subprocess.run(cmd, capture_output=True, text=True) + + if process.returncode != 0: + logger.error(f"Error during segment {i} extraction: {process.stderr}") + raise Exception(f"FFmpeg error: {process.stderr}") + + last_end = end + + # Add final segment if needed + if last_end < file_duration: + segment_file = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_segment_final{ext}") + segment_files.append(segment_file) + temp_files.append(segment_file) + + cmd = [ + 'ffmpeg', + '-i', input_filename, + '-ss', str(last_end), + '-c:v', video_codec, + '-preset', video_preset, + '-crf', str(video_crf), + '-c:a', audio_codec, + '-b:a', audio_bitrate, + '-pix_fmt', 'yuv420p', + '-vsync', 'cfr', + '-r', '30', + '-avoid_negative_ts', 'make_zero', + segment_file + ] + logger.info(f"Extracting final segment: {' '.join(cmd)}") + process = subprocess.run(cmd, capture_output=True, text=True) + + if process.returncode != 0: + logger.error(f"Error during final segment extraction: {process.stderr}") + raise Exception(f"FFmpeg error: {process.stderr}") + + # If we have segments to concatenate + if segment_files: + # Create a concat file + concat_file = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_concat.txt") + temp_files.append(concat_file) + + with open(concat_file, 'w') as f: + for segment in segment_files: + f.write(f"file '{segment}'\n") + + # Concatenate the segments + cmd = [ + 'ffmpeg', + '-f', 'concat', + '-safe', '0', + '-i', concat_file, + '-c:v', video_codec, + '-preset', video_preset, + '-crf', str(video_crf), + '-c:a', audio_codec, + '-b:a', audio_bitrate, + '-vsync', 'cfr', + '-r', '30', + '-pix_fmt', 'yuv420p', + '-movflags', '+faststart', + output_filename + ] + logger.info(f"Concatenating segments: {' '.join(cmd)}") + process = subprocess.run(cmd, capture_output=True, text=True) + + if process.returncode != 0: + logger.error(f"Error during concatenation: {process.stderr}") + raise Exception(f"FFmpeg error: {process.stderr}") + else: + # No segments to keep + with open(output_filename, 'wb') as f: + # Create an empty file + pass + + # Clean up temporary files + for temp_file in temp_files: + if os.path.exists(temp_file): + os.remove(temp_file) + logger.info(f"Removed temporary file: {temp_file}") + + return output_filename, input_filename + + except Exception as e: + logger.error(f"Video cut operation failed: {str(e)}") + # Clean up all temporary files if they exist + for temp_file in temp_files: + if os.path.exists(temp_file): + os.remove(temp_file) + + if 'input_filename' in locals() and os.path.exists(input_filename): + os.remove(input_filename) + + if 'output_filename' in locals() and os.path.exists(output_filename): + os.remove(output_filename) + + raise \ No newline at end of file diff --git a/services/v1/video/split.py b/services/v1/video/split.py new file mode 100644 index 0000000000000000000000000000000000000000..12943100adafe8f90c49d8c59c9b39fc36f115fe --- /dev/null +++ b/services/v1/video/split.py @@ -0,0 +1,181 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import json +import subprocess +import logging +import uuid +from services.file_management import download_file +from services.cloud_storage import upload_file +from config import LOCAL_STORAGE_PATH + +# Set up logging +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +def time_to_seconds(time_str): + """ + Convert a time string in format HH:MM:SS[.mmm] to seconds. + + Args: + time_str (str): Time string + + Returns: + float: Time in seconds + """ + try: + parts = time_str.split(':') + if len(parts) == 3: + hours, minutes, seconds = parts + return int(hours) * 3600 + int(minutes) * 60 + float(seconds) + elif len(parts) == 2: + minutes, seconds = parts + return int(minutes) * 60 + float(seconds) + else: + return float(time_str) + except ValueError: + raise ValueError(f"Invalid time format: {time_str}. Expected HH:MM:SS[.mmm]") + +def split_video(video_url, splits, job_id=None, video_codec='libx264', video_preset='medium', + video_crf=23, audio_codec='aac', audio_bitrate='128k'): + """ + Splits a video file into multiple segments with customizable encoding settings. + + Args: + video_url (str): URL of the video file to split + splits (list): List of dictionaries with 'start' and 'end' timestamps + job_id (str, optional): Unique job identifier + video_codec (str, optional): Video codec to use for encoding (default: 'libx264') + video_preset (str, optional): Encoding preset for speed/quality tradeoff (default: 'medium') + video_crf (int, optional): Constant Rate Factor for quality (0-51, default: 23) + audio_codec (str, optional): Audio codec to use for encoding (default: 'aac') + audio_bitrate (str, optional): Audio bitrate (default: '128k') + + Returns: + tuple: (list of output file paths, input file path) + """ + logger.info(f"Starting video split operation for {video_url}") + if not job_id: + job_id = str(uuid.uuid4()) + + input_filename = download_file(video_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input")) + logger.info(f"Downloaded video to local file: {input_filename}") + + output_files = [] + + try: + # Get the file extension + _, ext = os.path.splitext(input_filename) + + # Get the duration of the input file + probe_cmd = [ + 'ffprobe', + '-v', 'error', + '-show_entries', 'format=duration', + '-of', 'default=noprint_wrappers=1:nokey=1', + input_filename + ] + duration_result = subprocess.run(probe_cmd, capture_output=True, text=True) + + try: + file_duration = float(duration_result.stdout.strip()) + logger.info(f"File duration: {file_duration} seconds") + except (ValueError, IndexError): + logger.warning("Could not determine file duration, using a large value") + file_duration = 86400 # 24 hours as a fallback + + # Validate and process splits + valid_splits = [] + for i, split in enumerate(splits): + try: + start_seconds = time_to_seconds(split['start']) + end_seconds = time_to_seconds(split['end']) + + # Validate split times + if start_seconds >= end_seconds: + logger.warning(f"Invalid split {i+1}: start time ({split['start']}) must be before end time ({split['end']}). Skipping.") + continue + + if start_seconds < 0: + logger.warning(f"Split {i+1} start time {split['start']} is negative, using 0 instead") + start_seconds = 0 + + if end_seconds > file_duration: + logger.warning(f"Split {i+1} end time {split['end']} exceeds file duration, using file duration instead") + end_seconds = file_duration + + # Only add valid splits + if start_seconds < end_seconds: + valid_splits.append((i, start_seconds, end_seconds, split)) + except ValueError as e: + logger.warning(f"Error processing split {i+1}: {str(e)}. Skipping.") + + if not valid_splits: + raise ValueError("No valid split segments specified") + + logger.info(f"Processing {len(valid_splits)} valid splits") + + # Process each split + for index, (split_index, start_seconds, end_seconds, split_data) in enumerate(valid_splits): + # Create output filename for this split + output_filename = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_split_{index+1}{ext}") + + # Create FFmpeg command to extract the segment + cmd = [ + 'ffmpeg', + '-i', input_filename, + '-ss', str(start_seconds), + '-to', str(end_seconds), + '-c:v', video_codec, + '-preset', video_preset, + '-crf', str(video_crf), + '-c:a', audio_codec, + '-b:a', audio_bitrate, + '-avoid_negative_ts', 'make_zero', + output_filename + ] + + logger.info(f"Running FFmpeg command for split {index+1}: {' '.join(cmd)}") + + # Run the FFmpeg command + process = subprocess.run(cmd, capture_output=True, text=True) + + if process.returncode != 0: + logger.error(f"Error processing split {index+1}: {process.stderr}") + raise Exception(f"FFmpeg error for split {index+1}: {process.stderr}") + + # Add the output file to the list + output_files.append(output_filename) + logger.info(f"Successfully created split {index+1}: {output_filename}") + + # Return the list of output files and the input filename + return output_files, input_filename + + except Exception as e: + logger.error(f"Video split operation failed: {str(e)}") + + # Clean up all temporary files if they exist + if 'input_filename' in locals() and os.path.exists(input_filename): + os.remove(input_filename) + + for output_file in output_files: + if os.path.exists(output_file): + os.remove(output_file) + + raise \ No newline at end of file diff --git a/services/v1/video/thumbnail.py b/services/v1/video/thumbnail.py new file mode 100644 index 0000000000000000000000000000000000000000..54d2be1cb79fe7f14cb1e7fc0abead7b16b924bc --- /dev/null +++ b/services/v1/video/thumbnail.py @@ -0,0 +1,66 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import ffmpeg +from services.file_management import download_file +from config import LOCAL_STORAGE_PATH + +def extract_thumbnail(video_url, job_id, second=0): + """ + Extract a thumbnail from a video at the specified timestamp. + + Args: + video_url (str): URL of the video to extract thumbnail from + job_id (str): Unique identifier for the job + second (float): Timestamp in seconds to extract the thumbnail from (default: 0) + + Returns: + str: Path to the extracted thumbnail image + """ + # Download the video from the provided URL + video_path = download_file(video_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input")) + + # Set output path for the thumbnail + thumbnail_path = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_thumbnail.jpg") + + try: + # Extract thumbnail using ffmpeg at the specified timestamp + ( + ffmpeg + .input(video_path, ss=second) # 'ss' is the seek parameter for the timestamp + .output(thumbnail_path, vframes=1) # vframes=1 extracts a single frame + .overwrite_output() + .run(capture_stdout=True, capture_stderr=True) + ) + + # Clean up the downloaded video file + os.remove(video_path) + + # Ensure the thumbnail file exists + if not os.path.exists(thumbnail_path): + raise FileNotFoundError(f"Thumbnail file {thumbnail_path} was not created") + + return thumbnail_path + + except Exception as e: + print(f"Thumbnail extraction failed: {str(e)}") + # Clean up any downloaded files on error + if os.path.exists(video_path): + os.remove(video_path) + raise diff --git a/services/v1/video/trim.py b/services/v1/video/trim.py new file mode 100644 index 0000000000000000000000000000000000000000..4539651cf5c4d003a6956f976d6e4e8e4b03bd09 --- /dev/null +++ b/services/v1/video/trim.py @@ -0,0 +1,178 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import os +import json +import subprocess +import logging +import uuid +from services.file_management import download_file +from services.cloud_storage import upload_file +from config import LOCAL_STORAGE_PATH + +# Set up logging +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +def time_to_seconds(time_str): + """ + Convert a time string in format HH:MM:SS[.mmm] to seconds. + + Args: + time_str (str): Time string + + Returns: + float: Time in seconds + """ + if not time_str: + return None + + try: + parts = time_str.split(':') + if len(parts) == 3: + hours, minutes, seconds = parts + return int(hours) * 3600 + int(minutes) * 60 + float(seconds) + elif len(parts) == 2: + minutes, seconds = parts + return int(minutes) * 60 + float(seconds) + else: + return float(time_str) + except ValueError: + raise ValueError(f"Invalid time format: {time_str}. Expected HH:MM:SS[.mmm]") + +def trim_video(video_url, start=None, end=None, job_id=None, video_codec='libx264', video_preset='medium', + video_crf=23, audio_codec='aac', audio_bitrate='128k'): + """ + Trims a video by removing specified portions from the beginning and/or end with customizable encoding settings. + + Args: + video_url (str): URL of the video file to trim + start (str, optional): Timestamp to start the trimmed video (keep everything after this point) + end (str, optional): Timestamp to end the trimmed video (keep everything before this point) + job_id (str, optional): Unique job identifier + video_codec (str, optional): Video codec to use for encoding (default: 'libx264') + video_preset (str, optional): Encoding preset for speed/quality tradeoff (default: 'medium') + video_crf (int, optional): Constant Rate Factor for quality (0-51, default: 23) + audio_codec (str, optional): Audio codec to use for encoding (default: 'aac') + audio_bitrate (str, optional): Audio bitrate (default: '128k') + + Returns: + tuple: (output_filename, input_filename) + """ + logger.info(f"Starting video trim operation for {video_url}") + if not job_id: + job_id = str(uuid.uuid4()) + + input_filename = download_file(video_url, os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_input")) + logger.info(f"Downloaded video to local file: {input_filename}") + + try: + # Get the file extension + _, ext = os.path.splitext(input_filename) + + # Create output filename + output_filename = os.path.join(LOCAL_STORAGE_PATH, f"{job_id}_output{ext}") + + # Get the duration of the input file + probe_cmd = [ + 'ffprobe', + '-v', 'error', + '-show_entries', 'format=duration', + '-of', 'default=noprint_wrappers=1:nokey=1', + input_filename + ] + duration_result = subprocess.run(probe_cmd, capture_output=True, text=True) + + try: + file_duration = float(duration_result.stdout.strip()) + logger.info(f"File duration: {file_duration} seconds") + except (ValueError, IndexError): + logger.warning("Could not determine file duration, using a large value") + file_duration = 86400 # 24 hours as a fallback + + # Convert start and end times to seconds + start_seconds = time_to_seconds(start) if start else 0 + end_seconds = time_to_seconds(end) if end else file_duration + + # Validate times + if start_seconds is not None and start_seconds < 0: + logger.warning(f"Start time {start} is negative, using 0 instead") + start_seconds = 0 + + if end_seconds is not None and end_seconds > file_duration: + logger.warning(f"End time {end} exceeds file duration, using file duration instead") + end_seconds = file_duration + + if start_seconds is not None and end_seconds is not None and start_seconds >= end_seconds: + raise ValueError(f"Invalid trim: start time ({start}) must be before end time ({end})") + + # Prepare FFmpeg command based on trim parameters + cmd = ['ffmpeg', '-i', input_filename] + + filter_applied = False + + if start_seconds > 0 or end_seconds < file_duration: + # We need to trim the video + logger.info(f"Trimming video from {start_seconds}s to {end_seconds}s") + + if start_seconds > 0: + cmd.extend(['-ss', str(start_seconds)]) + + if end_seconds < file_duration: + duration = end_seconds - (start_seconds or 0) + cmd.extend(['-t', str(duration)]) + + filter_applied = True + + # Add encoding parameters + cmd.extend([ + '-c:v', video_codec, + '-preset', video_preset, + '-crf', str(video_crf), + '-c:a', audio_codec, + '-b:a', audio_bitrate, + '-avoid_negative_ts', 'make_zero', + output_filename + ]) + + if not filter_applied: + logger.info("No trimming needed, copying with encoder settings") + + logger.info(f"Running FFmpeg command: {' '.join(cmd)}") + + # Run the FFmpeg command + process = subprocess.run(cmd, capture_output=True, text=True) + + if process.returncode != 0: + logger.error(f"Error during trim: {process.stderr}") + raise Exception(f"FFmpeg error: {process.stderr}") + + # Return the path to the output file (route will handle upload) + return output_filename, input_filename + + except Exception as e: + logger.error(f"Video trim operation failed: {str(e)}") + + # Clean up all temporary files if they exist + if 'input_filename' in locals() and os.path.exists(input_filename): + os.remove(input_filename) + + if 'output_filename' in locals() and os.path.exists(output_filename): + os.remove(output_filename) + + raise \ No newline at end of file diff --git a/services/webhook.py b/services/webhook.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec852c8c1f75f99d150e1eded88d6f5f6773749 --- /dev/null +++ b/services/webhook.py @@ -0,0 +1,32 @@ +# Copyright (c) 2025 Stephen G. Pope +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +import requests +import logging + +logger = logging.getLogger(__name__) + +def send_webhook(webhook_url, data): + """Send a POST request to a webhook URL with the provided data.""" + try: + logger.info(f"Attempting to send webhook to {webhook_url} with data: {data}") + response = requests.post(webhook_url, json=data) + response.raise_for_status() + logger.info(f"Webhook sent: {data}") + except requests.RequestException as e: + logger.error(f"Webhook failed: {e}") diff --git a/version.py b/version.py new file mode 100644 index 0000000000000000000000000000000000000000..fbd5e059771c8a43a6a0231c8e7e42c4f8524989 --- /dev/null +++ b/version.py @@ -0,0 +1 @@ +BUILD_NUMBER = 200