diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index af4bcd5e2dc..2e178927525 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -2,62 +2,64 @@ name: Bug Report description: Create a report to help us improve labels: ["type: bug", "needs-triage"] body: -- type: markdown + - type: markdown attributes: - value: | - Thanks for helping PyScript! 🐍 + value: | + Thanks for helping PyScript! 🐍 - Going through bugs and issues takes up a lot of time, so please be so kind and take a few minutes to fill out all the areas to the best of your ability. + Going through bugs and issues takes up a lot of time, so please be so kind and take a few minutes to fill out all the areas to the best of your ability. - There will always be more issues than there is time to do them, and so we will need to selectively close issues that don't provide enough information, so we can focus our time on helping people like you who fill out the issue form completely. Thank you for your collaboration! + There will always be more issues than there is time to do them, and so we will need to selectively close issues that don't provide enough information, so we can focus our time on helping people like you who fill out the issue form completely. Thank you for your collaboration! - There are also already a lot of open issues, so please take 2 minutes and search through existing ones to see if what you are experiencing already exists + There are also already a lot of open issues, so please take 2 minutes and search through existing ones to see if what you are experiencing already exists. - Thanks for helping PyScript be amazing. We are nothing without people like you helping build a better community 💐! -- type: checkboxes + Finally, if you are opening **a bug report related to PyScript.com** please [use this repository instead](https://github.com/anaconda/pyscript-dot-com-issues/issues/new/choose). + + Thanks for helping PyScript be amazing. We are nothing without people like you helping build a better community 💐! + - type: checkboxes id: checks attributes: - label: Checklist - description: Please confirm and check all the following options. - options: - - label: I added a descriptive title - required: true - - label: I searched for other issues and couldn't find a solution or duplication - required: true - - label: I already searched in Google and didn't find any good information or help - required: true -- type: textarea + label: Checklist + description: Please confirm and check all the following options. + options: + - label: I added a descriptive title + required: true + - label: I searched for other issues and couldn't find a solution or duplication + required: true + - label: I already searched in Google and didn't find any good information or help + required: true + - type: textarea id: what-happened attributes: - label: What happened? - description: And what should have happened instead? This really helps everyone review quicker and greatly increases the chance that someone can get around to solve your issue - placeholder: Tell us what you see! + label: What happened? + description: And what should have happened instead? This really helps everyone review quicker and greatly increases the chance that someone can get around to solve your issue + placeholder: Tell us what you see! validations: - required: true -- type: dropdown + required: true + - type: dropdown id: browsers attributes: - label: What browsers are you seeing the problem on? (if applicable) - multiple: true - options: - - Firefox - - Chrome - - Safari - - Microsoft Edge - - Other + label: What browsers are you seeing the problem on? (if applicable) + multiple: true + options: + - Firefox + - Chrome + - Safari + - Microsoft Edge + - Other validations: - required: false -- type: textarea + required: false + - type: textarea id: list attributes: - label: Console info - description: | - If there are errors in your browser console then its helpful to be able to troubleshoot. - - Chrome , Firefox, and Edge: Right-click on the page and select *Inspect*. Alternatively you can press F12 on your keyboard. - - Safari: Find instructions [here](https://support.apple.com/guide/safari/use-the-developer-tools-in-the-develop-menu-sfri20948/mac). - render: shell -- type: textarea + label: Console info + description: | + If there are errors in your browser console then its helpful to be able to troubleshoot. + - Chrome , Firefox, and Edge: Right-click on the page and select *Inspect*. Alternatively you can press F12 on your keyboard. + - Safari: Find instructions [here](https://support.apple.com/guide/safari/use-the-developer-tools-in-the-develop-menu-sfri20948/mac). + render: shell + - type: textarea id: context attributes: - label: Additional Context - description: Add any additional context information or screenshots you think are useful. + label: Additional Context + description: Add any additional context information or screenshots you think are useful. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 451a4c5db6d..cbd90d4bb82 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,8 @@ -blank_issues_enabled: false +blank_issues_enabled: true contact_links: -- name: Question - url: https://community.anaconda.cloud/c/tech-topics/pyscript + - name: Feature Proposals + url: https://github.com/pyscript/pyscript/discussions/new?category=proposals + about: Create a feature request to make PyScript even better + - name: Questions + url: https://github.com/pyscript/pyscript/discussions/new?category=q-a about: For questions or discussions about pyscript diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml deleted file mode 100644 index 5f791094c95..00000000000 --- a/.github/ISSUE_TEMPLATE/feature-request.yml +++ /dev/null @@ -1,67 +0,0 @@ -name: Feature Request -description: Create a feature request to make PyScript even better -labels: ["type: enhancement", "needs-triage"] -body: -- type: markdown - attributes: - value: | - ### Thanks for helping PyScript! 🐍 - - Going through feature requests and issues takes up a lot of time, so please be so kind and take a few minutes to fill out all the areas to the best of your ability. - - There will always be more great ideas than there is time to do them, and so we will need to selectively close issues that don't provide enough information, so everyone can focus our time on helping people like you who fill out the form completely. Thank you for your collaboration! - - There are also already a lot of open requests, so please take 2 minutes and search through existing ones to see if your idea already exists. If you find something close, please upvote that request and comment. - - Thanks for helping PyScript be amazing. We are nothing without people like you helping build a better community 💐! - - ### Lets make sure you are in the right place. If you have an idea/request for: - - - #### A specific package/library (such as pandas or scikit learn): - - Search for that respective library on github repo or website. You will have much more success there. - - - #### A general Python question/feature request: - - Try out a forum post [here](https://discuss.python.org/c/users/7) - -- type: checkboxes - id: checks - attributes: - label: Checklist - description: Please confirm and check all the following options - options: - - label: I added a descriptive title - required: true - - label: I searched for other feature requests and couldn't find a duplicate (including also the ``type-feature`` tag) - required: true - - label: I confirmed that it's not related to another project are area (see the above section) - required: true -- type: textarea - id: request-idea - attributes: - label: What is the idea? - description: Describe what the feature is and the desired state - placeholder: This feature would allow any user of PyScript to type in a simple command in the console and show all variables currently in use - validations: - required: true -- type: textarea - id: why - attributes: - label: Why is this needed - description: | - Who would benefit from this and why would this add value to them? What problem does this solve? - placeholder: This would benefit users who would like to see what is being used so they can learn and debug faster -- type: textarea - id: what - attributes: - label: What should happen? - description: | - What should be the user experience with the feature? Describe from a user perpective what they would do and see - placeholder: A user would type in ``PyScript debug`` in the browser console and see a list of all variables created. -- type: textarea - id: context - attributes: - label: Additional Context - description: | - Is there any other information that you think would be valuable for the team to know? diff --git a/.github/ISSUE_TEMPLATE/misc.yml b/.github/ISSUE_TEMPLATE/misc.yml deleted file mode 100644 index cb327275c88..00000000000 --- a/.github/ISSUE_TEMPLATE/misc.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Miscellaneous -description: For issues that don't belong in other categories -labels: ["type: misc", "needs-triage"] -body: -- type: markdown - attributes: - value: | - Thanks for helping PyScript! 🐍 - - This issue is for things that doesn't make sense to put into the other issue categories and we don't want it to get lost. - - Going through issues takes up a lot of time, so please be so kind and take a few minutes to fill out all the areas to the best of your ability. - - There will always be more issues than there is time to do them, and so we will need to selectively close issues that don't provide enough information, so we can focus our time on helping people like you who fill out the issue form completely. Thank you for your collaboration! - - There are also already a lot of open issues, so please take 2 minutes and search through existing ones to see if what you are experiencing already exists - - Thanks for helping PyScript be amazing. We are nothing without people like you helping build a better community 💐! -- type: checkboxes - id: checks - attributes: - label: Checklist - description: Please confirm and check all the following options. - options: - - label: I added a descriptive title - required: true - - label: I searched for other issues and couldn't find a duplication - required: true - - label: I already searched in Google and didn't find any good information or help - required: true -- type: textarea - id: what - attributes: - label: What is the issue/comment/problem? - description: This is a miscellaneous issue so this could be just about anything. We simply ask that you provide as many details as you can to help spur discussion or the outcome you want. - validations: - required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000000..591e81853a0 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,12 @@ +## Description + + + +## Changes + + + +## Checklist + +- [ ] I have checked `make build` works locally. +- [ ] I have created / updated documentation for this change (if applicable). diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000000..e29bff2bead --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +# Keep GitHub Actions up to date with GitHub's Dependabot... +# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot +# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + groups: + github-actions: + patterns: + - "*" # Group all Actions updates into a single larger pull request + schedule: + interval: weekly diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 00000000000..0bc80808634 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,5 @@ +changelog: + categories: + - title: New Features + - title: Breaking Changes + - title: Known Issues diff --git a/.github/workflows/build-alpha.yml b/.github/workflows/build-alpha.yml deleted file mode 100644 index 30b2501b8a1..00000000000 --- a/.github/workflows/build-alpha.yml +++ /dev/null @@ -1,66 +0,0 @@ -name: '[CI] Build Alpha' - -on: - push: - tags: - - '**' # Currently any tag, need to slim down - paths: - - pyscriptjs/** - -env: - MINICONDA_PYTHON_VERSION: py38 - MINICONDA_VERSION: 4.11.0 - -defaults: - run: - working-directory: pyscriptjs - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - steps: - - - name: Checkout - uses: actions/checkout@v3 - - - name: Install node - uses: actions/setup-node@v3 - with: - node-version: 18.x - - - name: Cache node modules - uses: actions/cache@v3 - env: - cache-name: cache-node-modules - with: - # npm cache files are stored in `~/.npm` on Linux/macOS - path: ~/.npm - key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-build-${{ env.cache-name }}- - ${{ runner.os }}-build- - ${{ runner.os }}- - - - name: setup Miniconda - uses: conda-incubator/setup-miniconda@v2 - - - name: Setup Environment - run: make setup - - - name: Build and Test - run: make test - - # Deploy to S3 - - name: Configure AWS credentials - if: github.ref == 'refs/heads/main' # Only deploy on merge into main - uses: aws-actions/configure-aws-credentials@v1.6.1 - with: - aws-region: ${{secrets.AWS_REGION}} - role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} - - - name: Sync to S3 - if: github.ref == 'refs/heads/main' - run: aws s3 sync --quiet ./examples/build/ s3://pyscript.net/alpha/ diff --git a/.github/workflows/build-latest.yml b/.github/workflows/build-latest.yml deleted file mode 100644 index 8477cf15c0f..00000000000 --- a/.github/workflows/build-latest.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: '[CI] Build Latest' - -on: - push: # Only run on merges into main that modify files under pyscriptjs/ - branches: - - main - paths: - - pyscriptjs/** - - .github/workflows/build-latest.yml # Test that workflow works when changed - - pull_request: # Run on any PR that modifies files in pyscriptjs/ - branches: - - main - paths: - - pyscriptjs/** - - .github/workflows/build-latest.yml # Test that workflow works when changed - -env: - MINICONDA_PYTHON_VERSION: py38 - MINICONDA_VERSION: 4.11.0 - -defaults: - run: - working-directory: pyscriptjs - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - steps: - - - name: Checkout - uses: actions/checkout@v3 - - - name: Install node - uses: actions/setup-node@v3 - with: - node-version: 18.x - - - name: Cache node modules - uses: actions/cache@v3 - env: - cache-name: cache-node-modules - with: - # npm cache files are stored in `~/.npm` on Linux/macOS - path: ~/.npm - key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-build-${{ env.cache-name }}- - ${{ runner.os }}-build- - ${{ runner.os }}- - - - name: setup Miniconda - uses: conda-incubator/setup-miniconda@v2 - - - name: Setup Environment - run: make setup - - - name: Build and Test - run: make test - - # Deploy to S3 - - name: Configure AWS credentials - if: github.ref == 'refs/heads/main' # Only deploy on merge into main - uses: aws-actions/configure-aws-credentials@v1.6.1 - with: - aws-region: ${{secrets.AWS_REGION}} - role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} - - - name: Sync to S3 - if: github.ref == 'refs/heads/main' - run: aws s3 sync --quiet ./examples/build/ s3://pyscript.net/unstable diff --git a/.github/workflows/docs-latest.yml b/.github/workflows/docs-latest.yml deleted file mode 100644 index 1a05385e7ba..00000000000 --- a/.github/workflows/docs-latest.yml +++ /dev/null @@ -1,60 +0,0 @@ -name: '[Docs] Build Latest' - -on: - push: - branches: - - main - paths: - - docs/** - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - env: - SPHINX_HTML_BASE_URL: https://docs.pyscript.net/ - steps: - - - name: Checkout - uses: actions/checkout@v3 - with: - persist-credentials: false # otherwise, the token used is the GITHUB_TOKEN, instead of your personal access token. - fetch-depth: 0 # otherwise, there would be errors pushing refs to the destination repository. - - - name: Setup - uses: conda-incubator/setup-miniconda@v2 - with: - auto-update-conda: true - activate-environment: docs - environment-file: docs/environment.yml - python-version: '3.9' - - - name: Build - shell: bash -l {0} - run: | - cd docs/ - make html - - - name: Upload artifacts - uses: actions/upload-artifact@v3 - with: - name: pyscript-docs-latest - path: docs/_build/html/ - - # Deploy to S3 - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v1.6.1 - with: - aws-region: ${{secrets.AWS_REGION}} - role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} - - - name: Copy redirect file - run: aws s3 cp --quiet ./docs/_build/html/_static/redirect.html s3://docs.pyscript.net/index.html - - # - name: Delete latest directory - # run: aws s3 rm --recursive s3://docs.pyscript.net/latest/ - - - name: Sync to S3 - run: aws s3 sync --quiet ./docs/_build/html/ s3://docs.pyscript.net/latest/ diff --git a/.github/workflows/docs-release.yml b/.github/workflows/docs-release.yml deleted file mode 100644 index a007e9bc8d5..00000000000 --- a/.github/workflows/docs-release.yml +++ /dev/null @@ -1,61 +0,0 @@ -name: '[Docs] Build Release' - -on: - # Any time a tag or branch is created - # https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#create - create: - paths: - - docs/** - -jobs: - build: - if: startsWith(github.ref, 'refs/tags') # Only if tagged - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - env: - SPHINX_HTML_BASE_URL: https://docs.pyscript.net/ - steps: - - - name: Checkout - uses: actions/checkout@v3 - with: - persist-credentials: false # otherwise, the token used is the GITHUB_TOKEN, instead of your personal access token. - fetch-depth: 0 # otherwise, there would be errors pushing refs to the destination repository. - - - name: Setup - uses: conda-incubator/setup-miniconda@v2 - with: - auto-update-conda: true - activate-environment: docs - environment-file: docs/environment.yml - python-version: '3.9' - - - name: Build - shell: bash -l {0} - run: | - cd docs/ - make html - - - name: Upload artifacts - uses: actions/upload-artifact@v3 - with: - name: pyscript-docs-${{ github.ref_name }} - path: docs/_build/html/ - - # Deploy to S3 - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v1.6.1 - with: - aws-region: ${{secrets.AWS_REGION}} - role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} - - - name: Copy redirect file - run: aws s3 cp --quiet ./docs/_build/html/_static/redirect.html s3://docs.pyscript.net/index.html - - # - name: Delete release directory - # run: aws s3 rm --recursive s3://docs.pyscript.net/${{ github.ref_name }}/ - - - name: Sync to S3 - run: aws s3 sync --quiet ./docs/_build/html/ s3://docs.pyscript.net/${{ github.ref_name }}/ diff --git a/.github/workflows/docs-review.yml b/.github/workflows/docs-review.yml deleted file mode 100644 index 358efd24c1e..00000000000 --- a/.github/workflows/docs-review.yml +++ /dev/null @@ -1,76 +0,0 @@ -name: '[Docs] Build Review' - -on: - pull_request: - branches: - - '*' - paths: - - docs/** - -concurrency: - # Concurrency group that uses the workflow name and PR number if available - # or commit SHA as a fallback. If a new build is triggered under that - # concurrency group while a previous build is running it will be canceled. - # Repeated pushes to a PR will cancel all previous builds, while multiple - # merges to main will not cancel. - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} - cancel-in-progress: true - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - env: - SPHINX_HTML_BASE_URL: https://docs.pyscript.net/ - steps: - - - name: Checkout - uses: actions/checkout@v3 - with: - persist-credentials: false # otherwise, the token used is the GITHUB_TOKEN, instead of your personal access token. - fetch-depth: 0 # otherwise, there would be errors pushing refs to the destination repository. - - - name: Setup - uses: conda-incubator/setup-miniconda@v2 - with: - auto-update-conda: true - activate-environment: docs - environment-file: docs/environment.yml - python-version: '3.9' - - - name: Build - shell: bash -l {0} - run: | - cd docs/ - make html - - - name: Upload artifacts - uses: actions/upload-artifact@v3 - with: - name: pyscript-docs-review-${{ github.event.number }} - path: docs/_build/html/ - - # Deploy to S3 - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v1.6.1 - with: - aws-region: ${{secrets.AWS_REGION}} - role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} - - - name: Copy redirect file - run: aws s3 cp --quiet ./docs/_build/html/_static/redirect.html s3://docs.pyscript.net/index.html - - # - name: Delete review directory - # run: aws s3 rm --recursive s3://docs.pyscript.net/review/${{ github.event.number }}/ - - - name: Sync to S3 - run: aws s3 sync --quiet ./docs/_build/html/ s3://docs.pyscript.net/review/${{ github.event.number }}/ - - - name: Adding step summary - run: | - echo "### Review documentation" >> $GITHUB_STEP_SUMMARY - echo "As with any pull request, you can find the rendered documentation version for pull request ${{ github.event.number }} here:" - echo "" >> $GITHUB_STEP_SUMMARY # this is a blank line - echo "https://docs.pyscript.net/review/${{ github.event.number }}/" >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 00000000000..43fe719dbf1 --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,71 @@ +name: "Prepare Release" + +on: + push: + tags: + - "[0-9][0-9][0-9][0-9].[0-9][0-9].[0-9]+" # YYYY.MM.MICRO + +defaults: + run: + working-directory: ./core + +jobs: + prepare-release: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install node + uses: actions/setup-node@v4 + with: + node-version: 20.x + + - name: Python venv + run: python -m venv env + + - name: Activate Python + run: source env/bin/activate + + - name: Update pip + run: pip install --upgrade pip + + - name: Install PyMinifier + run: pip install --ignore-requires-python python-minifier + + - name: Install Setuptools + run: pip install setuptools + + - name: Cache node modules + uses: actions/cache@v4 + env: + cache-name: cache-node-modules + with: + # npm cache files are stored in `~/.npm` on Linux/macOS + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: NPM Install + run: npm install && npx playwright install chromium + + - name: Build + run: npm run build + + - name: Generate index.html + working-directory: . + run: sed -e 's#_PATH_#./#' -e 's#_DOC_VERSION_#latest#' -e 's#_TAG_VERSION_##' -e 's#_VERSION_#latest#' ./public/index.html > ./core/dist/index.html + + - name: Zip dist folder + run: zip -r -q ./build.zip ./dist + + - name: Prepare Release + uses: softprops/action-gh-release@v2 + with: + draft: true + prerelease: true + generate_release_notes: true + files: ./build.zip diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml new file mode 100644 index 00000000000..5c605299dbc --- /dev/null +++ b/.github/workflows/publish-release.yml @@ -0,0 +1,78 @@ +name: "Publish Release" + +on: + release: + types: [published] + +defaults: + run: + working-directory: ./core + +jobs: + publish-release: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install node + uses: actions/setup-node@v4 + with: + node-version: 20.x + + - name: Python venv + run: python -m venv env + + - name: Activate Python + run: source env/bin/activate + + - name: Update pip + run: pip install --upgrade pip + + - name: Install PyMinifier + run: pip install --ignore-requires-python python-minifier + + - name: Install Setuptools + run: pip install setuptools + + - name: Cache node modules + uses: actions/cache@v4 + env: + cache-name: cache-node-modules + with: + # npm cache files are stored in `~/.npm` on Linux/macOS + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: npm install + run: npm install && npx playwright install chromium + + - name: build + run: npm run build + + - name: Generate index.html in snapshot + working-directory: . + run: sed -e 's#_PATH_#https://pyscript.net/releases/${{ github.ref_name }}/#' -e 's#_DOC_VERSION_#${{ github.ref_name }}#' -e 's#_TAG_VERSION_#/tag/${{ github.ref_name }}#' -e 's#_VERSION_#${{ github.ref_name }}#' ./public/index.html > ./core/dist/index.html + + - name: Generate release.tar from snapshot and put it in dist/ + working-directory: . + run: tar -cvf ../release.tar * && mv ../release.tar . + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-region: ${{ secrets.AWS_REGION }} + role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} + + - name: Sync to S3 + run: + | # Update /latest and create an explicitly versioned directory under releases/YYYY.MM.MICRO/ + aws s3 sync --quiet ./dist/ s3://pyscript.net/latest/ + aws s3 sync --quiet ./dist/ s3://pyscript.net/releases/${{ github.ref_name }}/ diff --git a/.github/workflows/publish-snapshot.yml b/.github/workflows/publish-snapshot.yml new file mode 100644 index 00000000000..b7f51d52ae7 --- /dev/null +++ b/.github/workflows/publish-snapshot.yml @@ -0,0 +1,76 @@ +name: "Publish Snapshot" + +on: + workflow_dispatch: + inputs: + snapshot_version: + description: "The calver version of this snapshot: 2022.09.1 or 2022.09.1.RC1" + type: string + required: true + +defaults: + run: + working-directory: ./core + +jobs: + publish-snapshot: + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install node + uses: actions/setup-node@v4 + with: + node-version: 20.x + + - name: Python venv + run: python -m venv env + + - name: Activate Python + run: source env/bin/activate + + - name: Update pip + run: pip install --upgrade pip + + - name: Install PyMinifier + run: pip install --ignore-requires-python python-minifier + + - name: Install Setuptools + run: pip install setuptools + + - name: Cache node modules + uses: actions/cache@v4 + env: + cache-name: cache-node-modules + with: + # npm cache files are stored in `~/.npm` on Linux/macOS + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: Install Dependencies + run: npm install && npx playwright install chromium + + - name: Build Pyscript.core + run: npm run build + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-region: ${{ secrets.AWS_REGION }} + role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} + + - name: Generate index.html in snapshot + working-directory: . + run: sed -e 's#_PATH_#https://pyscript.net/snapshots/${{ inputs.snapshot_version }}/#' -e 's#_DOC_VERSION_#${{ inputs.snapshot_version }}#' -e 's#_TAG_VERSION_#/tag/${{ inputs.snapshot_version }}#' -e 's#_VERSION_#${{ inputs.snapshot_version }}#' ./public/index.html > ./core/dist/index.html + + - name: Copy to Snapshot + run: > + aws s3 sync ./dist/ s3://pyscript.net/snapshots/${{ inputs.snapshot_version }}/ diff --git a/.github/workflows/publish-unstable.yml b/.github/workflows/publish-unstable.yml new file mode 100644 index 00000000000..89a0e2b8902 --- /dev/null +++ b/.github/workflows/publish-unstable.yml @@ -0,0 +1,76 @@ +name: "Publish Unstable" + +on: + push: # Only run on merges into main that modify files under core/ and examples/ + branches: + - main + paths: + - core/** + - examples/** + + workflow_dispatch: + +jobs: + publish-unstable: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + defaults: + run: + working-directory: ./core + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install node + uses: actions/setup-node@v4 + with: + node-version: 20.x + + - name: Python venv + run: python -m venv env + + - name: Activate Python + run: source env/bin/activate + + - name: Update pip + run: pip install --upgrade pip + + - name: Install PyMinifier + run: pip install --ignore-requires-python python-minifier + + - name: Install Setuptools + run: pip install setuptools + + - name: Cache node modules + uses: actions/cache@v4 + env: + cache-name: cache-node-modules + with: + # npm cache files are stored in `~/.npm` on Linux/macOS + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: NPM Install + run: npm install && npx playwright install chromium + + - name: Build + run: npm run build + + - name: Generate index.html in snapshot + working-directory: . + run: sed -e 's#_PATH_#./#' -e 's#_DOC_VERSION_#latest#' -e 's#_TAG_VERSION_##' -e 's#_VERSION_#latest#' ./public/index.html > ./core/dist/index.html + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-region: ${{ secrets.AWS_REGION }} + role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} + + - name: Sync to S3 + run: aws s3 sync --quiet ./dist/ s3://pyscript.net/unstable/ diff --git a/.github/workflows/sync-examples.yml b/.github/workflows/sync-examples.yml deleted file mode 100644 index c67c8c5c1a8..00000000000 --- a/.github/workflows/sync-examples.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: '[CI] Sync Examples' - -on: - push: # Only run on merges into main that modify files under examples/ - branches: - - main - paths: - - examples/** - - .github/workflows/sync-examples.yml # Test that workflow works when changed - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - defaults: - run: - working-directory: examples - - steps: - - # Deploy to S3 - - name: Checkout - uses: actions/checkout@v3 - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v1.6.1 - with: - aws-region: ${{secrets.AWS_REGION}} - role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} - - name: Sync to S3 - # Sync outdated or new files, delete ones no longer in source - run: aws s3 sync --quiet --delete . s3://pyscript.net/examples/ # Sync directory, delete what is not in source diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000000..785b7cbbf3f --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,80 @@ +name: "[CI] Test" + +on: + push: # Only run on merges into main that modify certain files + branches: + - main + paths: + - core/** + - .github/workflows/test.yml + + pull_request: # Only run on merges into main that modify certain files + branches: + - main + paths: + - core/** + - .github/workflows/test.yml + workflow_dispatch: + +jobs: + BuildAndTest: + runs-on: ubuntu-latest + env: + MINICONDA_PYTHON_VERSION: py38 + MINICONDA_VERSION: 4.11.0 + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 3 + + # display a git log: when you run CI on PRs, github automatically + # merges the PR into main and run the CI on that commit. The idea + # here is to show enough of git log to understand what is the + # actual commit (in the PR) that we are using. See also + # 'fetch-depth: 3' above. + - name: git log + run: git log --graph -3 + + - name: Install node + uses: actions/setup-node@v4 + with: + node-version: 20.x + + - name: Cache node modules + uses: actions/cache@v4 + env: + cache-name: cache-node-modules + with: + # npm cache files are stored in `~/.npm` on Linux/macOS + path: ~/.npm + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: setup Miniconda + uses: conda-incubator/setup-miniconda@v3 + + - name: Create and activate virtual environment + run: | + python3 -m venv test_venv + source test_venv/bin/activate + echo PATH=$PATH >> $GITHUB_ENV + echo VIRTUAL_ENV=$VIRTUAL_ENV >> $GITHUB_ENV + + - name: Setup dependencies in virtual environment + run: | + make setup + + - name: Build + run: make build # Integration tests run in the build step. + + - uses: actions/upload-artifact@v4 + with: + name: pyscript + path: | + core/dist/ + if-no-files-found: error + retention-days: 7 diff --git a/.gitignore b/.gitignore index da873c29f20..6ccef40cf9e 100644 --- a/.gitignore +++ b/.gitignore @@ -51,7 +51,6 @@ coverage.xml *.py,cover .hypothesis/ .pytest_cache/ -pyscriptjs/examples # Translations *.mo @@ -136,3 +135,18 @@ dmypy.json .pyre/ node_modules/ + +coverage/ + +# junit xml for test results +test_results + +# @pyscript/core npm artifacts +core/test-results/* +core/core.* +core/dist +core/dist.zip +core/src/plugins.js +core/src/stdlib/pyscript.js +core/src/3rd-party/* +!core/src/3rd-party/READMEmd diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4d1377d04e5..b18b22ee168 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,89 +1,53 @@ # This is the configuration for pre-commit, a local framework for managing pre-commit hooks # Check out the docs at: https://pre-commit.com/ +ci: + #skip: [eslint] + autoupdate_schedule: monthly -default_stages: [commit] +default_stages: [pre-commit] repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.2.0 - hooks: - - id: check-builtin-literals - - id: check-case-conflict - - id: check-docstring-first - - id: check-executables-have-shebangs - - id: check-json - exclude: tsconfig.json - - id: check-toml - - id: check-xml - - id: check-yaml - - id: detect-private-key - - id: end-of-file-fixer - exclude: \.min\.js$ - - id: trailing-whitespace - -- repo: https://github.com/PyCQA/bandit - rev: 1.7.4 - hooks: - - id: bandit - args: - - --skip=B201 - -- repo: https://github.com/psf/black - rev: 22.3.0 - hooks: - - id: black - -- repo: https://github.com/codespell-project/codespell - rev: v2.1.0 - hooks: - - id: codespell # See 'setup.cfg' for args - -- repo: https://github.com/PyCQA/flake8 - rev: 4.0.1 - hooks: - - id: flake8 # See 'setup.cfg' for args - additional_dependencies: [flake8-bugbear, flake8-comprehensions] - -- repo: https://github.com/pycqa/isort - rev: 5.10.1 - hooks: - - id: isort - name: isort (python) - args: [--profile, black] - -- repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks - rev: v2.3.0 - hooks: - - id: pretty-format-yaml - args: [--autofix, --indent, '4'] - exclude: .github/ISSUE_TEMPLATE/.*\.yml$ - -- repo: https://github.com/asottile/pyupgrade - rev: v2.32.1 - hooks: - - id: pyupgrade - args: - - --py310-plus - -- repo: https://github.com/pre-commit/mirrors-eslint - rev: v8.16.0 - hooks: - - id: eslint - files: pyscriptjs/src/.*\.[jt]sx?$ # *.js, *.jsx, *.ts and *.tsx - types: [file] - additional_dependencies: - - eslint - - eslint-plugin-svelte3 - - typescript - - '@typescript-eslint/eslint-plugin' - - '@typescript-eslint/parser' - -# Commented out until mdformat-myst supports custom extensions -# See https://github.com/executablebooks/mdformat-myst/pull/9 -# - repo: https://github.com/executablebooks/mdformat -# rev: 0.7.14 # Use the ref you want to point at -# hooks: -# - id: mdformat -# additional_dependencies: -# - mdformat-gfm -# - mdformat-myst -# - mdformat-black + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: check-builtin-literals + - id: check-case-conflict + - id: check-docstring-first + - id: check-executables-have-shebangs + - id: check-json + exclude: tsconfig\.json + - id: check-toml + exclude: bad\.toml + - id: check-xml + - id: check-yaml + - id: detect-private-key + - id: end-of-file-fixer + exclude: core/dist|\.min\.js$ + - id: trailing-whitespace + + - repo: https://github.com/psf/black + rev: 25.1.0 + hooks: + - id: black + exclude: core/tests + args: ["-l", "88", "--skip-string-normalization"] + + - repo: https://github.com/codespell-project/codespell + rev: v2.4.1 + hooks: + - id: codespell # See 'pyproject.toml' for args + exclude: fs\.py|\.js\.map$ + additional_dependencies: + - tomli + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.11.8 + hooks: + - id: ruff + exclude: core/tests + + - repo: https://github.com/hoodmane/pyscript-prettier-precommit + rev: "v3.0.0-alpha.6" + hooks: + - id: prettier + exclude: core/tests|core/dist|core/types|core/src/stdlib/pyscript.js|pyscript\.sw/|core/src/3rd-party + args: [--tab-width, "4"] diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000000..32b310b5153 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,3 @@ +ISSUE_TEMPLATE +*.min.* +package-lock.json diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index 78adcb2e958..00000000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,28 +0,0 @@ -# .readthedocs.yaml -# Read the Docs configuration file -# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details - -# Required -version: 2 - -# Set the version of Python and other tools you might need -build: - os: ubuntu-20.04 - tools: - python: miniconda3-4.7 - -# Build documentation in the docs/ directory with Sphinx -sphinx: - configuration: docs/conf.py - -conda: - environment: docs/environment.yml - -# If using Sphinx, optionally build your docs in additional formats such as PDF -# formats: -# - pdf - -# Optionally declare the Python requirements required to build your docs -python: - install: - - requirements: docs/requirements.txt diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6b770c1a862..8ce2c517a45 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,98 +1,4 @@ # Contributing to PyScript -Thank you for wanting to contribute to the PyScript project! - -## Table of contents - -* [Code of Conduct](#code-of-conduct) -* [Contributing](#contributing) - * [Reporting bugs](#reporting-bugs) - * [Reporting security issues](#reporting-security-issues) - * [Asking questions](#asking-questions) - * [Setting up your environment](#setting-up-your-environment) - * [Places to start](#places-to-start) - * [Submitting a change](#submitting-a-change) -* [License terms for contributions](#license-terms-for-contributions) -* [Becoming a maintainer](#becoming-a-maintainer) -* [Trademarks](#trademarks) - -## Code of Conduct - -The [PyScript Code of Conduct](https://github.com/pyscript/governance/blob/main/CODE-OF-CONDUCT.md) governs the project and everyone participating in it. By participating, you are expected to uphold this code. Please report unacceptable behavior to the maintainers or administrators as described in that document. - -## Contributing - -### Reporting bugs - -Bugs are tracked on the [project issues page](https://github.com/pyscript/pyscript/issues). Please check if your issue has already been filed by someone else by searching the existing issues before filing a new one. Once your issue is filed, it will be triaged by another contributor or maintainer. If there are questions raised about your issue, please respond promptly. - -#### Creating useful issues - -* Use a clear and descriptive title. -* Describe the specific steps that reproduce the problem with as many details as possible so that someone can verify the issue. -* Describe the behavior you observed, and the behavior you had expected. -* Include screenshots if they help make the issue clear. - -### Reporting security issues - -If you aren't confident that it is appropriate to submit a security issue using the above process, you can e-mail it to security@pyscript.net - -### Asking questions - -If you have questions about the project, using PyScript, or anything else, please ask in the [PyScript forum](https://community.anaconda.cloud/c/tech-topics/pyscript). - -### Setting up your environment - -* clone the repo -``` - git clone https://github.com/pyscript/pyscript -``` -* cd into the main project folder -``` - cd pyscript/pyscriptjs -``` -* install the dependencies with npm install - make sure to use nodejs version >= 16 -``` - npm install -``` -* run npm run dev to build and run the dev server. This will also watch for changes and rebuild when a file is saved. -``` - npm run dev -``` - -### Places to start - -If you would like to contribute to PyScript, but you aren't sure where to begin, here are some suggestions. - -* **Read over the existing documentation.** Are there things missing, or could they be clearer? Make some changes/additions to those documents. -* **Review the open issues.** Are they clear? Can you reproduce them? You can add comments, clarifications, or additions to those issues. If you think you have an idea of how to address the issue, submit a fix! -* **Look over the open pull requests.** Do you have comments or suggestions for the proposed changes? Add them. -* **Check out the examples.** Is there a use case that would be good to have sample code for? Create an example for it. - -### Submitting a change - -All contributions must be licensed Apache 2.0, and all files must have a copy of the boilerplate license comment (can be copied from an existing file). - -To create a change for PyScript, you can follow the process described [here](https://docs.github.com/en/get-started/quickstart/contributing-to-projects). - -* Fork a personal copy of the PyScript project. -* Make the changes you would like (don't forget to test them!) -* Please squash all commits for a change into a single commit (this can be done using "git rebase -i"). Do your best to have a well-formed commit message for the change. -* Open a pull request back to the PyScript project and address any comments/questions from the maintainers and other contributors. - -## License terms for contributions - -This Project welcomes contributions, suggestions, and feedback. All contributions, suggestions, and feedback you submitted are accepted under the [Apache 2.0](./LICENSE) license. You represent that if you do not own copyright in the code that you have the authority to submit it under the [Apache 2.0](./LICENSE) license. All feedback, suggestions, or contributions are not confidential. - - -## Becoming a maintainer - -Contributors are invited to be maintainers of the project by demonstrating good decision making in their contributions, a commitment to the goals of the project, and consistent adherence to the [code of conduct](https://github.com/pyscript/governance/blob/main/CODE-OF-CONDUCT.md). New maintainers are invited by a 3/4 vote of the existing maintainers. - -## Trademarks - -The Project abides by the Organization's [trademark policy](https://github.com/pyscript/governance/blob/main/TRADEMARKS.md). - ---- -Part of MVG-0.1-beta. -Made with love by GitHub. Licensed under the [CC-BY 4.0 License](https://creativecommons.org/licenses/by-sa/4.0/). +Please see our guide to contributing to PyScript +[in our documentation](https://docs.pyscript.net/latest/contributing/). diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 4baa1d88374..4a7cc5032a7 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -41,5 +41,6 @@ Any names, trademarks, logos, or goodwill developed by and associated with the P Amendments to this governance policy may be made by affirmative vote of 2/3 of all Maintainers, with approval by the Organization's Steering Committee. --- + Part of MVG-0.1-beta. Made with love by GitHub. Licensed under the [CC-BY 4.0 License](https://creativecommons.org/licenses/by-sa/4.0/). diff --git a/LICENSE b/LICENSE index 261eeb9e9f8..aa530349d35 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,11 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + + Copyright (c) 2022-present, PyScript Development Team + + Originated at Anaconda, Inc. in 2022 + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 58d4eee6c52..ab141aa6186 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -2,17 +2,23 @@ This document lists the Maintainers of the Project. Maintainers may be added once approved by the existing maintainers as described in the [Governance document](https://github.com/pyscript/pyscript/blob/main/GOVERNANCE.md). By adding your name to this list you are agreeing to abide by the Project governance documents and to abide by all of the Organization's polices, including the [code of conduct](https://github.com/pyscript/governance/blob/main/CODE-OF-CONDUCT.md), [trademark policy](https://github.com/pyscript/governance/blob/main/TRADEMARKS.md), and [antitrust policy](https://github.com/pyscript/governance/blob/main/TRADEMARKS.md). If you are participating because of your affiliation with another organization (designated below), you represent that you have the authority to bind that organization to these policies. -| **NAME** | **Organization** | -| ---------------- | ---------------- | -| Fabio Pliger | Anaconda, Inc | -| Antonio Cuni | Anaconda, Inc | -| Philipp Rudiger | Anaconda, Inc | -| Peter Wang | Anaconda, Inc | -| Kevin Goldsmith | Anaconda, Inc | -| Mariana Meireles | Anaconda, Inc | -| --- | --- | +| **NAME** | **Organization** | +| -------------------- | ---------------- | +| Fabio Pliger | Anaconda, Inc | +| Antonio Cuni | Anaconda, Inc | +| Philipp Rudiger | Anaconda, Inc | +| Peter Wang | Anaconda, Inc | +| Kevin Goldsmith | Anaconda, Inc | +| Mariana Meireles | | +| Nicholas H.Tollervey | Anaconda, Inc | +| Madhur Tandon | Anaconda, Inc | +| Ted Patrick | Anaconda, Inc | +| Jeff Glass | | +| Paul Everitt | | +| Fabio Rosado | Anaconda, Inc | +| Andrea Giammarchi | Anaconda, Inc | -______________________________________________________________________ +--- Part of MVG-0.1-beta. Made with love by GitHub. Licensed under the [CC-BY 4.0 License](https://creativecommons.org/licenses/by-sa/4.0/). diff --git a/Makefile b/Makefile new file mode 100644 index 00000000000..0e603bfa847 --- /dev/null +++ b/Makefile @@ -0,0 +1,93 @@ +MIN_NODE_VER := 20 +MIN_NPM_VER := 6 +MIN_PY3_VER := 8 +NODE_VER := $(shell node -v | cut -d. -f1 | sed 's/^v\(.*\)/\1/') +NPM_VER := $(shell npm -v | cut -d. -f1) +PY3_VER := $(shell python3 -c "import sys;t='{v[1]}'.format(v=list(sys.version_info[:2]));print(t)") +PY_OK := $(shell python3 -c "print(int($(PY3_VER) >= $(MIN_PY3_VER)))") + +all: + @echo "\nThere is no default Makefile target right now. Try:\n" + @echo "make setup - check your environment and install the dependencies." + @echo "make update - update dependencies." + @echo "make clean - clean up auto-generated assets." + @echo "make build - build PyScript." + @echo "make precommit-check - run the precommit checks (run eslint)." + @echo "make test - run all automated tests in playwright." + @echo "make fmt - format the code." + @echo "make fmt-check - check the code formatting.\n" + +.PHONY: check-node +check-node: + @if [ $(NODE_VER) -lt $(MIN_NODE_VER) ]; then \ + echo "\033[0;31mBuild requires Node $(MIN_NODE_VER).x or higher: $(NODE_VER) detected.\033[0m"; \ + false; \ + fi + +.PHONY: check-npm +check-npm: + @if [ $(NPM_VER) -lt $(MIN_NPM_VER) ]; then \ + echo "\033[0;31mBuild requires Node $(MIN_NPM_VER).x or higher: $(NPM_VER) detected.\033[0m"; \ + false; \ + fi + +.PHONY: check-python +check-python: + @if [ $(PY_OK) -eq 0 ]; then \ + echo "\033[0;31mRequires Python 3.$(MIN_PY3_VER).x or higher: 3.$(PY3_VER) detected.\033[0m"; \ + false; \ + fi + +# Check the environment, install the dependencies. +setup: check-node check-npm check-python + cd core && npm ci && cd .. +ifeq (,$(VIRTUAL_ENV)$(CONDA_PREFIX)) + echo "\n\n\033[0;31mCannot install Python dependencies. Your virtualenv or conda env is not activated.\033[0m" + false +else + python -m pip install -r requirements.txt +endif + +# Clean up generated assets. +clean: + find . -name \*.py[cod] -delete + rm -rf $(env) *.egg-info + rm -rf .pytest_cache .coverage coverage.xml + +# Build PyScript. +build: precommit-check + cd core && npx playwright install chromium && npm run build + +# Update the dependencies. +update: + python -m pip install -r requirements.txt --upgrade + +# Run the precommit checks (run eslint). +precommit-check: + pre-commit run --all-files + +# Run all automated tests in playwright. +test: + cd core && npm run test:integration + +# Serve the repository with the correct headers. +serve: + npx mini-coi . + +# Format the code. +fmt: fmt-py + @echo "Format completed" + +# Check the code formatting. +fmt-check: fmt-py-check + @echo "Format check completed" + +# Format Python code. +fmt-py: + black -l 88 --skip-string-normalization . + +# Check the format of Python code. +fmt-py-check: + black -l 88 --check . + +.PHONY: $(MAKECMDGOALS) diff --git a/README.md b/README.md index 06af7ed0c99..130a20e6cbe 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,94 @@ # PyScript -## What is PyScript +## PyScript is an open source platform for Python in the browser. -### Summary +Using PyScript is as simple as: -PyScript is a Pythonic alternative to Scratch, JSFiddle, and other "easy to use" programming frameworks, with the goal of making the web a friendly, hackable place where anyone can author interesting and interactive applications. +```html + + + + + + PyScript! + + + + + + + + +``` -To get started see the [getting started tutorial](docs/tutorials/getting-started.md). +PyScript enables the creation of rich Python applications in the browser using +[Pyodide](https://pyodide.org/en/stable/) (a version of +[CPython](https://python.org/)), [MicroPython](https://micropython.org/), +[WASM](https://webassembly.org/), and modern web technologies. It means Python +now runs anywhere a browser runs: desktop, laptop, mobile, tablet, or any other +browser enabled device. -For examples see [here](examples). +To start building, read the +[Beginning PyScript tutorial](https://docs.pyscript.net/latest/beginning-pyscript/). -### Longer Version -PyScript is a meta project that aims to combine multiple open technologies into a framework that allows users to create sophisticated browser applications with Python. It integrates seamlessly with the way the DOM works in the browser and allows users to add Python logic in a way that feels natural both to web and Python developers. +For example applications, see [here](https://pyscript.com/@examples). -## Try PyScript +Other useful resources: -To try PyScript, import the appropriate pyscript files to your html page with: -```html - - -``` -You can then use PyScript components in your html page. PyScript currently implements the following elements: +- Our [Home Page](https://pyscript.net/) as an open source project. +- The [official technical docs](https://docs.pyscript.net/). +- A [YouTube channel](https://www.youtube.com/@PyScriptTV) with helpful videos + and community content. +- A free-to-use [online IDE](https://pyscript.com/) for trying PyScript. +- Our community [Discord Channel](https://discord.gg/BYB2kvyFwm), to keep in + touch . -* ``: can be used to define python code that is executable within the web page. The element itself is not rendered to the page and is only used to add logic -* ``: creates a REPL component that is rendered to the page as a code editor and allows users to write executable code +Every Tuesday at 15:30 UTC there is the _PyScript Community Call_ on zoom, +where we can talk about PyScript development in the open. Most of the +maintainers regularly participate in the call, and everybody is welcome to +join. This meeting is recorded and uploaded to our YouTube channel. -Check out the [the examples directory](examples) folder for more examples on how to use it, all you need to do is open them in Chrome. +Every other Thursday at 16:00 UTC there is the _PyScript FUN_ call: the focus +of this call is to share fun projects, goofy hacks or clever uses of PyScript. +It's a supportive, energetic and entertaining meeting. This meeting is also +recorded and uploaded to our YouTube channel. -## How to Contribute +For more details on how to join the calls and up to date schedule, consult the +official calendar: -Read the [contributing guide](CONTRIBUTING.md) to learn about our development process, reporting bugs and improvements, creating issues and asking questions. +- [Google calendar](https://calendar.google.com/calendar/u/0/embed?src=d3afdd81f9c132a8c8f3290f5cc5966adebdf61017fca784eef0f6be9fd519e0@group.calendar.google.com&ctz=UTC) in UTC time; +- [iCal format](https://calendar.google.com/calendar/ical/d3afdd81f9c132a8c8f3290f5cc5966adebdf61017fca784eef0f6be9fd519e0%40group.calendar.google.com/public/basic.ics). -## Resources +## Contribute -* [Discussion board](https://community.anaconda.cloud/c/tech-topics/pyscript) -* [Home Page](https://pyscript.net/) -* [Blog Post](https://engineering.anaconda.com/2022/04/welcome-pyscript.html) +For technical details of the code, please see the [README](core/README.md) in +the `core` directory. -## Notes +Read the [contributing guide](https://docs.pyscript.net/latest/contributing/) +to learn about our development process, reporting bugs and improvements, +creating issues and asking questions. -* This is an extremely experimental project, so expect things to break! -* PyScript has been only tested on Chrome at the moment. +Check out the [development process](https://docs.pyscript.net/latest/developers/) +documentation for more information on how to setup your development environment. ## Governance -The [PyScript organization governance](https://github.com/pyscript/governance) is documented in a separate repository. +The [PyScript organization governance](https://github.com/pyscript/governance) +is documented in a separate repository. + +## Supporters + +PyScript is an independent open source project. + +However, PyScript was born at [Anaconda Inc](https://anaconda.com/) and its +core contributors are currently employed by Anaconda to work on PyScript. We +would like to acknowledge and celebrate Anaconda's continued support of this +project. Thank you [Anaconda Inc](https://anaconda.com/)! diff --git a/core/LICENSE b/core/LICENSE new file mode 100644 index 00000000000..aa530349d35 --- /dev/null +++ b/core/LICENSE @@ -0,0 +1,205 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + + Copyright (c) 2022-present, PyScript Development Team + + Originated at Anaconda, Inc. in 2022 + + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/core/README.md b/core/README.md new file mode 100644 index 00000000000..d5fd6926a1b --- /dev/null +++ b/core/README.md @@ -0,0 +1,168 @@ +# @pyscript/core + +PyScript brings two Python interpreters to the browser: + +- [MicroPython](https://micropython.org/) - a lean and efficient implementation + of the Python 3 programming language that includes a small subset of the + Python standard library and is optimised to run on microcontrollers and in + constrained environments (like the browser). +- [Pyodide](https://pyodide.org)) - a port of all CPython to WebAssembly. + +These interpreters are compiled to [WebAssembly](https://webassembly.org/) +(shortened to WASM). The browser provides a secure WASM computing sandbox. Both +interpreters are compiled to web assembly with +[Emscripten](https://emscripten.org/). PyScript core maintainers work closely +with the core maintainers of both MicroPython and Pyodide (and CPython). We +work hard to ensure PyScript works efficiently in browsers on all platforms: +desktop, mobile, or elsewhere. + +Our technical documentation for using this project can be +[found here](https://docs.pyscript.net/). + +PyScript sits on two further projects (both written in JavaScript): + +1. [polyscript](https://github.com/pyscript/polyscript/#readme) - used to + bootstrap WASM compiled interpreters in a browser. +2. [coincident](https://github.com/WebReflection/coincident) - used to simplify + worker based tasks. + +PyScript itself is mostly written in JavaScript. The test suite for JavaScript +is in two parts: automated tests run in [playwright](https://playwright.dev/), +and manual tests you have to run in a browser and check yourself. PyScript also +has a plugin system so third parties can extend its capabilities with +JavaScript. Our built-in core plugins can be found in the `src/plugins` +directory. We describe how to write third party plugins in our +[developer documentation](https://docs.pyscript.net/latest/user-guide/plugins/). + +We provide a `pyscript` namespace containing Python modules for common browser +based APIs and features (i.e. you can `import pyscript` in Python code running +inside PyScript, to access these features). The Python code for the `pyscript` +namespace is in `src/stdlib/pyscript` with the associated test suite in +`tests/python`. The tests use the browser friendly +[uPyTest](https://github.com/ntoll/upytest) test framework for checking Python +code running _within_ PyScript. All the Python tests are run in each each +available interpreter in both the main thread and a web worker (i.e. the +test suite is run four times, accounting for each combination of interpreter +and main/worker context). + +When you create a local build all the automated tests (JavaScript and Python) +are run. + +## Developer Guide + +Full instructions for setting up a working development environment, how to +build PyScript and how to test it can be +[found in our official docs](https://docs.pyscript.net/latest/developers/). + +The short version is: + +- Ensure you have Python, node and npm installed. +- Create a Python virtual environment. +- In the root of this repository `make setup`. +- `make build` to build PyScript. +- As dependencies change over time, `make update` to keep in sync. + +To start using the locally built version of PyScript, you'll need an HTML +page something like this (note the relative paths to assets in the `dist` +directory, in the `` of the document): + +```html + + + + + + Pure Python PyScript tests + + + + + + + +``` + +Once set up, you should be able to run the most common activities via the +`make` command: + +``` +$ make + +There is no default Makefile target right now. Try: + +make setup - check your environment and install the dependencies. +make update - update dependencies. +make clean - clean up auto-generated assets. +make build - build PyScript. +make precommit-check - run the precommit checks (run eslint). +make test - run all automated tests in playwright. +make fmt - format the code. +make fmt-check - check the code formatting. +``` + +## Artifacts + +There are two main artifacts in this project: + +- **stdlib** and its content: `src/stdlib/pyscript.js` exposes, as a + JavaScript object literal, all the _Python_ content within the folder + (recursively). +- **plugins** and its content: `src/plugins.js` exposes all available + _dynamic imports_, and is able to instrument the bundler to create files + apart from the `_dist/_` folder, so that by default _core_ remains as small + as possible. + +Accordingly, whenever a file contains this warning at its first line, **please +do not change such file directly before submitting a merge request**, as that +file will be overwritten at the next `npm run build` command, either here or +in _CI_: + +```js +// ⚠️ This file is an artifact: DO NOT MODIFY +``` + +## Plugins + +While community or third party plugins don't need to be part of this repository +and can be added just importing `@pyscript/core` as module, there are a few +plugins that we would like to make available by default and these are +considered _core plugins_. + +To add a _core plugin_ to this project define the plugin entry-point and name +in the `src/plugins` folder (see the `error.js` example) and create, if +necessary, a folder with the same name where extra files or dependencies can be +added. + +The _build_ command will include plugins by name as artifacts so that the +bundler can create ad-hoc files within the `dist/` folder. + +## Python + +The `pyscript` package available in _Python_ lives in the folder +`src/stdlib/pyscript/`. + +All _Python_ files will be embedded automatically whenever `npm run build` +happens and reflected into the `src/stdlib/pyscript.js` file. + +Its _core_ responsibility is to ensure those files will be available through +the filesystem in either the _main_ thread, or any _worker_. + +## Release + +To cut a new release of PyScript simply +[add a new release](https://github.com/pyscript/pyscript/releases) while +remembering to write a comprehensive changelog. A +[GitHub action](https://github.com/pyscript/pyscript/blob/main/.github/workflows/publish-release.yml) +will kick in and ensure the release is described and deployed to a URL with the +pattern: https://pyscript.net/releases/YYYY.M.v/ (year/month/version - as per +our [CalVer](https://calver.org/) versioning scheme). + +Then, the following three separate repositories need updating: + +- [Documentation](https://github.com/pyscript/docs) - Change the `version.json` + file in the root of the directory and then `node version-update.js`. +- [Homepage](https://github.com/pyscript/pyscript.net) - Ensure the version + referenced in `index.html` is the latest version. +- [PSDC](https://pyscript.com) - Use discord or Anaconda Slack (if you work at + Anaconda) to let the PSDC team know there's a new version, so they can update + their project templates. diff --git a/core/dev.cjs b/core/dev.cjs new file mode 100644 index 00000000000..08bb9e2affb --- /dev/null +++ b/core/dev.cjs @@ -0,0 +1,31 @@ +let queue = Promise.resolve(); + +const { exec } = require("node:child_process"); + +const build = (fileName) => { + if (fileName) console.log(fileName, "changed"); + else console.log("building without optimizations"); + queue = queue.then( + () => + new Promise((resolve) => { + exec( + "npm run build:stdlib && npm run build:plugins && npm run build:core", + { cwd: __dirname, env: { ...process.env, NO_MIN: true } }, + (error) => { + if (error) console.error(error); + else console.log(fileName || "", "build completed"); + resolve(); + }, + ); + }), + ); +}; + +const options = { + ignored: /\/(?:toml|plugins|pyscript)\.[mc]?js$/, + persistent: true, +}; + +require("chokidar").watch("./src", options).on("change", build); + +build(); diff --git a/core/eslint.config.mjs b/core/eslint.config.mjs new file mode 100644 index 00000000000..9b9cc86349b --- /dev/null +++ b/core/eslint.config.mjs @@ -0,0 +1,22 @@ +import globals from "globals"; +import js from "@eslint/js"; + +export default [ + js.configs.recommended, + { + ignores: ["**/3rd-party/"], + }, + { + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + globals: { + ...globals.browser, + ...globals.es2021, + }, + }, + rules: { + "no-implicit-globals": ["error"], + }, + }, +]; diff --git a/core/index.js b/core/index.js new file mode 100644 index 00000000000..1d970a7202d --- /dev/null +++ b/core/index.js @@ -0,0 +1 @@ +export * from "./dist/core.js"; diff --git a/core/jsdelivr.js b/core/jsdelivr.js new file mode 100644 index 00000000000..9e9ac722cee --- /dev/null +++ b/core/jsdelivr.js @@ -0,0 +1,2 @@ +// @see https://github.com/jsdelivr/jsdelivr/issues/18528 +export * from "./core/dist/core.js"; diff --git a/core/package-lock.json b/core/package-lock.json new file mode 100644 index 00000000000..6ce7af03450 --- /dev/null +++ b/core/package-lock.json @@ -0,0 +1,4083 @@ +{ + "name": "@pyscript/core", + "version": "0.6.53", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@pyscript/core", + "version": "0.6.53", + "license": "APACHE-2.0", + "dependencies": { + "@ungap/with-resolvers": "^0.1.0", + "@webreflection/idb-map": "^0.3.2", + "@webreflection/utils": "^0.1.0", + "add-promise-listener": "^0.1.3", + "basic-devtools": "^0.1.6", + "polyscript": "^0.17.20", + "sticky-module": "^0.1.1", + "to-json-callback": "^0.1.1", + "type-checked-collections": "^0.1.7" + }, + "devDependencies": { + "@codemirror/commands": "^6.8.1", + "@codemirror/lang-python": "^6.2.1", + "@codemirror/language": "^6.11.0", + "@codemirror/state": "^6.5.2", + "@codemirror/view": "^6.36.8", + "@playwright/test": "^1.52.0", + "@rollup/plugin-commonjs": "^28.0.3", + "@rollup/plugin-node-resolve": "^16.0.1", + "@rollup/plugin-terser": "^0.4.4", + "@webreflection/toml-j0.4": "^1.1.4", + "@xterm/addon-fit": "^0.10.0", + "@xterm/addon-web-links": "^0.11.0", + "@xterm/xterm": "^5.5.0", + "bun": "^1.2.13", + "chokidar": "^4.0.3", + "codedent": "^0.1.2", + "codemirror": "^6.0.1", + "eslint": "^9.27.0", + "flatted": "^3.3.3", + "rollup": "^4.41.0", + "rollup-plugin-postcss": "^4.0.2", + "rollup-plugin-string": "^3.0.0", + "static-handler": "^0.5.3", + "string-width": "^7.2.0", + "typescript": "^5.8.3", + "xterm-readline": "^1.1.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@codemirror/autocomplete": { + "version": "6.18.6", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.18.6.tgz", + "integrity": "sha512-PHHBXFomUs5DF+9tCOM/UoW6XQ4R44lLNNhRaW9PKPTU0D7lIjRg3ElxaJnTwsl/oHiR93WSXDBrekhoUGCPtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@codemirror/commands": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.8.1.tgz", + "integrity": "sha512-KlGVYufHMQzxbdQONiLyGQDUW0itrLZwq3CcY7xpv9ZLRHqzkBSoteocBHtMCoY7/Ci4xhzSrToIeLg7FxHuaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.4.0", + "@codemirror/view": "^6.27.0", + "@lezer/common": "^1.1.0" + } + }, + "node_modules/@codemirror/lang-python": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", + "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.3.2", + "@codemirror/language": "^6.8.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.2.1", + "@lezer/python": "^1.1.4" + } + }, + "node_modules/@codemirror/language": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.11.0.tgz", + "integrity": "sha512-A7+f++LodNNc1wGgoRDTt78cOwWm9KVezApgjOMp1W4hM0898nsqBXwF+sbePE7ZRcjN7Sa1Z5m2oN27XkmEjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.23.0", + "@lezer/common": "^1.1.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0", + "style-mod": "^4.0.0" + } + }, + "node_modules/@codemirror/lint": { + "version": "6.8.5", + "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.8.5.tgz", + "integrity": "sha512-s3n3KisH7dx3vsoeGMxsbRAgKe4O1vbrnKBClm99PU0fWxmxsx5rR2PfqQgIt+2MMJBHbiJ5rfIdLYfB9NNvsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.35.0", + "crelt": "^1.0.5" + } + }, + "node_modules/@codemirror/search": { + "version": "6.5.10", + "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.5.10.tgz", + "integrity": "sha512-RMdPdmsrUf53pb2VwflKGHEe1XVM07hI7vV2ntgw1dmqhimpatSJKva4VA9h4TLUDOD4EIF02201oZurpnEFsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "crelt": "^1.0.5" + } + }, + "node_modules/@codemirror/state": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.5.2.tgz", + "integrity": "sha512-FVqsPqtPWKVVL3dPSxy8wEF/ymIEuVzF1PK3VbUgrxXpJUSHQWWZz4JMToquRxnkw+36LTamCZG2iua2Ptq0fA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@marijn/find-cluster-break": "^1.0.0" + } + }, + "node_modules/@codemirror/view": { + "version": "6.36.8", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.36.8.tgz", + "integrity": "sha512-yoRo4f+FdnD01fFt4XpfpMCcCAo9QvZOtbrXExn4SqzH32YC6LgzqxfLZw/r6Ge65xyY03mK/UfUqrVw1gFiFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.5.0", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz", + "integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.1.tgz", + "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.20.0", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.20.0.tgz", + "integrity": "sha512-fxlS1kkIjx8+vy2SjuCB94q3htSNrufYTXubwiBFeaQHbH6Ipi43gFJq2zCMt6PHhImH3Xmr0NksKDvchWlpQQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.6", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.2.2.tgz", + "integrity": "sha512-+GPzk8PlG0sPpzdU5ZvIRMPidzAnZDl/s9L+y13iodqvb8leL53bTannOrQ/Im7UkpsmFU5Ily5U60LWixnmLg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.14.0.tgz", + "integrity": "sha512-qIbV0/JZr7iSDjqAc60IqbLdsj9GDt16xQtWD+B78d/HAlvysGdZZ6rpJHGAc2T0FQx1X6thsSPdnoiGKdNtdg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.1.tgz", + "integrity": "sha512-gtF186CXhIl1p4pJNGZw8Yc6RlshoePRvE0X91oPGb3vZ8pM3qOS9W9NGPat9LziaBV7XrJWGylNQXkGcnM3IQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/js": { + "version": "9.27.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.27.0.tgz", + "integrity": "sha512-G5JD9Tu5HJEu4z2Uo4aHY2sLV64B7CDMXxFzqzjl3NKd6RVzSXNoE80jk7Y0lJkTTkjiIhBAqmlYwjuBY3tvpA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.6.tgz", + "integrity": "sha512-RBMg5FRL0I0gs51M/guSAj5/e14VQ4tpZnQNWwuDT66P14I43ItmPfIZRhO9fUVIPOAQXU47atlywZ/czoqFPA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.1.tgz", + "integrity": "sha512-0J+zgWxHN+xXONWIyPWKFMgVuJoZuGiIFu8yxk7RJjxkzpGmyja5wRFqZIVtjDVOQpV+Rw0iOAjYPE2eQyjr0w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.14.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.6", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.6.tgz", + "integrity": "sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.3.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node/node_modules/@humanwhocodes/retry": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.1.tgz", + "integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.2.tgz", + "integrity": "sha512-xeO57FpIu4p1Ri3Jq/EXq4ClRm86dVF2z/+kvFnyqVYRavTZmaFaUBbWCOuuTh0o/g7DSsk6kc2vrS4Vl5oPOQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.8.tgz", + "integrity": "sha512-imAbBGkb+ebQyxKgzv5Hu2nmROxoDOXHh80evxdoXNOrvAnVx7zimzc1Oo5h9RlfV4vPXaE2iM5pOFbvOCClWA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.6.tgz", + "integrity": "sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@lezer/common": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.2.3.tgz", + "integrity": "sha512-w7ojc8ejBqr2REPsWxJjrMFsA/ysDCFICn8zEOR9mrqzOu2amhITYuLD8ag6XZf0CFXDrhKqw7+tW8cX66NaDA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@lezer/highlight": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.1.tgz", + "integrity": "sha512-Z5duk4RN/3zuVO7Jq0pGLJ3qynpxUVsh7IbUbGj88+uV2ApSAn6kWg2au3iJb+0Zi7kKtqffIESgNcRXWZWmSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@lezer/lr": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.2.tgz", + "integrity": "sha512-pu0K1jCIdnQ12aWNaAVU5bzi7Bd1w54J3ECgANPmYLtQKP0HBj2cE/5coBD66MT10xbtIuUr7tg0Shbsvk0mDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@lezer/python": { + "version": "1.1.18", + "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.18.tgz", + "integrity": "sha512-31FiUrU7z9+d/ElGQLJFXl+dKOdx0jALlP3KEOsGTex8mvj+SoE1FgItcHWK/axkxCHGUSpqIHt6JAWfWu9Rhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz", + "integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@oven/bun-darwin-aarch64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-aarch64/-/bun-darwin-aarch64-1.2.13.tgz", + "integrity": "sha512-AOU4O9jxRp2TXeqoEfOjEaUNZb3+SUPBN8TIEnUjpnyLWPoYJGCeNdQuCDcUkmF3MJEmEuJdyF1IeOITozpC6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@oven/bun-darwin-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64/-/bun-darwin-x64-1.2.13.tgz", + "integrity": "sha512-kJ2iOvxY8uz5/nu+8zIjKf4LmRIHBH9pJJM2q+tA47U04Tod6k6rtntDOI8SdmRe2M5c87RfbadWdxhpYHFIWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@oven/bun-darwin-x64-baseline": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64-baseline/-/bun-darwin-x64-baseline-1.2.13.tgz", + "integrity": "sha512-bZpIUOvx9np07AmH5MVXGYHWZ40m2vCpNV74fma6sCzBlssJclS2V3BZgO+lLvtUKSqnW3HAyJBGsRF34wPbNw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@oven/bun-linux-aarch64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64/-/bun-linux-aarch64-1.2.13.tgz", + "integrity": "sha512-hocSJmblX4CCjP1HpaM64I65erB+CONUCCwKzGGOfLGLobVi+vn/G56UaYWsje1y/Z7WlVaUSgKYVWl7EJ6T9g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oven/bun-linux-aarch64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64-musl/-/bun-linux-aarch64-musl-1.2.13.tgz", + "integrity": "sha512-P56m718KXeyu4Vq5fsESFktfu+0Us1jhu/ZzgHYFRYJcm/hjs6AUA/RJtUAifFy5PNAM5IJdrYl3xPsE8Wa+pg==", + "cpu": [ + "aarch64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oven/bun-linux-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64/-/bun-linux-x64-1.2.13.tgz", + "integrity": "sha512-pf8+Kn2GLrFKLcb8JSLM6Z147Af6L9GQODpnOHM4gvXQv6E/GwQg47/o+7f1XCfzib3fdzOTJlDPvvO1rnXOTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oven/bun-linux-x64-baseline": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-baseline/-/bun-linux-x64-baseline-1.2.13.tgz", + "integrity": "sha512-9n1ai2ejEpxEMqpbHQMWFyvacq3MYsB7gh5mxRlFwhNFPCWu/Sv6gyrO+q2vkOYgcEIGhJb6dqJ6L9vBNaL61A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oven/bun-linux-x64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl/-/bun-linux-x64-musl-1.2.13.tgz", + "integrity": "sha512-w5Ob+GM3Ww4yRA6f1N845o6wEvuwHSmipFUGaRaVp4UELrFnIV9G3pmrlBbYHFnWhk13o8Q7H1/4ZphOkCRJmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oven/bun-linux-x64-musl-baseline": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl-baseline/-/bun-linux-x64-musl-baseline-1.2.13.tgz", + "integrity": "sha512-VI8hVdfqk0QmbAbyrsIdo2O95n3fkbt72E0h3Wu69cHD1iKJqRXG28R8QoHdehoLSJnKVzRTwsUzHp764nefWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@oven/bun-windows-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-windows-x64/-/bun-windows-x64-1.2.13.tgz", + "integrity": "sha512-sArgbRmT7V3mUdNFaAdUcuJsuS+oeMDZLPWFSg0gtQZpRrURs9nPzEnZMmVCFo4+kPF9Tb5ujQT9uDySh6/qVg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@oven/bun-windows-x64-baseline": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@oven/bun-windows-x64-baseline/-/bun-windows-x64-baseline-1.2.13.tgz", + "integrity": "sha512-Aiezu99fOUJJpzGuylOJryd6w9Syg2TBigHeXV2+RJsouBzvAnIEYIBA94ZspRq1ulD26Wmkk8Ae+jZ4edk9GA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@playwright/test": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.52.0.tgz", + "integrity": "sha512-uh6W7sb55hl7D6vsAeA+V2p5JnlAqzhqFyF0VcJkKZXkgnFcVG9PziERRHQfPLfNGx1C292a4JqbWzhR8L4R1g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.52.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@rollup/plugin-commonjs": { + "version": "28.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-28.0.3.tgz", + "integrity": "sha512-pyltgilam1QPdn+Zd9gaCfOLcnjMEJ9gV+bTw6/r73INdvzf1ah9zLIJBm+kW7R6IUFIQ1YO+VqZtYxZNWFPEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "fdir": "^6.2.0", + "is-reference": "1.2.1", + "magic-string": "^0.30.3", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=16.0.0 || 14 >= 14.17" + }, + "peerDependencies": { + "rollup": "^2.68.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.1.tgz", + "integrity": "sha512-tk5YCxJWIG81umIvNkSod2qK5KyQW19qcBF/B78n1bjtOON6gzKoVeSzAE8yHCZEDmqkHKkxplExA8KzdJLJpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-terser": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.4.tgz", + "integrity": "sha512-XHeJC5Bgvs8LfukDwWZp7yeqin6ns8RTl2B9avbejt6tZqsqvVoWI7ZTQrcNsfKEDWBTnTxM8nMDkO2IFFbd0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "serialize-javascript": "^6.0.1", + "smob": "^1.0.0", + "terser": "^5.17.4" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.4.tgz", + "integrity": "sha512-USm05zrsFxYLPdWWq+K3STlWiT/3ELn3RcV5hJMghpeAIhxfsUIg6mt12CBJBInWMV4VneoV7SfGv8xIwo2qNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.41.0.tgz", + "integrity": "sha512-KxN+zCjOYHGwCl4UCtSfZ6jrq/qi88JDUtiEFk8LELEHq2Egfc/FgW+jItZiOLRuQfb/3xJSgFuNPC9jzggX+A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.41.0.tgz", + "integrity": "sha512-yDvqx3lWlcugozax3DItKJI5j05B0d4Kvnjx+5mwiUpWramVvmAByYigMplaoAQ3pvdprGCTCE03eduqE/8mPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.41.0.tgz", + "integrity": "sha512-2KOU574vD3gzcPSjxO0eyR5iWlnxxtmW1F5CkNOHmMlueKNCQkxR6+ekgWyVnz6zaZihpUNkGxjsYrkTJKhkaw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.41.0.tgz", + "integrity": "sha512-gE5ACNSxHcEZyP2BA9TuTakfZvULEW4YAOtxl/A/YDbIir/wPKukde0BNPlnBiP88ecaN4BJI2TtAd+HKuZPQQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.41.0.tgz", + "integrity": "sha512-GSxU6r5HnWij7FoSo7cZg3l5GPg4HFLkzsFFh0N/b16q5buW1NAWuCJ+HMtIdUEi6XF0qH+hN0TEd78laRp7Dg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.41.0.tgz", + "integrity": "sha512-KGiGKGDg8qLRyOWmk6IeiHJzsN/OYxO6nSbT0Vj4MwjS2XQy/5emsmtoqLAabqrohbgLWJ5GV3s/ljdrIr8Qjg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.41.0.tgz", + "integrity": "sha512-46OzWeqEVQyX3N2/QdiU/CMXYDH/lSHpgfBkuhl3igpZiaB3ZIfSjKuOnybFVBQzjsLwkus2mjaESy8H41SzvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.41.0.tgz", + "integrity": "sha512-lfgW3KtQP4YauqdPpcUZHPcqQXmTmH4nYU0cplNeW583CMkAGjtImw4PKli09NFi2iQgChk4e9erkwlfYem6Lg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.41.0.tgz", + "integrity": "sha512-nn8mEyzMbdEJzT7cwxgObuwviMx6kPRxzYiOl6o/o+ChQq23gfdlZcUNnt89lPhhz3BYsZ72rp0rxNqBSfqlqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.41.0.tgz", + "integrity": "sha512-l+QK99je2zUKGd31Gh+45c4pGDAqZSuWQiuRFCdHYC2CSiO47qUWsCcenrI6p22hvHZrDje9QjwSMAFL3iwXwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loongarch64-gnu": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.41.0.tgz", + "integrity": "sha512-WbnJaxPv1gPIm6S8O/Wg+wfE/OzGSXlBMbOe4ie+zMyykMOeqmgD1BhPxZQuDqwUN+0T/xOFtL2RUWBspnZj3w==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.41.0.tgz", + "integrity": "sha512-eRDWR5t67/b2g8Q/S8XPi0YdbKcCs4WQ8vklNnUYLaSWF+Cbv2axZsp4jni6/j7eKvMLYCYdcsv8dcU+a6QNFg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.41.0.tgz", + "integrity": "sha512-TWrZb6GF5jsEKG7T1IHwlLMDRy2f3DPqYldmIhnA2DVqvvhY2Ai184vZGgahRrg8k9UBWoSlHv+suRfTN7Ua4A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.41.0.tgz", + "integrity": "sha512-ieQljaZKuJpmWvd8gW87ZmSFwid6AxMDk5bhONJ57U8zT77zpZ/TPKkU9HpnnFrM4zsgr4kiGuzbIbZTGi7u9A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.41.0.tgz", + "integrity": "sha512-/L3pW48SxrWAlVsKCN0dGLB2bi8Nv8pr5S5ocSM+S0XCn5RCVCXqi8GVtHFsOBBCSeR+u9brV2zno5+mg3S4Aw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.41.0.tgz", + "integrity": "sha512-XMLeKjyH8NsEDCRptf6LO8lJk23o9wvB+dJwcXMaH6ZQbbkHu2dbGIUindbMtRN6ux1xKi16iXWu6q9mu7gDhQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.41.0.tgz", + "integrity": "sha512-m/P7LycHZTvSQeXhFmgmdqEiTqSV80zn6xHaQ1JSqwCtD1YGtwEK515Qmy9DcB2HK4dOUVypQxvhVSy06cJPEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.41.0.tgz", + "integrity": "sha512-4yodtcOrFHpbomJGVEqZ8fzD4kfBeCbpsUy5Pqk4RluXOdsWdjLnjhiKy2w3qzcASWd04fp52Xz7JKarVJ5BTg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.41.0.tgz", + "integrity": "sha512-tmazCrAsKzdkXssEc65zIE1oC6xPHwfy9d5Ta25SRCDOZS+I6RypVVShWALNuU9bxIfGA0aqrmzlzoM5wO5SPQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.41.0.tgz", + "integrity": "sha512-h1J+Yzjo/X+0EAvR2kIXJDuTuyT7drc+t2ALY0nIcGPbTatNOf0VWdhEA2Z4AAjv6X1NJV7SYo5oCTYRJhSlVA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@trysound/sax": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@trysound/sax/-/sax-0.2.0.tgz", + "integrity": "sha512-L7z9BgrNEcYyUYtF+HaEfiS5ebkh9jXqbszz7pC0hRBPaatV0XjSD3+eHrpqFemQfgwiFF0QPIarnIihIDn7OA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/@types/estree": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz", + "integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/with-resolvers": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@ungap/with-resolvers/-/with-resolvers-0.1.0.tgz", + "integrity": "sha512-g7f0IkJdPW2xhY7H4iE72DAsIyfuwEFc6JWc2tYFwKDMWWAF699vGjrM348cwQuOXgHpe1gWFe+Eiyjx/ewvvw==", + "license": "ISC" + }, + "node_modules/@webreflection/fetch": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/@webreflection/fetch/-/fetch-0.1.5.tgz", + "integrity": "sha512-zCcqCJoNLvdeF41asAK71XPlwSPieeRDsE09albBunJEksuYPYNillKNQjf8p5BqSoTKTuKrW3lUm3MNodUC4g==", + "license": "MIT" + }, + "node_modules/@webreflection/idb-map": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@webreflection/idb-map/-/idb-map-0.3.2.tgz", + "integrity": "sha512-VLBTx6EUYF/dPdLyyjWWKxQmTWnVXTT1YJekrJUmfGxBcqEVL0Ih2EQptNG/JezkTYgJ0uSTb0yAum/THltBvQ==", + "license": "MIT" + }, + "node_modules/@webreflection/toml-j0.4": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@webreflection/toml-j0.4/-/toml-j0.4-1.1.4.tgz", + "integrity": "sha512-mZI7Oig3IFv7zzwnBLTw/GGSu4ZlUY/3WZdOy7FEjEVJMV0xHNlHhfb3mZ9PAaq1qDyixU2Yd2X52wVvPDaO2g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webreflection/utils": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@webreflection/utils/-/utils-0.1.0.tgz", + "integrity": "sha512-PLug+LMwQbtYasHsJ8JykII02c1drRszSNe2tLl9DuMWaP9ARm8sKty0QejNR2q8VPpFq5/iYExsKd5OT7Hx6A==", + "license": "MIT" + }, + "node_modules/@xterm/addon-fit": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.10.0.tgz", + "integrity": "sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^5.0.0" + } + }, + "node_modules/@xterm/addon-web-links": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-web-links/-/addon-web-links-0.11.0.tgz", + "integrity": "sha512-nIHQ38pQI+a5kXnRaTgwqSHnX7KE6+4SVoceompgHL26unAxdfP6IPqUTSYPQgSwM56hsElfoNrrW5V7BUED/Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@xterm/xterm": "^5.0.0" + } + }, + "node_modules/@xterm/xterm": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz", + "integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==", + "dev": true, + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.14.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", + "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/add-promise-listener": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/add-promise-listener/-/add-promise-listener-0.1.3.tgz", + "integrity": "sha512-hQ6IgGJ7NvvlPYbwdekhdVwPb4QzEptNZ5v7B4XRKz7FukUPDuF/v+R5EFHArWmhmq4d+xv0G4/B5bu2GSiz9Q==", + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/basic-devtools": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/basic-devtools/-/basic-devtools-0.1.6.tgz", + "integrity": "sha512-g9zJ63GmdUesS3/Fwv0B5SYX6nR56TQXmGr+wE5PRTNCnGQMYWhUx/nZB/mMWnQJVLPPAp89oxDNlasdtNkW5Q==", + "license": "ISC" + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "dev": true, + "license": "ISC" + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/browserslist": { + "version": "4.24.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.5.tgz", + "integrity": "sha512-FDToo4Wo82hIdgc1CQ+NQD0hEhmpPjrZ3hiUgwgOG6IuTdlpr8jdjyG24P6cNP1yJpTLzS5OcGgSw0xmDU1/Tw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "caniuse-lite": "^1.0.30001716", + "electron-to-chromium": "^1.5.149", + "node-releases": "^2.0.19", + "update-browserslist-db": "^1.1.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/bun": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/bun/-/bun-1.2.13.tgz", + "integrity": "sha512-EhP1MhFbicqtaRSFCbEZdkcFco8Ov47cNJcB9QmKS8U4cojKHfLU+dQR14lCvLYmtBvGgwv/Lp+9SSver2OPzQ==", + "cpu": [ + "arm64", + "x64", + "aarch64" + ], + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "os": [ + "darwin", + "linux", + "win32" + ], + "bin": { + "bun": "bin/bun.exe", + "bunx": "bin/bun.exe" + }, + "optionalDependencies": { + "@oven/bun-darwin-aarch64": "1.2.13", + "@oven/bun-darwin-x64": "1.2.13", + "@oven/bun-darwin-x64-baseline": "1.2.13", + "@oven/bun-linux-aarch64": "1.2.13", + "@oven/bun-linux-aarch64-musl": "1.2.13", + "@oven/bun-linux-x64": "1.2.13", + "@oven/bun-linux-x64-baseline": "1.2.13", + "@oven/bun-linux-x64-musl": "1.2.13", + "@oven/bun-linux-x64-musl-baseline": "1.2.13", + "@oven/bun-windows-x64": "1.2.13", + "@oven/bun-windows-x64-baseline": "1.2.13" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-api": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-3.0.0.tgz", + "integrity": "sha512-bsTwuIg/BZZK/vreVTYYbSWoe2F+71P7K5QGEX+pT250DZbfU1MQ5prOKpPR+LL6uWKK3KMwMCAS74QB3Um1uw==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.0.0", + "caniuse-lite": "^1.0.0", + "lodash.memoize": "^4.1.2", + "lodash.uniq": "^4.5.0" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001717", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001717.tgz", + "integrity": "sha512-auPpttCq6BDEG8ZAuHJIplGw6GODhjw+/11e7IjpnYCxZcW/ONgPs0KVBJ0d1bY3e2+7PRe5RCLyP+PfwVgkYw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/codedent": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/codedent/-/codedent-0.1.2.tgz", + "integrity": "sha512-qEqzcy5viM3UoCN0jYHZeXZoyd4NZQzYFg0kOBj8O1CgoGG9WYYTF+VeQRsN0OSKFjF3G1u4WDUOtOsWEx6N2w==", + "license": "ISC", + "dependencies": { + "plain-tag": "^0.1.3" + } + }, + "node_modules/codemirror": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.1.tgz", + "integrity": "sha512-J8j+nZ+CdWmIeFIGXEFbFPtpiYacFMDR8GlHK3IyHQJMCaVRfGx9NT+Hxivv1ckLWPvNdZqndbr/7lVhrf/Svg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/commands": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/lint": "^6.0.0", + "@codemirror/search": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0" + } + }, + "node_modules/coincident": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/coincident/-/coincident-3.0.5.tgz", + "integrity": "sha512-caQv9P+P1keF6QGmVn82StddFu3hnpm/Tox1NxbFJe26m4ad0bSKmnAcQNoVnZNVtnLF5xUv2h1jgsXqoetaiA==", + "license": "MIT", + "dependencies": { + "gc-hook": "^0.4.1", + "js-proxy": "^0.5.2", + "next-resolver": "^0.1.2" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/colord": { + "version": "2.9.3", + "resolved": "https://registry.npmjs.org/colord/-/colord-2.9.3.tgz", + "integrity": "sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw==", + "dev": true, + "license": "MIT" + }, + "node_modules/commander": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", + "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-with-sourcemaps": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/concat-with-sourcemaps/-/concat-with-sourcemaps-1.1.0.tgz", + "integrity": "sha512-4gEjHJFT9e+2W/77h/DS5SGUgwDaOwprX8L/gl5+3ixnzkVJJsZWDSelmN3Oilw3LNDZjZV0yqH1hLG3k6nghg==", + "dev": true, + "license": "ISC", + "dependencies": { + "source-map": "^0.6.1" + } + }, + "node_modules/crelt": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", + "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/css-declaration-sorter": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/css-declaration-sorter/-/css-declaration-sorter-6.4.1.tgz", + "integrity": "sha512-rtdthzxKuyq6IzqX6jEcIzQF/YqccluefyCYheovBOLhFT/drQA9zj/UbRAa9J7C0o6EG6u3E6g+vKkay7/k3g==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.0.9" + } + }, + "node_modules/css-select": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-4.3.0.tgz", + "integrity": "sha512-wPpOYtnsVontu2mODhA19JrqWxNsfdatRKd64kmpRbQgh1KtItko5sTnEpPdpSaJszTOhEMlF/RPz28qj4HqhQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.0.1", + "domhandler": "^4.3.1", + "domutils": "^2.8.0", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-tree": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-1.1.3.tgz", + "integrity": "sha512-tRpdppF7TRazZrjJ6v3stzv93qxRcSsFmW6cX0Zm2NVKpxE1WV1HblnghVv9TreireHkqI/VDEsfolRF1p6y7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.0.14", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/css-what": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", + "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/cssnano": { + "version": "5.1.15", + "resolved": "https://registry.npmjs.org/cssnano/-/cssnano-5.1.15.tgz", + "integrity": "sha512-j+BKgDcLDQA+eDifLx0EO4XSA56b7uut3BQFH+wbSaSTuGLuiyTa/wbRYthUXX8LC9mLg+WWKe8h+qJuwTAbHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssnano-preset-default": "^5.2.14", + "lilconfig": "^2.0.3", + "yaml": "^1.10.2" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/cssnano" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/cssnano-preset-default": { + "version": "5.2.14", + "resolved": "https://registry.npmjs.org/cssnano-preset-default/-/cssnano-preset-default-5.2.14.tgz", + "integrity": "sha512-t0SFesj/ZV2OTylqQVOrFgEh5uanxbO6ZAdeCrNsUQ6fVuXwYTxJPNAGvGTxHbD68ldIJNec7PyYZDBrfDQ+6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-declaration-sorter": "^6.3.1", + "cssnano-utils": "^3.1.0", + "postcss-calc": "^8.2.3", + "postcss-colormin": "^5.3.1", + "postcss-convert-values": "^5.1.3", + "postcss-discard-comments": "^5.1.2", + "postcss-discard-duplicates": "^5.1.0", + "postcss-discard-empty": "^5.1.1", + "postcss-discard-overridden": "^5.1.0", + "postcss-merge-longhand": "^5.1.7", + "postcss-merge-rules": "^5.1.4", + "postcss-minify-font-values": "^5.1.0", + "postcss-minify-gradients": "^5.1.1", + "postcss-minify-params": "^5.1.4", + "postcss-minify-selectors": "^5.2.1", + "postcss-normalize-charset": "^5.1.0", + "postcss-normalize-display-values": "^5.1.0", + "postcss-normalize-positions": "^5.1.1", + "postcss-normalize-repeat-style": "^5.1.1", + "postcss-normalize-string": "^5.1.0", + "postcss-normalize-timing-functions": "^5.1.0", + "postcss-normalize-unicode": "^5.1.1", + "postcss-normalize-url": "^5.1.0", + "postcss-normalize-whitespace": "^5.1.1", + "postcss-ordered-values": "^5.1.3", + "postcss-reduce-initial": "^5.1.2", + "postcss-reduce-transforms": "^5.1.0", + "postcss-svgo": "^5.1.0", + "postcss-unique-selectors": "^5.1.1" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/cssnano-utils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cssnano-utils/-/cssnano-utils-3.1.0.tgz", + "integrity": "sha512-JQNR19/YZhz4psLX/rQ9M83e3z2Wf/HdJbryzte4a3NSuafyp9w/I4U+hx5C2S9g41qlstH7DEWnZaaj83OuEA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/csso": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/csso/-/csso-4.2.0.tgz", + "integrity": "sha512-wvlcdIbf6pwKEk7vHj8/Bkc0B4ylXZruLvOgs9doS5eOsOpuodOV2zJChSpkp+pRpYQLQMeF04nr3Z68Sta9jA==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^1.1.2" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dom-serializer": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", + "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.2.0", + "entities": "^2.0.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz", + "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.2.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz", + "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^1.0.1", + "domelementtype": "^2.2.0", + "domhandler": "^4.2.0" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.150", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.150.tgz", + "integrity": "sha512-rOOkP2ZUMx1yL4fCxXQKDHQ8ZXwisb2OycOQVKHgvB3ZI4CvehOd4y2tfnnLDieJ3Zs1RL1Dlp3cMkyIn7nnXA==", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.4.0.tgz", + "integrity": "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "dev": true, + "license": "BSD-2-Clause", + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.27.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.27.0.tgz", + "integrity": "sha512-ixRawFQuMB9DZ7fjU3iGGganFDp3+45bPOdaRurcFHSXO1e/sYwUX/FtQZpLZJR6SjMoJH8hR2pPEAfDyCoU2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.20.0", + "@eslint/config-helpers": "^0.2.1", + "@eslint/core": "^0.14.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.27.0", + "@eslint/plugin-kit": "^0.3.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "@types/json-schema": "^7.0.15", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.3.0", + "eslint-visitor-keys": "^4.2.0", + "espree": "^10.3.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.3.0.tgz", + "integrity": "sha512-pUNxi75F8MJ/GdeKtVLSbYg4ZI34J6C0C7sbL4YOp2exGwen7ZsuBqKzUhXd0qMQ362yET3z+uPwKeg/0C2XCQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", + "integrity": "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.3.0.tgz", + "integrity": "sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.14.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.4.4", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.4.tgz", + "integrity": "sha512-1NZP+GK4GfuAv3PqKvxQRDMjdSRZjnkq7KfhlNrCNNlZ0ygQFpebfrnfnq/W7fpUnAv9aGWmY1zKx7FYL3gwhg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gc-hook": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/gc-hook/-/gc-hook-0.4.1.tgz", + "integrity": "sha512-uiF+uUftDVLr+VRdudsdsT3/LQYnv2ntwhRH964O7xXDI57Smrek5olv75Wb8Nnz6U+7iVTRXsBlxKcsaDTJTQ==", + "license": "ISC" + }, + "node_modules/generic-names": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/generic-names/-/generic-names-4.0.0.tgz", + "integrity": "sha512-ySFolZQfw9FoDb3ed9d80Cm9f0+r7qj+HJkWjeD9RBfpxEVTlVhol+gvaQB/78WbwYfbnNh8nWHHBSlg072y6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "loader-utils": "^3.2.0" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.3.0.tgz", + "integrity": "sha512-vpeMIQKxczTD/0s2CdEWHcb0eeJe6TFjxb+J5xgX7hScxqrGuyjmv4c1D4A/gelKfyox0gJJwIHF+fLjeaM8kQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-escaper": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz", + "integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==", + "license": "MIT" + }, + "node_modules/icss-replace-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/icss-replace-symbols/-/icss-replace-symbols-1.1.0.tgz", + "integrity": "sha512-chIaY3Vh2mh2Q3RGXttaDIzeiPvaVXJ+C4DAh/w3c37SKZ/U6PGMmuicR2EQQp9bKG8zLMCl7I+PtIoOOPp8Gg==", + "dev": true, + "license": "ISC" + }, + "node_modules/icss-utils": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/icss-utils/-/icss-utils-5.1.0.tgz", + "integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/import-cwd/-/import-cwd-3.0.0.tgz", + "integrity": "sha512-4pnzH16plW+hgvRECbDWpQl3cqtvSofHWh44met7ESfZ8UZOWWddm8hEyDTqREJ9RbYHY8gi8DqmaelApoOGMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "import-from": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/import-from/-/import-from-3.0.0.tgz", + "integrity": "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/import-from/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/js-proxy": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/js-proxy/-/js-proxy-0.5.2.tgz", + "integrity": "sha512-gywYozJo2nfzlnYtBZXZCzbcMX8TfEJJtuUcj/uIE6xwqx9UoiOUeZcBb1Gy1IFxs3Tf+1kos8Aiv45P9HAkyQ==", + "license": "MIT", + "dependencies": { + "gc-hook": "^0.4.1", + "proxy-target": "^3.0.2" + } + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lilconfig": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", + "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/loader-utils": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-3.3.1.tgz", + "integrity": "sha512-FMJTLMXfCLMLfJxcX9PFqX5qD88Z5MRGaZCVzfuqeZSPsyiBzs+pahDQjbIWz2QIzPZz0NX9Zy4FX3lmK6YHIg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.17", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz", + "integrity": "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0" + } + }, + "node_modules/mdn-data": { + "version": "2.0.14", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.14.tgz", + "integrity": "sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/next-resolver": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/next-resolver/-/next-resolver-0.1.3.tgz", + "integrity": "sha512-z5KPZ7LERFcc3GZuMlDzTmjfFLM5SeMZFY4kUEuI1oJp9uB+9RtIA6fI8REXcqJ6mid97zR+fMX0jf4YdFihKA==", + "license": "MIT", + "dependencies": { + "@webreflection/utils": "^0.1.0" + } + }, + "node_modules/node-releases": { + "version": "2.0.19", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.19.tgz", + "integrity": "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-url": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz", + "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue": { + "version": "6.6.2", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz", + "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.4", + "p-timeout": "^3.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-timeout": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz", + "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-finally": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz", + "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-5.0.0.tgz", + "integrity": "sha512-eW/gHNMlxdSP6dmG6uJip6FXN0EQBwm2clYYd8Wul42Cwu/DK8HEftzsapcNdYe2MfLiIwZqsDk2RDEsTE79hA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/plain-tag": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/plain-tag/-/plain-tag-0.1.3.tgz", + "integrity": "sha512-yyVAOFKTAElc7KdLt2+UKGExNYwYb/Y/WE9i+1ezCQsJE8gbKSjewfpRqK2nQgZ4d4hhAAGgDCOcIZVilqE5UA==", + "license": "ISC" + }, + "node_modules/playwright": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.52.0.tgz", + "integrity": "sha512-JAwMNMBlxJ2oD1kce4KPtMkDeKGHQstdpFPcPH3maElAXon/QZeTvtsfXmTMRyO9TslfoYOXkSsvao2nE1ilTw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.52.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.52.0.tgz", + "integrity": "sha512-l2osTgLXSMeuLZOML9qYODUQoPPnUsKsb5/P6LJ2e6uPKXUdPK5WYhN4z03G+YNbWmGDY4YENauNu4ZKczreHg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/polyscript": { + "version": "0.17.20", + "resolved": "https://registry.npmjs.org/polyscript/-/polyscript-0.17.20.tgz", + "integrity": "sha512-aqNHp/IjkYk2t+JDaX4IOE3Xv0yO/SFmXGwzXBJoLTknRttJlALvHf8Kx2b3vyKHs6ZRdaXCVCVDmXEwsQVkkQ==", + "license": "APACHE-2.0", + "dependencies": { + "@webreflection/fetch": "^0.1.5", + "@webreflection/idb-map": "^0.3.2", + "@webreflection/utils": "^0.1.0", + "basic-devtools": "^0.1.6", + "codedent": "^0.1.2", + "coincident": "^3.0.5", + "gc-hook": "^0.4.1", + "html-escaper": "^3.0.3", + "proxy-target": "^3.0.2", + "sticky-module": "^0.1.1", + "to-json-callback": "^0.1.1" + } + }, + "node_modules/postcss": { + "version": "8.5.3", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.3.tgz", + "integrity": "sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.8", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-calc": { + "version": "8.2.4", + "resolved": "https://registry.npmjs.org/postcss-calc/-/postcss-calc-8.2.4.tgz", + "integrity": "sha512-SmWMSJmB8MRnnULldx0lQIyhSNvuDl9HfrZkaqqE/WHAhToYsAvDq+yAsA/kIyINDszOp3Rh0GFoNuH5Ypsm3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.0.9", + "postcss-value-parser": "^4.2.0" + }, + "peerDependencies": { + "postcss": "^8.2.2" + } + }, + "node_modules/postcss-colormin": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/postcss-colormin/-/postcss-colormin-5.3.1.tgz", + "integrity": "sha512-UsWQG0AqTFQmpBegeLLc1+c3jIqBNB0zlDGRWR+dQ3pRKJL1oeMzyqmH3o2PIfn9MBdNrVPWhDbT769LxCTLJQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.21.4", + "caniuse-api": "^3.0.0", + "colord": "^2.9.1", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-convert-values": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/postcss-convert-values/-/postcss-convert-values-5.1.3.tgz", + "integrity": "sha512-82pC1xkJZtcJEfiLw6UXnXVXScgtBrjlO5CBmuDQc+dlb88ZYheFsjTn40+zBVi3DkfF7iezO0nJUPLcJK3pvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.21.4", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-discard-comments": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/postcss-discard-comments/-/postcss-discard-comments-5.1.2.tgz", + "integrity": "sha512-+L8208OVbHVF2UQf1iDmRcbdjJkuBF6IS29yBDSiWUIzpYaAhtNl6JYnYm12FnkeCwQqF5LeklOu6rAqgfBZqQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-discard-duplicates": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-discard-duplicates/-/postcss-discard-duplicates-5.1.0.tgz", + "integrity": "sha512-zmX3IoSI2aoenxHV6C7plngHWWhUOV3sP1T8y2ifzxzbtnuhk1EdPwm0S1bIUNaJ2eNbWeGLEwzw8huPD67aQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-discard-empty": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/postcss-discard-empty/-/postcss-discard-empty-5.1.1.tgz", + "integrity": "sha512-zPz4WljiSuLWsI0ir4Mcnr4qQQ5e1Ukc3i7UfE2XcrwKK2LIPIqE5jxMRxO6GbI3cv//ztXDsXwEWT3BHOGh3A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-discard-overridden": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-discard-overridden/-/postcss-discard-overridden-5.1.0.tgz", + "integrity": "sha512-21nOL7RqWR1kasIVdKs8HNqQJhFxLsyRfAnUDm4Fe4t4mCWL9OJiHvlHPjcd8zc5Myu89b/7wZDnOSjFgeWRtw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-load-config": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-3.1.4.tgz", + "integrity": "sha512-6DiM4E7v4coTE4uzA8U//WhtPwyhiim3eyjEMFCnUpzbrkK9wJHgKDT2mR+HbtSrd/NubVaYTOpSpjUl8NQeRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "lilconfig": "^2.0.5", + "yaml": "^1.10.2" + }, + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + "peerDependencies": { + "postcss": ">=8.0.9", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "postcss": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/postcss-merge-longhand": { + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/postcss-merge-longhand/-/postcss-merge-longhand-5.1.7.tgz", + "integrity": "sha512-YCI9gZB+PLNskrK0BB3/2OzPnGhPkBEwmwhfYk1ilBHYVAZB7/tkTHFBAnCrvBBOmeYyMYw3DMjT55SyxMBzjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0", + "stylehacks": "^5.1.1" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-merge-rules": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/postcss-merge-rules/-/postcss-merge-rules-5.1.4.tgz", + "integrity": "sha512-0R2IuYpgU93y9lhVbO/OylTtKMVcHb67zjWIfCiKR9rWL3GUk1677LAqD/BcHizukdZEjT8Ru3oHRoAYoJy44g==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.21.4", + "caniuse-api": "^3.0.0", + "cssnano-utils": "^3.1.0", + "postcss-selector-parser": "^6.0.5" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-minify-font-values": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-minify-font-values/-/postcss-minify-font-values-5.1.0.tgz", + "integrity": "sha512-el3mYTgx13ZAPPirSVsHqFzl+BBBDrXvbySvPGFnQcTI4iNslrPaFq4muTkLZmKlGk4gyFAYUBMH30+HurREyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-minify-gradients": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/postcss-minify-gradients/-/postcss-minify-gradients-5.1.1.tgz", + "integrity": "sha512-VGvXMTpCEo4qHTNSa9A0a3D+dxGFZCYwR6Jokk+/3oB6flu2/PnPXAh2x7x52EkY5xlIHLm+Le8tJxe/7TNhzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "colord": "^2.9.1", + "cssnano-utils": "^3.1.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-minify-params": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/postcss-minify-params/-/postcss-minify-params-5.1.4.tgz", + "integrity": "sha512-+mePA3MgdmVmv6g+30rn57USjOGSAyuxUmkfiWpzalZ8aiBkdPYjXWtHuwJGm1v5Ojy0Z0LaSYhHaLJQB0P8Jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.21.4", + "cssnano-utils": "^3.1.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-minify-selectors": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/postcss-minify-selectors/-/postcss-minify-selectors-5.2.1.tgz", + "integrity": "sha512-nPJu7OjZJTsVUmPdm2TcaiohIwxP+v8ha9NehQ2ye9szv4orirRU3SDdtUmKH+10nzn0bAyOXZ0UEr7OpvLehg==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.0.5" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-modules": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/postcss-modules/-/postcss-modules-4.3.1.tgz", + "integrity": "sha512-ItUhSUxBBdNamkT3KzIZwYNNRFKmkJrofvC2nWab3CPKhYBQ1f27XXh1PAPE27Psx58jeelPsxWB/+og+KEH0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "generic-names": "^4.0.0", + "icss-replace-symbols": "^1.1.0", + "lodash.camelcase": "^4.3.0", + "postcss-modules-extract-imports": "^3.0.0", + "postcss-modules-local-by-default": "^4.0.0", + "postcss-modules-scope": "^3.0.0", + "postcss-modules-values": "^4.0.0", + "string-hash": "^1.1.1" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-modules-extract-imports": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.1.0.tgz", + "integrity": "sha512-k3kNe0aNFQDAZGbin48pL2VNidTF0w4/eASDsxlyspobzU3wZQLOGj7L9gfRe0Jo9/4uud09DsjFNH7winGv8Q==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-local-by-default": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.2.0.tgz", + "integrity": "sha512-5kcJm/zk+GJDSfw+V/42fJ5fhjL5YbFDl8nVdXkJPLLW+Vf9mTD5Xe0wqIaDnLuL2U6cDNpTr+UQ+v2HWIBhzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "icss-utils": "^5.0.0", + "postcss-selector-parser": "^7.0.0", + "postcss-value-parser": "^4.1.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-local-by-default/node_modules/postcss-selector-parser": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", + "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-modules-scope": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/postcss-modules-scope/-/postcss-modules-scope-3.2.1.tgz", + "integrity": "sha512-m9jZstCVaqGjTAuny8MdgE88scJnCiQSlSrOWcTQgM2t32UBe+MUmFSO5t7VMSfAf/FJKImAxBav8ooCHJXCJA==", + "dev": true, + "license": "ISC", + "dependencies": { + "postcss-selector-parser": "^7.0.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-scope/node_modules/postcss-selector-parser": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", + "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-modules-values": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz", + "integrity": "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "icss-utils": "^5.0.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-normalize-charset": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-normalize-charset/-/postcss-normalize-charset-5.1.0.tgz", + "integrity": "sha512-mSgUJ+pd/ldRGVx26p2wz9dNZ7ji6Pn8VWBajMXFf8jk7vUoSrZ2lt/wZR7DtlZYKesmZI680qjr2CeFF2fbUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-normalize-display-values": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-normalize-display-values/-/postcss-normalize-display-values-5.1.0.tgz", + "integrity": "sha512-WP4KIM4o2dazQXWmFaqMmcvsKmhdINFblgSeRgn8BJ6vxaMyaJkwAzpPpuvSIoG/rmX3M+IrRZEz2H0glrQNEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-normalize-positions": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/postcss-normalize-positions/-/postcss-normalize-positions-5.1.1.tgz", + "integrity": "sha512-6UpCb0G4eofTCQLFVuI3EVNZzBNPiIKcA1AKVka+31fTVySphr3VUgAIULBhxZkKgwLImhzMR2Bw1ORK+37INg==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-normalize-repeat-style": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/postcss-normalize-repeat-style/-/postcss-normalize-repeat-style-5.1.1.tgz", + "integrity": "sha512-mFpLspGWkQtBcWIRFLmewo8aC3ImN2i/J3v8YCFUwDnPu3Xz4rLohDO26lGjwNsQxB3YF0KKRwspGzE2JEuS0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-normalize-string": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-normalize-string/-/postcss-normalize-string-5.1.0.tgz", + "integrity": "sha512-oYiIJOf4T9T1N4i+abeIc7Vgm/xPCGih4bZz5Nm0/ARVJ7K6xrDlLwvwqOydvyL3RHNf8qZk6vo3aatiw/go3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-normalize-timing-functions": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-normalize-timing-functions/-/postcss-normalize-timing-functions-5.1.0.tgz", + "integrity": "sha512-DOEkzJ4SAXv5xkHl0Wa9cZLF3WCBhF3o1SKVxKQAa+0pYKlueTpCgvkFAHfk+Y64ezX9+nITGrDZeVGgITJXjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-normalize-unicode": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/postcss-normalize-unicode/-/postcss-normalize-unicode-5.1.1.tgz", + "integrity": "sha512-qnCL5jzkNUmKVhZoENp1mJiGNPcsJCs1aaRmURmeJGES23Z/ajaln+EPTD+rBeNkSryI+2WTdW+lwcVdOikrpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.21.4", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-normalize-url": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-normalize-url/-/postcss-normalize-url-5.1.0.tgz", + "integrity": "sha512-5upGeDO+PVthOxSmds43ZeMeZfKH+/DKgGRD7TElkkyS46JXAUhMzIKiCa7BabPeIy3AQcTkXwVVN7DbqsiCew==", + "dev": true, + "license": "MIT", + "dependencies": { + "normalize-url": "^6.0.1", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-normalize-whitespace": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/postcss-normalize-whitespace/-/postcss-normalize-whitespace-5.1.1.tgz", + "integrity": "sha512-83ZJ4t3NUDETIHTa3uEg6asWjSBYL5EdkVB0sDncx9ERzOKBVJIUeDO9RyA9Zwtig8El1d79HBp0JEi8wvGQnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-ordered-values": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/postcss-ordered-values/-/postcss-ordered-values-5.1.3.tgz", + "integrity": "sha512-9UO79VUhPwEkzbb3RNpqqghc6lcYej1aveQteWY+4POIwlqkYE21HKWaLDF6lWNuqCobEAyTovVhtI32Rbv2RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssnano-utils": "^3.1.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-reduce-initial": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/postcss-reduce-initial/-/postcss-reduce-initial-5.1.2.tgz", + "integrity": "sha512-dE/y2XRaqAi6OvjzD22pjTUQ8eOfc6m/natGHgKFBK9DxFmIm69YmaRVQrGgFlEfc1HePIurY0TmDeROK05rIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.21.4", + "caniuse-api": "^3.0.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-reduce-transforms": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-reduce-transforms/-/postcss-reduce-transforms-5.1.0.tgz", + "integrity": "sha512-2fbdbmgir5AvpW9RLtdONx1QoYG2/EtqpNQbFASDlixBbAYuTcJ0dECwlqNqH7VbaUnEnh8SrxOe2sRIn24XyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", + "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-svgo": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/postcss-svgo/-/postcss-svgo-5.1.0.tgz", + "integrity": "sha512-D75KsH1zm5ZrHyxPakAxJWtkyXew5qwS70v56exwvw542d9CRtTo78K0WeFxZB4G7JXKKMbEZtZayTGdIky/eA==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0", + "svgo": "^2.7.0" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-unique-selectors": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/postcss-unique-selectors/-/postcss-unique-selectors-5.1.1.tgz", + "integrity": "sha512-5JiODlELrz8L2HwxfPnhOWZYWDxVHWL83ufOv84NrcgipI7TaeRsatAhK4Tr2/ZiYldpK/wBvw5BD3qfaK96GA==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.0.5" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/promise.series": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/promise.series/-/promise.series-0.2.0.tgz", + "integrity": "sha512-VWQJyU2bcDTgZw8kpfBpB/ejZASlCrzwz5f2hjb/zlujOEB4oeiAhHygAWq8ubsX2GVkD4kCU5V2dwOTaCY5EQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12" + } + }, + "node_modules/proxy-target": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/proxy-target/-/proxy-target-3.0.2.tgz", + "integrity": "sha512-FFE1XNwXX/FNC3/P8HiKaJSy/Qk68RitG/QEcLy/bVnTAPlgTAWPZKh0pARLAnpfXQPKyalBhk009NRTgsk8vQ==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/resolve": { + "version": "1.22.10", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", + "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/rollup": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.41.0.tgz", + "integrity": "sha512-HqMFpUbWlf/tvcxBFNKnJyzc7Lk+XO3FGc3pbNBLqEbOz0gPLRgcrlS3UF4MfUrVlstOaP/q0kM6GVvi+LrLRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.7" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.41.0", + "@rollup/rollup-android-arm64": "4.41.0", + "@rollup/rollup-darwin-arm64": "4.41.0", + "@rollup/rollup-darwin-x64": "4.41.0", + "@rollup/rollup-freebsd-arm64": "4.41.0", + "@rollup/rollup-freebsd-x64": "4.41.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.41.0", + "@rollup/rollup-linux-arm-musleabihf": "4.41.0", + "@rollup/rollup-linux-arm64-gnu": "4.41.0", + "@rollup/rollup-linux-arm64-musl": "4.41.0", + "@rollup/rollup-linux-loongarch64-gnu": "4.41.0", + "@rollup/rollup-linux-powerpc64le-gnu": "4.41.0", + "@rollup/rollup-linux-riscv64-gnu": "4.41.0", + "@rollup/rollup-linux-riscv64-musl": "4.41.0", + "@rollup/rollup-linux-s390x-gnu": "4.41.0", + "@rollup/rollup-linux-x64-gnu": "4.41.0", + "@rollup/rollup-linux-x64-musl": "4.41.0", + "@rollup/rollup-win32-arm64-msvc": "4.41.0", + "@rollup/rollup-win32-ia32-msvc": "4.41.0", + "@rollup/rollup-win32-x64-msvc": "4.41.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/rollup-plugin-postcss": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/rollup-plugin-postcss/-/rollup-plugin-postcss-4.0.2.tgz", + "integrity": "sha512-05EaY6zvZdmvPUDi3uCcAQoESDcYnv8ogJJQRp6V5kZ6J6P7uAVJlrTZcaaA20wTH527YTnKfkAoPxWI/jPp4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "concat-with-sourcemaps": "^1.1.0", + "cssnano": "^5.0.1", + "import-cwd": "^3.0.0", + "p-queue": "^6.6.2", + "pify": "^5.0.0", + "postcss-load-config": "^3.0.0", + "postcss-modules": "^4.0.0", + "promise.series": "^0.2.0", + "resolve": "^1.19.0", + "rollup-pluginutils": "^2.8.2", + "safe-identifier": "^0.4.2", + "style-inject": "^0.3.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "postcss": "8.x" + } + }, + "node_modules/rollup-plugin-string": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-string/-/rollup-plugin-string-3.0.0.tgz", + "integrity": "sha512-vqyzgn9QefAgeKi+Y4A7jETeIAU1zQmS6VotH6bzm/zmUQEnYkpIGRaOBPY41oiWYV4JyBoGAaBjYMYuv+6wVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "rollup-pluginutils": "^2.4.1" + } + }, + "node_modules/rollup-pluginutils": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", + "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "estree-walker": "^0.6.1" + } + }, + "node_modules/rollup-pluginutils/node_modules/estree-walker": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", + "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-identifier": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/safe-identifier/-/safe-identifier-0.4.2.tgz", + "integrity": "sha512-6pNbSMW6OhAi9j+N8V+U715yBQsaWJ7eyEUaOrawX+isg5ZxhUlV1NipNtgaKHmFGiABwt+ZF04Ii+3Xjkg+8w==", + "dev": true, + "license": "ISC" + }, + "node_modules/serialize-javascript": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/smob": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.5.0.tgz", + "integrity": "sha512-g6T+p7QO8npa+/hNx9ohv1E5pVCmWrVCUzUXJyLdMmftX6ER0oiWY/w9knEonLpnOp6b6FenKnMfR8gqwWdwig==", + "dev": true, + "license": "MIT" + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/stable": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.8.tgz", + "integrity": "sha512-ji9qxRnOVfcuLDySj9qzhGSEFVobyt1kIOSkj1qZzYLzq7Tos/oUUWvotUPQLlrsidqsK6tBH89Bc9kL5zHA6w==", + "deprecated": "Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility", + "dev": true, + "license": "MIT" + }, + "node_modules/static-handler": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/static-handler/-/static-handler-0.5.3.tgz", + "integrity": "sha512-VSg7+Dd6HkgwjdJ9nRN2mmBZkP/u6ICA7RQuLqBFi3KdzWe9BEQXhMiDw3A8TYcllshIVn5nNP5fRcicOPZhzQ==", + "dev": true, + "license": "ISC", + "bin": { + "static-handler": "static-handler.cjs" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/sticky-module": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/sticky-module/-/sticky-module-0.1.1.tgz", + "integrity": "sha512-IuYgnyIMUx/m6rtu14l/LR2MaqOLtpXcWkxPmtPsiScRHEo+S4Tojk+DWFHOncSdFX/OsoLOM4+T92yOmI1AMw==", + "license": "ISC" + }, + "node_modules/string-hash": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/string-hash/-/string-hash-1.1.3.tgz", + "integrity": "sha512-kJUvRUFK49aub+a7T1nNE66EJbZBMnBgoC1UbCZ5n6bsZKBRga4KgBRTMn/pFkeCZSYtNeSyMxPDM0AXWELk2A==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/style-inject": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/style-inject/-/style-inject-0.3.0.tgz", + "integrity": "sha512-IezA2qp+vcdlhJaVm5SOdPPTUu0FCEqfNSli2vRuSIBbu5Nq5UvygTk/VzeCqfLz2Atj3dVII5QBKGZRZ0edzw==", + "dev": true, + "license": "MIT" + }, + "node_modules/style-mod": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.2.tgz", + "integrity": "sha512-wnD1HyVqpJUI2+eKZ+eo1UwghftP6yuFheBqqe+bWCotBjC2K1YnteJILRMs3SM4V/0dLEW1SC27MWP5y+mwmw==", + "dev": true, + "license": "MIT" + }, + "node_modules/stylehacks": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/stylehacks/-/stylehacks-5.1.1.tgz", + "integrity": "sha512-sBpcd5Hx7G6seo7b1LkpttvTz7ikD0LlH5RmdcBNb6fFR0Fl7LQwHDFr300q4cwUqi+IYrFGmsIHieMBfnN/Bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "browserslist": "^4.21.4", + "postcss-selector-parser": "^6.0.4" + }, + "engines": { + "node": "^10 || ^12 || >=14.0" + }, + "peerDependencies": { + "postcss": "^8.2.15" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/svgo": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/svgo/-/svgo-2.8.0.tgz", + "integrity": "sha512-+N/Q9kV1+F+UeWYoSiULYo4xYSDQlTgb+ayMobAXPwMnLvop7oxKMo9OzIrX5x3eS4L4f2UHhc9axXwY8DpChg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@trysound/sax": "0.2.0", + "commander": "^7.2.0", + "css-select": "^4.1.3", + "css-tree": "^1.1.3", + "csso": "^4.2.0", + "picocolors": "^1.0.0", + "stable": "^0.1.8" + }, + "bin": { + "svgo": "bin/svgo" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/terser": { + "version": "5.39.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.39.0.tgz", + "integrity": "sha512-LBAhFyLho16harJoWMg/nZsQYgTrg5jXOn2nCYjRUcZZEdE3qa2zb8QEDRUGVZBW4rlazf2fxkg8tztybTaqWw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser/node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/to-json-callback": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/to-json-callback/-/to-json-callback-0.1.1.tgz", + "integrity": "sha512-BzOeinTT3NjE+FJ2iCvWB8HvyuyBzoH3WlSnJ+AYVC4tlePyZWSYdkQIFOARWiq0t35/XhmI0uQsFiUsRksRqg==", + "license": "ISC" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-checked-collections": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/type-checked-collections/-/type-checked-collections-0.1.7.tgz", + "integrity": "sha512-fLIydlJy7IG9XL4wjRwEcKhxx/ekLXiWiMvcGo01cOMF+TN+5ZqajM1mRNRz2bNNi1bzou2yofhjZEQi7kgl9A==", + "license": "ISC" + }, + "node_modules/typescript": { + "version": "5.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", + "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz", + "integrity": "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/xterm-readline": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/xterm-readline/-/xterm-readline-1.1.2.tgz", + "integrity": "sha512-1+W2nVuQvCYz9OUYwFBiolrSQUui51aDDyacKXt4PuxeBHqzvabQEJ2kwdBDzsmOjz5BwlDTAjJmYpH2OGqLFA==", + "dev": true, + "license": "MIT", + "dependencies": { + "string-width": "^4" + }, + "peerDependencies": { + "@xterm/xterm": "^5.5.0" + } + }, + "node_modules/xterm-readline/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/xterm-readline/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/xterm-readline/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/xterm-readline/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yaml": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", + "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/core/package.json b/core/package.json new file mode 100644 index 00000000000..e551ef25ad7 --- /dev/null +++ b/core/package.json @@ -0,0 +1,114 @@ +{ + "name": "@pyscript/core", + "version": "0.6.53", + "type": "module", + "description": "PyScript", + "module": "./index.js", + "unpkg": "./index.js", + "jsdelivr": "./jsdelivr.js", + "browser": "./index.js", + "main": "./index.js", + "engines": { + "node": ">=20" + }, + "files": [ + "./dist/", + "./src/", + "./types/", + "./index.js", + "./jsdelivr.js", + "LICENSE", + "README.md" + ], + "exports": { + ".": { + "types": "./types/core.d.ts", + "import": "./src/core.js" + }, + "./js": { + "types": "./types/core.d.ts", + "import": "./dist/core.js" + }, + "./css": { + "import": "./dist/core.css" + }, + "./storage": { + "import": "./dist/storage.js" + }, + "./service-worker": { + "import": "./dist/service-worker.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "server": "echo \"➡️ TESTS @ $(tput bold)http://localhost:8080/tests/$(tput sgr0)\"; npx static-handler --coi .", + "build": "export ESLINT_USE_FLAT_CONFIG=true;npm run build:3rd-party && npm run build:stdlib && npm run build:plugins && npm run build:core && npm run build:tests-index && if [ -z \"$NO_MIN\" ]; then eslint src/ && npm run ts && npm run test:integration; fi", + "build:core": "rm -rf dist && rollup --config rollup/core.config.js && cp src/3rd-party/*.css dist/", + "build:flatted": "node rollup/flatted.cjs", + "build:plugins": "node rollup/plugins.cjs", + "build:stdlib": "node rollup/stdlib.cjs", + "build:3rd-party": "node rollup/3rd-party.cjs", + "build:tests-index": "node rollup/build_test_index.cjs", + "clean:3rd-party": "rm src/3rd-party/*.js && rm src/3rd-party/*.css", + "test:integration": "npm run test:ws; static-handler --coi . 2>/dev/null & SH_PID=$!; EXIT_CODE=0; (playwright test tests/js_tests.spec.js && playwright test tests/py_tests.main.spec.js && playwright test tests/py_tests.worker.spec.js) || EXIT_CODE=$?; kill $SH_PID 2>/dev/null; exit $EXIT_CODE", + "test:ws": "bun tests/javascript/ws/index.js & playwright test tests/javascript/ws/index.spec.js", + "dev": "node dev.cjs", + "release": "npm run build && npm run zip", + "size": "echo -e \"\\033[1mdist/*.js file size\\033[0m\"; for js in $(ls dist/*.js); do cat $js | brotli > ._; echo -e \"\\033[2m$js:\\033[0m $(du -h --apparent-size ._ | sed -e 's/[[:space:]]*._//')\"; rm ._; done", + "ts": "rm -rf types && tsc -p .", + "zip": "zip -r dist.zip ./dist" + }, + "keywords": [ + "pyscript", + "core" + ], + "author": "Anaconda Inc.", + "license": "APACHE-2.0", + "dependencies": { + "@ungap/with-resolvers": "^0.1.0", + "@webreflection/idb-map": "^0.3.2", + "@webreflection/utils": "^0.1.0", + "add-promise-listener": "^0.1.3", + "basic-devtools": "^0.1.6", + "polyscript": "^0.17.20", + "sticky-module": "^0.1.1", + "to-json-callback": "^0.1.1", + "type-checked-collections": "^0.1.7" + }, + "devDependencies": { + "@codemirror/commands": "^6.8.1", + "@codemirror/lang-python": "^6.2.1", + "@codemirror/language": "^6.11.0", + "@codemirror/state": "^6.5.2", + "@codemirror/view": "^6.36.8", + "@playwright/test": "^1.52.0", + "@rollup/plugin-commonjs": "^28.0.3", + "@rollup/plugin-node-resolve": "^16.0.1", + "@rollup/plugin-terser": "^0.4.4", + "@webreflection/toml-j0.4": "^1.1.4", + "@xterm/addon-fit": "^0.10.0", + "@xterm/addon-web-links": "^0.11.0", + "@xterm/xterm": "^5.5.0", + "bun": "^1.2.13", + "chokidar": "^4.0.3", + "codedent": "^0.1.2", + "codemirror": "^6.0.1", + "eslint": "^9.27.0", + "flatted": "^3.3.3", + "rollup": "^4.41.0", + "rollup-plugin-postcss": "^4.0.2", + "rollup-plugin-string": "^3.0.0", + "static-handler": "^0.5.3", + "string-width": "^7.2.0", + "typescript": "^5.8.3", + "xterm-readline": "^1.1.2" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pyscript/pyscript.git" + }, + "bugs": { + "url": "https://github.com/pyscript/pyscript/issues" + }, + "homepage": "https://github.com/pyscript/pyscript#readme" +} diff --git a/core/rollup/3rd-party.cjs b/core/rollup/3rd-party.cjs new file mode 100644 index 00000000000..784d54c55c7 --- /dev/null +++ b/core/rollup/3rd-party.cjs @@ -0,0 +1,77 @@ +const { copyFileSync, writeFileSync } = require("node:fs"); +const { join } = require("node:path"); + +const CDN = "https://cdn.jsdelivr.net/npm"; + +const targets = join(__dirname, "..", "src", "3rd-party"); +const node_modules = join(__dirname, "..", "node_modules"); + +const { devDependencies } = require(join(__dirname, "..", "package.json")); + +const v = (name) => devDependencies[name].replace(/[^\d.]/g, ""); + +const dropSourceMap = (str) => + str.replace(/^\/.+? sourceMappingURL=\/.+$/m, ""); + +// Fetch a module via jsdelivr CDN `/+esm` orchestration +// then sanitize the resulting outcome to avoid importing +// anything via `/npm/...` through Rollup +const resolve = (name) => { + const cdn = `${CDN}/${name}@${v(name)}/+esm`; + console.debug("fetching", cdn); + return fetch(cdn) + .then((b) => b.text()) + .then((text) => + text.replace( + /("|')\/npm\/(.+)?\+esm\1/g, + // normalize `/npm/module@version/+esm` as + // just `module` so that rollup can do the rest + (_, quote, module) => { + const i = module.lastIndexOf("@"); + return `${quote}${module.slice(0, i)}${quote}`; + }, + ), + ); +}; + +// create a file rollup can then process and understand +const reBundle = (name) => Promise.resolve(`export * from "${name}";\n`); + +// key/value pairs as: +// "3rd-party/file-name.js" +// string as content or +// Promise as resolved content +const modules = { + // toml + "toml.js": join(node_modules, "@webreflection", "toml-j0.4", "toml.js"), + + // xterm + "xterm.js": resolve("@xterm/xterm"), + "xterm-readline.js": resolve("xterm-readline"), + "xterm_addon-fit.js": fetch(`${CDN}/@xterm/addon-fit/+esm`).then((b) => + b.text(), + ), + "xterm_addon-web-links.js": fetch( + `${CDN}/@xterm/addon-web-links/+esm`, + ).then((b) => b.text()), + "xterm.css": fetch( + `${CDN}/@xterm/xterm@${v("@xterm/xterm")}/css/xterm.min.css`, + ).then((b) => b.text()), + + // codemirror + "codemirror.js": reBundle("codemirror"), + "codemirror_state.js": reBundle("@codemirror/state"), + "codemirror_lang-python.js": reBundle("@codemirror/lang-python"), + "codemirror_language.js": reBundle("@codemirror/language"), + "codemirror_view.js": reBundle("@codemirror/view"), + "codemirror_commands.js": reBundle("@codemirror/commands"), +}; + +for (const [target, source] of Object.entries(modules)) { + if (typeof source === "string") copyFileSync(source, join(targets, target)); + else { + source.then((text) => + writeFileSync(join(targets, target), dropSourceMap(text)), + ); + } +} diff --git a/core/rollup/build_test_index.cjs b/core/rollup/build_test_index.cjs new file mode 100644 index 00000000000..e35cd3aff00 --- /dev/null +++ b/core/rollup/build_test_index.cjs @@ -0,0 +1,73 @@ +const { join } = require("node:path"); +const { lstatSync, readdirSync, writeFileSync } = require("node:fs"); + +// folders to not consider while crawling +const EXCLUDE_DIR = new Set(["ws"]); + +const TEST_DIR = join(__dirname, "..", "tests"); + +const TEST_INDEX = join(TEST_DIR, "index.html"); + +const crawl = (path, tree = {}) => { + for (const file of readdirSync(path)) { + const current = join(path, file); + if (current === TEST_INDEX) continue; + if (lstatSync(current).isDirectory()) { + if (EXCLUDE_DIR.has(file)) continue; + const sub = {}; + tree[file] = sub; + crawl(current, sub); + if (!Reflect.ownKeys(sub).length) { + delete tree[file]; + } + } else if (file.endsWith(".html")) { + const name = file === "index.html" ? "." : file.slice(0, -5); + tree[name] = current.replace(TEST_DIR, ""); + } + } + return tree; +}; + +const createList = (tree) => { + const ul = ["
    "]; + for (const [key, value] of Object.entries(tree)) { + ul.push("
  • "); + if (typeof value === "string") { + ul.push(`${key}.html`); + } else { + if ("." in value) { + ul.push(`${key}`); + delete value["."]; + } else { + ul.push(`${key}`); + } + if (Reflect.ownKeys(value).length) ul.push(createList(value)); + } + ul.push("
  • "); + } + ul.push("
"); + return ul.join(""); +}; + +writeFileSync( + TEST_INDEX, + ` + + + + + PyScript tests + + + ${createList(crawl(TEST_DIR))} + +`, +); diff --git a/core/rollup/core.config.js b/core/rollup/core.config.js new file mode 100644 index 00000000000..0b0933f5cf5 --- /dev/null +++ b/core/rollup/core.config.js @@ -0,0 +1,67 @@ +// This file generates /core.js minified version of the module, which is +// the default exported as npm entry. + +import { nodeResolve } from "@rollup/plugin-node-resolve"; +import commonjs from "@rollup/plugin-commonjs"; +import terser from "@rollup/plugin-terser"; +import postcss from "rollup-plugin-postcss"; + +const plugins = []; + +export default [ + { + input: "./src/core.js", + plugins: plugins.concat( + process.env.NO_MIN + ? [nodeResolve(), commonjs()] + : [nodeResolve(), commonjs(), terser()], + ), + output: { + esModule: true, + dir: "./dist", + sourcemap: true, + }, + }, + { + input: "./src/core.css", + plugins: [ + postcss({ + extract: true, + sourceMap: false, + minimize: !process.env.NO_MIN, + plugins: [], + }), + ], + output: { + file: "./dist/core.css", + }, + onwarn(warning, warn) { + if (warning.code === "FILE_NAME_CONFLICT") return; + warn(warning); + }, + }, + { + input: "./src/storage.js", + plugins: plugins.concat( + process.env.NO_MIN + ? [nodeResolve(), commonjs()] + : [nodeResolve(), commonjs(), terser()], + ), + output: { + esModule: true, + dir: "./dist", + sourcemap: true, + }, + }, + { + input: "./src/service-worker.js", + plugins: plugins.concat( + process.env.NO_MIN + ? [nodeResolve(), commonjs()] + : [nodeResolve(), commonjs(), terser()], + ), + output: { + file: "./dist/service-worker.js", + }, + }, +]; diff --git a/core/rollup/flatted.cjs b/core/rollup/flatted.cjs new file mode 100644 index 00000000000..22ae1d299a4 --- /dev/null +++ b/core/rollup/flatted.cjs @@ -0,0 +1,17 @@ +const { writeFileSync, readFileSync } = require("node:fs"); +const { join } = require("node:path"); + +const flatted = "# https://www.npmjs.com/package/flatted\n\n"; +const source = join( + __dirname, + "..", + "node_modules", + "flatted", + "python", + "flatted.py", +); +const dest = join(__dirname, "..", "src", "stdlib", "pyscript", "flatted.py"); + +const clear = (str) => String(str).replace(/^#.*/gm, "").trimStart(); + +writeFileSync(dest, flatted + clear(readFileSync(source))); diff --git a/core/rollup/plugins.cjs b/core/rollup/plugins.cjs new file mode 100644 index 00000000000..2f8596de751 --- /dev/null +++ b/core/rollup/plugins.cjs @@ -0,0 +1,33 @@ +const { readdirSync, writeFileSync } = require("node:fs"); +const { join } = require("node:path"); + +const plugins = [""]; + +for (const file of readdirSync(join(__dirname, "..", "src", "plugins"))) { + if (/\.js$/.test(file)) { + const name = file.slice(0, -3); + const key = /^[a-zA-Z0-9$_]+$/.test(name) + ? name + : `[${JSON.stringify(name)}]`; + const value = JSON.stringify(`./plugins/${file}`); + plugins.push( + // this comment is needed to avoid bundlers eagerly embedding lazy + // dependencies, causing all sort of issues once in production + // ⚠️ THIS HAS TO BE LIKE THIS or prettier changes it every single time + ` ${key}: () => + import( + /* webpackIgnore: true */ + ${value} + ),`, + ); + } +} + +plugins.push(""); + +writeFileSync( + join(__dirname, "..", "src", "plugins.js"), + `// ⚠️ This file is an artifact: DO NOT MODIFY\nexport default {${plugins.join( + "\n", + )}};\n`, +); diff --git a/core/rollup/stdlib.cjs b/core/rollup/stdlib.cjs new file mode 100644 index 00000000000..9009cbdca88 --- /dev/null +++ b/core/rollup/stdlib.cjs @@ -0,0 +1,66 @@ +const { + readdirSync, + readFileSync, + statSync, + writeFileSync, +} = require("node:fs"); + +const { spawnSync } = require("node:child_process"); + +const { join } = require("node:path"); + +const dedent = require("codedent"); + +const crawl = (path, json) => { + for (const file of readdirSync(path)) { + const full = join(path, file); + if (/\.py$/.test(file)) { + if (process.env.NO_MIN) json[file] = readFileSync(full).toString(); + else { + try { + const { + output: [error, result], + } = spawnSync("pyminify", [ + "--remove-literal-statements", + full, + ]); + if (error) { + console.error(error); + process.exit(1); + } + json[file] = result.toString(); + } catch (error) { + console.error(error); + console.log( + dedent(` + \x1b[1m⚠️ is your env activated?\x1b[0m + \x1b[2mYou need a Python env to run \x1b[0mpyminify\x1b[2m.\x1b[0m + \x1b[2mTo do so, you can try the following:\x1b[0m + python -m venv env + source env/bin/activate + pip install --upgrade pip + pip install --ignore-requires-python python-minifier + pip install setuptools + \x1b[2mand you can then try \x1b[0mnpm run build\x1b[2m again.\x1b[0m + `), + ); + process.exit(1); + } + } + } else if (statSync(full).isDirectory() && !file.endsWith("_")) + crawl(full, (json[file] = {})); + } +}; + +const json = {}; + +crawl(join(__dirname, "..", "src", "stdlib"), json); + +writeFileSync( + join(__dirname, "..", "src", "stdlib", "pyscript.js"), + `// ⚠️ This file is an artifact: DO NOT MODIFY\nexport default ${JSON.stringify( + json, + null, + " ", + )};\n`, +); diff --git a/core/src/3rd-party-licenses/codemirror.license.txt b/core/src/3rd-party-licenses/codemirror.license.txt new file mode 100644 index 00000000000..d69b9ac5e1a --- /dev/null +++ b/core/src/3rd-party-licenses/codemirror.license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/codemirror_commands.license.txt b/core/src/3rd-party-licenses/codemirror_commands.license.txt new file mode 100644 index 00000000000..4bd5334ad1a --- /dev/null +++ b/core/src/3rd-party-licenses/codemirror_commands.license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/codemirror_lang-python.license.txt b/core/src/3rd-party-licenses/codemirror_lang-python.license.txt new file mode 100644 index 00000000000..4bd5334ad1a --- /dev/null +++ b/core/src/3rd-party-licenses/codemirror_lang-python.license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/codemirror_language.license.txt b/core/src/3rd-party-licenses/codemirror_language.license.txt new file mode 100644 index 00000000000..4bd5334ad1a --- /dev/null +++ b/core/src/3rd-party-licenses/codemirror_language.license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/codemirror_state.license.txt b/core/src/3rd-party-licenses/codemirror_state.license.txt new file mode 100644 index 00000000000..4bd5334ad1a --- /dev/null +++ b/core/src/3rd-party-licenses/codemirror_state.license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/codemirror_view.license.txt b/core/src/3rd-party-licenses/codemirror_view.license.txt new file mode 100644 index 00000000000..4bd5334ad1a --- /dev/null +++ b/core/src/3rd-party-licenses/codemirror_view.license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/toml.license.txt b/core/src/3rd-party-licenses/toml.license.txt new file mode 100644 index 00000000000..62b9b39f687 --- /dev/null +++ b/core/src/3rd-party-licenses/toml.license.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jak Wings + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/core/src/3rd-party-licenses/xterm-readline.license.txt b/core/src/3rd-party-licenses/xterm-readline.license.txt new file mode 100644 index 00000000000..dffe82aba51 --- /dev/null +++ b/core/src/3rd-party-licenses/xterm-readline.license.txt @@ -0,0 +1,25 @@ +Copyright 2021 Erik Bremen + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/xterm.license.txt b/core/src/3rd-party-licenses/xterm.license.txt new file mode 100644 index 00000000000..4472336c9f3 --- /dev/null +++ b/core/src/3rd-party-licenses/xterm.license.txt @@ -0,0 +1,21 @@ +Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js) +Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com) +Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/xterm_addon-fit.license.txt b/core/src/3rd-party-licenses/xterm_addon-fit.license.txt new file mode 100644 index 00000000000..1c0bbe0f368 --- /dev/null +++ b/core/src/3rd-party-licenses/xterm_addon-fit.license.txt @@ -0,0 +1,19 @@ +Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party-licenses/xterm_addon-web-links.lixense.txt b/core/src/3rd-party-licenses/xterm_addon-web-links.lixense.txt new file mode 100644 index 00000000000..1de619d1e8e --- /dev/null +++ b/core/src/3rd-party-licenses/xterm_addon-web-links.lixense.txt @@ -0,0 +1,19 @@ +Copyright (c) 2017, The xterm.js authors (https://github.com/xtermjs/xterm.js) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/core/src/3rd-party/README.md b/core/src/3rd-party/README.md new file mode 100644 index 00000000000..45b1320432f --- /dev/null +++ b/core/src/3rd-party/README.md @@ -0,0 +1,11 @@ +# PyScript 3rd Party + +This folder contains artifacts created via [3rd-party.cjs](../../rollup/3rd-party.cjs). + +As we would like to offer a way to run PyScript offline, and we already offer a `dist` folder with all the necessary scripts, we have created a foreign dependencies resolver that allow to lazy-load CDN dependencies out of the box. + +Please **note** these dependencies are **not interpreters**, because interpreters have their own mechanism, folders structure, WASM files, and whatnot, to work locally, but at least XTerm or the TOML parser, among other lazy dependencies, should be available within the dist folder. + +## Licenses + +All licenses provided by 3rd-party authors can be found in [3rd-party-licenses](../3rd-party-licenses/) folder. diff --git a/core/src/3rd-party/codemirror.js b/core/src/3rd-party/codemirror.js new file mode 100644 index 00000000000..2a1a953a9a0 --- /dev/null +++ b/core/src/3rd-party/codemirror.js @@ -0,0 +1 @@ +export * from "codemirror"; diff --git a/core/src/3rd-party/codemirror_commands.js b/core/src/3rd-party/codemirror_commands.js new file mode 100644 index 00000000000..1862cebc7bb --- /dev/null +++ b/core/src/3rd-party/codemirror_commands.js @@ -0,0 +1 @@ +export * from "@codemirror/commands"; diff --git a/core/src/3rd-party/codemirror_lang-python.js b/core/src/3rd-party/codemirror_lang-python.js new file mode 100644 index 00000000000..76b718d3b66 --- /dev/null +++ b/core/src/3rd-party/codemirror_lang-python.js @@ -0,0 +1 @@ +export * from "@codemirror/lang-python"; diff --git a/core/src/3rd-party/codemirror_language.js b/core/src/3rd-party/codemirror_language.js new file mode 100644 index 00000000000..632a9f72919 --- /dev/null +++ b/core/src/3rd-party/codemirror_language.js @@ -0,0 +1 @@ +export * from "@codemirror/language"; diff --git a/core/src/3rd-party/codemirror_state.js b/core/src/3rd-party/codemirror_state.js new file mode 100644 index 00000000000..9dd5c97d8a1 --- /dev/null +++ b/core/src/3rd-party/codemirror_state.js @@ -0,0 +1 @@ +export * from "@codemirror/state"; diff --git a/core/src/3rd-party/codemirror_view.js b/core/src/3rd-party/codemirror_view.js new file mode 100644 index 00000000000..3669d051e72 --- /dev/null +++ b/core/src/3rd-party/codemirror_view.js @@ -0,0 +1 @@ +export * from "@codemirror/view"; diff --git a/core/src/3rd-party/toml.js b/core/src/3rd-party/toml.js new file mode 100644 index 00000000000..8c635be81b2 --- /dev/null +++ b/core/src/3rd-party/toml.js @@ -0,0 +1,3 @@ +const{SyntaxError:r,parse:t}=function(){function r(t,e,n,u){this.message=t,this.expected=e,this.found=n,this.location=u,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,r)}return function(r,t){function e(){this.constructor=r}e.prototype=t.prototype,r.prototype=new e}(r,Error),r.buildMessage=function(r,t){var e={literal:function(r){return'"'+u(r.text)+'"'},class:function(r){var t,e="";for(t=0;t0){for(t=1,n=1;t20||20===t.length&&t>n)&&(e=!0)}else{"+"===t[0]&&(t=t.substr(1));var u="9223372036854775807";(t.length>19||19===t.length&&t>u)&&(e=!0)}return e&&Dt(r+" is not a 64-bit signed integer."),t=parseInt(t,10),o(t)||Dt(r+" is not a 64-bit signed integer."),{type:"Integer",value:t}},kr="+",Br=jt("+",!1),Jr="-",Pr=jt("-",!1),Vr=/^[0-9]/,Wr=Ht([["0","9"]],!1,!1),qr="T",Gr=jt("T",!1),Kr=function(){var r=Tt(),t=new Date(r);return o(t.getTime())||Dt("Date-time "+r+" is invalid. It does not conform to RFC 3339 or this is a browser-specific problem."),{type:"DateTime",value:t}},Lr=Mt("FullDate (YYYY-mm-dd)"),Xr=":",$r=jt(":",!1),rt=Mt("Hour (HH)"),tt=Mt("Minute (MM)"),et=Mt("Second (SS)"),nt=Mt("TimeOffset (Z or +/-HH:MM)"),ut="Z",ot=jt("Z",!1),at="[",it=jt("[",!1),ct=",",ft=jt(",",!1),st="]",lt=jt("]",!1),ht=function(r){for(var t={type:"Array",value:r?r[0]:[]},e=0,n=t.value,u=n.length;eFt&&(Ft=mt,wt=[]),wt.push(r))}function Zt(){var r,e,n,u,o,a,i,c;for(r=mt,e=[],(n=Rt())===p&&(n=It())===p&&(n=Ut());n!==p;)e.push(n),(n=Rt())===p&&(n=It())===p&&(n=Ut());if(e!==p){if(n=mt,u=function(){var r,e;r=mt,e=function(){var r,e,n,u;r=mt,91===t.charCodeAt(mt)?(e=at,mt++):(e=p,0===Et&&Nt(it));e!==p&&(n=fe())!==p?(93===t.charCodeAt(mt)?(u=st,mt++):(u=p,0===Et&&Nt(lt)),u!==p?(xt=r,r=e=bt(n)):(mt=r,r=p)):(mt=r,r=p);return r}(),e!==p&&(xt=r,e=A(e));r=e,r===p&&(r=mt,(e=fe())!==p&&(xt=r,e=C(e)),(r=e)===p&&(r=mt,(e=zt())!==p&&(xt=r,e=b(e)),r=e));return r}(),u!==p){for(o=[],(a=Rt())===p&&(a=Ut());a!==p;)o.push(a),(a=Rt())===p&&(a=Ut());o!==p?(a=mt,(i=It())!==p&&(c=Zt())!==p?a=i=[i,c]:(mt=a,a=p),a===p&&(a=null),a!==p?n=u=[u,o,a]:(mt=n,n=p)):(mt=n,n=p)}else mt=n,n=p;n===p&&(n=null),n!==p?(xt=r,r=e=g()):(mt=r,r=p)}else mt=r,r=p;return r}function It(){var r;return Et++,10===t.charCodeAt(mt)?(r=m,mt++):(r=p,0===Et&&Nt(x)),r===p&&(t.substr(mt,2)===S?(r=S,mt+=2):(r=p,0===Et&&Nt(F))),Et--,r===p&&0===Et&&Nt(y),r}function Rt(){var r;return Et++,E.test(t.charAt(mt))?(r=t.charAt(mt),mt++):(r=p,0===Et&&Nt(T)),Et--,r===p&&0===Et&&Nt(w),r}function Ut(){var r,e,n,u,o,a;if(Et++,r=mt,35===t.charCodeAt(mt)?(e=j,mt++):(e=p,0===Et&&Nt(H)),e!==p){for(n=[],u=mt,o=mt,Et++,a=It(),Et--,a===p?o=void 0:(mt=o,o=p),o!==p?(t.length>mt?(a=t.charAt(mt),mt++):(a=p,0===Et&&Nt(M)),a!==p?u=o=[o,a]:(mt=u,u=p)):(mt=u,u=p);u!==p;)n.push(u),u=mt,o=mt,Et++,a=It(),Et--,a===p?o=void 0:(mt=o,o=p),o!==p?(t.length>mt?(a=t.charAt(mt),mt++):(a=p,0===Et&&Nt(M)),a!==p?u=o=[o,a]:(mt=u,u=p)):(mt=u,u=p);n!==p?r=e=[e,n]:(mt=r,r=p)}else mt=r,r=p;return Et--,r===p&&(e=p,0===Et&&Nt(D)),r}function zt(){var r,e,n,u,o,a;if(r=mt,(e=Qt())!==p){for(n=[],u=Rt();u!==p;)n.push(u),u=Rt();if(n!==p)if(61===t.charCodeAt(mt)?(u=O,mt++):(u=p,0===Et&&Nt(_)),u!==p){for(o=[],a=Rt();a!==p;)o.push(a),a=Rt();o!==p&&(a=Vt())!==p?(xt=r,r=e=N(e,a)):(mt=r,r=p)}else mt=r,r=p;else mt=r,r=p}else mt=r,r=p;return r}function Qt(){var r;return(r=function(){var r,t,e;if(r=mt,t=[],(e=Yt())!==p)for(;e!==p;)t.push(e),e=Yt();else t=p;t!==p&&(xt=r,t=Z());return r=t,r}())===p&&(r=function(){var r,t,e;if(r=mt,kt()!==p){if(t=[],(e=Wt())!==p)for(;e!==p;)t.push(e),e=Wt();else t=p;t!==p&&(e=kt())!==p?(xt=r,r=z(t)):(mt=r,r=p)}else mt=r,r=p;return r}()),r}function Yt(){var r;return Et++,R.test(t.charAt(mt))?(r=t.charAt(mt),mt++):(r=p,0===Et&&Nt(U)),Et--,r===p&&0===Et&&Nt(I),r}function kt(){var r;return Et++,34===t.charCodeAt(mt)?(r=Y,mt++):(r=p,0===Et&&Nt(k)),Et--,r===p&&0===Et&&Nt(Q),r}function Bt(){var r;return Et++,39===t.charCodeAt(mt)?(r=J,mt++):(r=p,0===Et&&Nt(P)),Et--,r===p&&0===Et&&Nt(B),r}function Jt(){var r;return Et++,t.substr(mt,3)===W?(r=W,mt+=3):(r=p,0===Et&&Nt(q)),Et--,r===p&&0===Et&&Nt(V),r}function Pt(){var r;return Et++,t.substr(mt,3)===K?(r=K,mt+=3):(r=p,0===Et&&Nt(L)),Et--,r===p&&0===Et&&Nt(G),r}function Vt(){var r;return(r=function(){var r;r=function(){var r,t,e,n;if(r=mt,Jt()!==p)if((t=It())===p&&(t=null),t!==p){for(e=[],n=Xt();n!==p;)e.push(n),n=Xt();e!==p&&(n=Jt())!==p?(xt=r,r=X(e)):(mt=r,r=p)}else mt=r,r=p;else mt=r,r=p;return r}(),r===p&&(r=function(){var r,t,e;if(r=mt,kt()!==p){for(t=[],e=Wt();e!==p;)t.push(e),e=Wt();t!==p&&(e=kt())!==p?(xt=r,r=X(t)):(mt=r,r=p)}else mt=r,r=p;return r}())===p&&(r=function(){var r,t,e,n;if(r=mt,Pt()!==p)if((t=It())===p&&(t=null),t!==p){for(e=[],n=$t();n!==p;)e.push(n),n=$t();e!==p&&(n=Pt())!==p?(xt=r,r=X(e)):(mt=r,r=p)}else mt=r,r=p;else mt=r,r=p;return r}())===p&&(r=function(){var r,t,e;if(r=mt,Bt()!==p){for(t=[],e=Lt();e!==p;)t.push(e),e=Lt();t!==p&&(e=Bt())!==p?(xt=r,r=Ar()):(mt=r,r=p)}else mt=r,r=p;return r}());return r}())===p&&(r=function(){var r,e;r=mt,t.substr(mt,4)===Er?(e=Er,mt+=4):(e=p,0===Et&&Nt(Tr));e!==p&&(xt=r,e=Dr());r=e,r===p&&(r=mt,t.substr(mt,5)===jr?(e=jr,mt+=5):(e=p,0===Et&&Nt(Hr)),e!==p&&(xt=r,e=Mr()),r=e);return r}())===p&&(r=function(){var r,e,n,u;r=mt,e=function(){var r,e,n,u,o,a;Et++,r=mt,e=function(){var r,t,e,n,u;r=mt,(t=ue())!==p&&(e=ue())!==p&&(n=ue())!==p&&(u=ue())!==p?r=t=[t,e,n,u]:(mt=r,r=p);return r}(),e!==p?(45===t.charCodeAt(mt)?(n=Jr,mt++):(n=p,0===Et&&Nt(Pr)),n!==p?(u=function(){var r,t,e;r=mt,t=ue(),t!==p&&(e=ue())!==p?r=t=[t,e]:(mt=r,r=p);return r}(),u!==p?(45===t.charCodeAt(mt)?(o=Jr,mt++):(o=p,0===Et&&Nt(Pr)),o!==p?(a=function(){var r,t,e;r=mt,t=ue(),t!==p&&(e=ue())!==p?r=t=[t,e]:(mt=r,r=p);return r}(),a!==p?r=e=[e,n,u,o,a]:(mt=r,r=p)):(mt=r,r=p)):(mt=r,r=p)):(mt=r,r=p)):(mt=r,r=p);Et--,r===p&&(e=p,0===Et&&Nt(Lr));return r}(),e!==p?(84===t.charCodeAt(mt)?(n=qr,mt++):(n=p,0===Et&&Nt(Gr)),n!==p?(u=function(){var r,e,n;r=mt,e=function(){var r,e,n,u,o,a,i;r=mt,e=oe(),e!==p?(58===t.charCodeAt(mt)?(n=Xr,mt++):(n=p,0===Et&&Nt($r)),n!==p&&(u=ae())!==p?(58===t.charCodeAt(mt)?(o=Xr,mt++):(o=p,0===Et&&Nt($r)),o!==p?(a=function(){var r,t,e;Et++,r=mt,t=ue(),t!==p&&(e=ue())!==p?r=t=[t,e]:(mt=r,r=p);Et--,r===p&&(t=p,0===Et&&Nt(et));return r}(),a!==p?(i=function(){var r,e,n,u;r=mt,46===t.charCodeAt(mt)?(e=_r,mt++):(e=p,0===Et&&Nt(Nr));if(e!==p){if(n=[],(u=ue())!==p)for(;u!==p;)n.push(u),u=ue();else n=p;n!==p?r=e=[e,n]:(mt=r,r=p)}else mt=r,r=p;return r}(),i===p&&(i=null),i!==p?r=e=[e,n,u,o,a,i]:(mt=r,r=p)):(mt=r,r=p)):(mt=r,r=p)):(mt=r,r=p)):(mt=r,r=p);return r}(),e!==p?(n=function(){var r,e,n,u,o;Et++,90===t.charCodeAt(mt)?(r=ut,mt++):(r=p,0===Et&&Nt(ot));r===p&&(r=mt,(e=ee())!==p&&(n=oe())!==p?(58===t.charCodeAt(mt)?(u=Xr,mt++):(u=p,0===Et&&Nt($r)),u!==p&&(o=ae())!==p?r=e=[e,n,u,o]:(mt=r,r=p)):(mt=r,r=p));Et--,r===p&&(e=p,0===Et&&Nt(nt));return r}(),n!==p?r=e=[e,n]:(mt=r,r=p)):(mt=r,r=p);return r}(),u!==p?(xt=r,r=e=Kr()):(mt=r,r=p)):(mt=r,r=p)):(mt=r,r=p);return r}())===p&&(r=function(){var r,e,n,u;r=mt,te()!==p?(e=mt,n=function(){var r,e,n,u,o,a,i;r=mt,46===t.charCodeAt(mt)?(e=_r,mt++):(e=p,0===Et&&Nt(Nr));if(e!==p)if((n=ue())!==p){for(u=[],o=mt,95===t.charCodeAt(mt)?(a=Zr,mt++):(a=p,0===Et&&Nt(Ir)),a===p&&(a=null),a!==p&&(i=ue())!==p?o=a=[a,i]:(mt=o,o=p);o!==p;)u.push(o),o=mt,95===t.charCodeAt(mt)?(a=Zr,mt++):(a=p,0===Et&&Nt(Ir)),a===p&&(a=null),a!==p&&(i=ue())!==p?o=a=[a,i]:(mt=o,o=p);u!==p?r=e=[e,n,u]:(mt=r,r=p)}else mt=r,r=p;else mt=r,r=p;return r}(),n!==p?((u=re())===p&&(u=null),u!==p?e=n=[n,u]:(mt=e,e=p)):(mt=e,e=p),e===p&&(e=re()),e!==p?(xt=r,r=Or()):(mt=r,r=p)):(mt=r,r=p);return r}())===p&&(r=te())===p&&(r=function(){var r,e,n,u,o,a,i,c,f,s;r=mt,91===t.charCodeAt(mt)?(e=at,mt++):(e=p,0===Et&&Nt(it));if(e!==p){for(n=[],u=ce();u!==p;)n.push(u),u=ce();if(n!==p){if(u=mt,(o=ie())!==p){for(a=[],i=ce();i!==p;)a.push(i),i=ce();if(a!==p){if(i=mt,44===t.charCodeAt(mt)?(c=ct,mt++):(c=p,0===Et&&Nt(ft)),c!==p){for(f=[],s=ce();s!==p;)f.push(s),s=ce();f!==p?i=c=[c,f]:(mt=i,i=p)}else mt=i,i=p;i===p&&(i=null),i!==p?u=o=[o,a,i]:(mt=u,u=p)}else mt=u,u=p}else mt=u,u=p;u===p&&(u=null),u!==p?(93===t.charCodeAt(mt)?(o=st,mt++):(o=p,0===Et&&Nt(lt)),o!==p?(xt=r,r=e=ht(u)):(mt=r,r=p)):(mt=r,r=p)}else mt=r,r=p}else mt=r,r=p;return r}())===p&&(r=function(){var r,e,n,u,o,a,i,c,f,s,l;r=mt,123===t.charCodeAt(mt)?(e=vt,mt++):(e=p,0===Et&&Nt(dt));if(e!==p){for(n=[],u=Rt();u!==p;)n.push(u),u=Rt();if(n!==p){if(u=mt,(o=zt())!==p){for(a=[],i=mt,c=[],f=Rt();f!==p;)c.push(f),f=Rt();if(c!==p)if(44===t.charCodeAt(mt)?(f=ct,mt++):(f=p,0===Et&&Nt(ft)),f!==p){for(s=[],l=Rt();l!==p;)s.push(l),l=Rt();s!==p&&(l=zt())!==p?i=c=[c,f,s,l]:(mt=i,i=p)}else mt=i,i=p;else mt=i,i=p;for(;i!==p;){for(a.push(i),i=mt,c=[],f=Rt();f!==p;)c.push(f),f=Rt();if(c!==p)if(44===t.charCodeAt(mt)?(f=ct,mt++):(f=p,0===Et&&Nt(ft)),f!==p){for(s=[],l=Rt();l!==p;)s.push(l),l=Rt();s!==p&&(l=zt())!==p?i=c=[c,f,s,l]:(mt=i,i=p)}else mt=i,i=p;else mt=i,i=p}if(a!==p){for(i=[],c=Rt();c!==p;)i.push(c),c=Rt();i!==p?u=o=[o,a,i]:(mt=u,u=p)}else mt=u,u=p}else mt=u,u=p;u===p&&(u=null),u!==p?(125===t.charCodeAt(mt)?(o=gt,mt++):(o=p,0===Et&&Nt(At)),o!==p?(xt=r,r=e=Ct(u)):(mt=r,r=p)):(mt=r,r=p)}else mt=r,r=p}else mt=r,r=p;return r}()),r}function Wt(){var r;return(r=function(){var r,e,n;Et++,r=mt,e=mt,Et++,n=It(),Et--,n===p?e=void 0:(mt=e,e=p);e!==p?(rr.test(t.charAt(mt))?(n=t.charAt(mt),mt++):(n=p,0===Et&&Nt(tr)),n!==p?(xt=r,r=e=Z()):(mt=r,r=p)):(mt=r,r=p);Et--,r===p&&(e=p,0===Et&&Nt($));return r}())===p&&(r=qt()),r}function qt(){var r,e,n,u;return r=mt,Gt()!==p?(e=function(){var r;Et++,cr.test(t.charAt(mt))?(r=t.charAt(mt),mt++):(r=p,0===Et&&Nt(fr));Et--,r===p&&0===Et&&Nt(ir);return r}(),e===p&&(e=kt())===p&&(e=Gt())===p&&(e=mt,117===t.charCodeAt(mt)?(n=er,mt++):(n=p,0===Et&&Nt(nr)),n!==p?(u=function(){var r,t,e,n,u;Et++,r=mt,t=Kt(),t!==p&&(e=Kt())!==p&&(n=Kt())!==p&&(u=Kt())!==p?r=t=[t,e,n,u]:(mt=r,r=p);Et--,r===p&&(t=p,0===Et&&Nt(pr));return r}(),u!==p?e=n=[n,u]:(mt=e,e=p)):(mt=e,e=p),e===p&&(e=mt,85===t.charCodeAt(mt)?(n=ur,mt++):(n=p,0===Et&&Nt(or)),n!==p?(u=function(){var r,t,e,n,u,o,a,i,c;Et++,r=mt,t=Kt(),t!==p&&(e=Kt())!==p&&(n=Kt())!==p&&(u=Kt())!==p&&(o=Kt())!==p&&(a=Kt())!==p&&(i=Kt())!==p&&(c=Kt())!==p?r=t=[t,e,n,u,o,a,i,c]:(mt=r,r=p);Et--,r===p&&(t=p,0===Et&&Nt(vr));return r}(),u!==p?e=n=[n,u]:(mt=e,e=p)):(mt=e,e=p))),e!==p?(xt=r,r=ar()):(mt=r,r=p)):(mt=r,r=p),r}function Gt(){var r;return Et++,92===t.charCodeAt(mt)?(r=lr,mt++):(r=p,0===Et&&Nt(hr)),Et--,r===p&&0===Et&&Nt(sr),r}function Kt(){var r;return dr.test(t.charAt(mt))?(r=t.charAt(mt),mt++):(r=p,0===Et&&Nt(gr)),r}function Lt(){var r,e,n;return Et++,r=mt,e=mt,Et++,n=It(),Et--,n===p?e=void 0:(mt=e,e=p),e!==p?(Cr.test(t.charAt(mt))?(n=t.charAt(mt),mt++):(n=p,0===Et&&Nt(br)),n!==p?r=e=[e,n]:(mt=r,r=p)):(mt=r,r=p),Et--,r===p&&(e=p,0===Et&&Nt($)),r}function Xt(){var r,e,n;if(r=function(){var r,e,n;r=mt,e=mt,Et++,n=Jt(),Et--,n===p?e=void 0:(mt=e,e=p);e!==p?(n=function(){var r,e,n;Et++,r=mt,e=mt,Et++,n=It(),Et--,n===p?e=void 0:(mt=e,e=p);e!==p?(mr.test(t.charAt(mt))?(n=t.charAt(mt),mt++):(n=p,0===Et&&Nt(xr)),n!==p?r=e=[e,n]:(mt=r,r=p)):(mt=r,r=p);Et--,r===p&&(e=p,0===Et&&Nt($));return r}(),n!==p?(xt=r,r=e=Z()):(mt=r,r=p)):(mt=r,r=p);r===p&&(r=qt());return r}(),r===p){if(r=mt,Gt()!==p)if(It()!==p){for(e=[],(n=Rt())===p&&(n=It());n!==p;)e.push(n),(n=Rt())===p&&(n=It());e!==p?(xt=r,r=yr()):(mt=r,r=p)}else mt=r,r=p;else mt=r,r=p;r===p&&(r=It())}return r}function $t(){var r,e,n;return r=mt,e=mt,Et++,t.substr(mt,3)===K?(n=K,mt+=3):(n=p,0===Et&&Nt(L)),Et--,n===p?e=void 0:(mt=e,e=p),e!==p?(n=function(){var r,e,n;Et++,r=mt,e=mt,Et++,n=It(),Et--,n===p?e=void 0:(mt=e,e=p);e!==p?(Fr.test(t.charAt(mt))?(n=t.charAt(mt),mt++):(n=p,0===Et&&Nt(wr)),n!==p?r=e=[e,n]:(mt=r,r=p)):(mt=r,r=p);Et--,r===p&&(e=p,0===Et&&Nt(Sr));return r}(),n!==p?(xt=r,r=e=Z()):(mt=r,r=p)):(mt=r,r=p),r===p&&(r=It()),r}function re(){var r,e,n,u;return r=mt,101===t.charCodeAt(mt)?(e=Rr,mt++):(e=p,0===Et&&Nt(Ur)),e===p&&(69===t.charCodeAt(mt)?(e=zr,mt++):(e=p,0===Et&&Nt(Qr))),e!==p?((n=ee())===p&&(n=null),n!==p&&(u=ne())!==p?r=e=[e,n,u]:(mt=r,r=p)):(mt=r,r=p),r}function te(){var r,t;return r=mt,(t=ee())===p&&(t=null),t!==p&&ne()!==p?(xt=r,r=t=Yr()):(mt=r,r=p),r}function ee(){var r;return 43===t.charCodeAt(mt)?(r=kr,mt++):(r=p,0===Et&&Nt(Br)),r===p&&(45===t.charCodeAt(mt)?(r=Jr,mt++):(r=p,0===Et&&Nt(Pr))),r}function ne(){var r,e,n,u,o,a;if(r=mt,(e=ue())!==p){for(n=[],u=mt,95===t.charCodeAt(mt)?(o=Zr,mt++):(o=p,0===Et&&Nt(Ir)),o===p&&(o=null),o!==p&&(a=ue())!==p?u=o=[o,a]:(mt=u,u=p);u!==p;)n.push(u),u=mt,95===t.charCodeAt(mt)?(o=Zr,mt++):(o=p,0===Et&&Nt(Ir)),o===p&&(o=null),o!==p&&(a=ue())!==p?u=o=[o,a]:(mt=u,u=p);n!==p?r=e=[e,n]:(mt=r,r=p)}else mt=r,r=p;return r}function ue(){var r;return Vr.test(t.charAt(mt))?(r=t.charAt(mt),mt++):(r=p,0===Et&&Nt(Wr)),r}function oe(){var r,t,e;return Et++,r=mt,(t=ue())!==p&&(e=ue())!==p?r=t=[t,e]:(mt=r,r=p),Et--,r===p&&(t=p,0===Et&&Nt(rt)),r}function ae(){var r,t,e;return Et++,r=mt,(t=ue())!==p&&(e=ue())!==p?r=t=[t,e]:(mt=r,r=p),Et--,r===p&&(t=p,0===Et&&Nt(tt)),r}function ie(){var r,e,n,u,o,a,i;if(r=mt,(e=Vt())!==p){for(n=mt,u=[],o=ce();o!==p;)u.push(o),o=ce();if(u!==p)if(44===t.charCodeAt(mt)?(o=ct,mt++):(o=p,0===Et&&Nt(ft)),o!==p){for(a=[],i=ce();i!==p;)a.push(i),i=ce();a!==p&&(i=ie())!==p?n=u=[u,o,a,i]:(mt=n,n=p)}else mt=n,n=p;else mt=n,n=p;n===p&&(n=null),n!==p?(xt=r,r=e=pt(e,n)):(mt=r,r=p)}else mt=r,r=p;return r}function ce(){var r;return(r=Rt())===p&&(r=It())===p&&(r=Ut()),r}function fe(){var r,e,n,u,o,a,i,c,f,s;if(r=mt,91===t.charCodeAt(mt)?(e=at,mt++):(e=p,0===Et&&Nt(it)),e!==p){for(n=[],u=Rt();u!==p;)n.push(u),u=Rt();if(n!==p)if((u=Qt())!==p){for(o=[],a=mt,i=[],c=Rt();c!==p;)i.push(c),c=Rt();if(i!==p)if(46===t.charCodeAt(mt)?(c=_r,mt++):(c=p,0===Et&&Nt(Nr)),c!==p){for(f=[],s=Rt();s!==p;)f.push(s),s=Rt();f!==p&&(s=Qt())!==p?a=i=[i,c,f,s]:(mt=a,a=p)}else mt=a,a=p;else mt=a,a=p;for(;a!==p;){for(o.push(a),a=mt,i=[],c=Rt();c!==p;)i.push(c),c=Rt();if(i!==p)if(46===t.charCodeAt(mt)?(c=_r,mt++):(c=p,0===Et&&Nt(Nr)),c!==p){for(f=[],s=Rt();s!==p;)f.push(s),s=Rt();f!==p&&(s=Qt())!==p?a=i=[i,c,f,s]:(mt=a,a=p)}else mt=a,a=p;else mt=a,a=p}if(o!==p){for(a=[],i=Rt();i!==p;)a.push(i),i=Rt();a!==p?(93===t.charCodeAt(mt)?(i=st,mt++):(i=p,0===Et&&Nt(lt)),i!==p?(xt=r,r=e=yt(u,o)):(mt=r,r=p)):(mt=r,r=p)}else mt=r,r=p}else mt=r,r=p;else mt=r,r=p}else mt=r,r=p;return r}u=function(r){return"Value for "+r+" should not be redefined in the same table."},o=Number.isFinite||function(r){return"number"==typeof r&&isFinite(r)},a=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)},i=function(r,t){return Object.prototype.hasOwnProperty.call(r,t)},c="object"==typeof JSON&&JSON?JSON.stringify:function(r){return'"'+String(r).replace(/[\x00-\x1F"\\]/g,(function(r){switch(r){case'"':case"\\":return"\\"+r;case"\t":return"\\t";case"\n":return"\\n";case"\r":return"\\r";case"\b":return"\\b";case"\f":return"\\f";default:var t=r.charCodeAt(0).toString(16);return"\\u"+"0000".substr(t.length)+t}}))+'"'},f=function(r){switch(r){case'"':case"\\":return r;case"t":return"\t";case"n":return"\n";case"r":return"\r";case"b":return"\b";case"f":return"\f";default:Dt(c(r)+" cannot be escaped.")}},s=function(r){if((!o(r)||r<0||r>1114111)&&Dt("U+"+r.toString(16)+" is not a valid Unicode code point."),String.fromCodePoint)return String.fromCodePoint(r);var t="";return r>65535&&(r-=65536,t+=String.fromCharCode(r>>>10&1023|55296),r=56320|1023&r),t+=String.fromCharCode(r)},l=function(r,t){i(r,t)&&Dt(u(c(t)))},h=function(r,t,e){for(var n="",o=0,f=e.length;o{try{return t(n)}catch(t){throw t instanceof r?(t.line=t.location.start.line,t.column=t.location.start.column,t.offset=t.location.start.offset,new e(t.message,t.location.start)):t}};export{e as SyntaxError,n as parse}; +//# sourceMappingURL=toml.js.map diff --git a/core/src/3rd-party/xterm-readline.js b/core/src/3rd-party/xterm-readline.js new file mode 100644 index 00000000000..226009c52e0 --- /dev/null +++ b/core/src/3rd-party/xterm-readline.js @@ -0,0 +1,7 @@ +/** + * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0. + * Original file: /npm/xterm-readline@1.1.2/lib/readline.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +import t from"string-width";var e,s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i={},r={};Object.defineProperty(r,"__esModule",{value:!0}),r.InputType=void 0,r.parseInput=function(t){return Array.from(function*(t){let s=[];const i=t[Symbol.iterator]();for(let t=i.next();!t.done;t=i.next()){const r=t.value;if(r.length>1){s.push(r);continue}const o=r.charCodeAt(0);if(s.length>0&&(o<32||127===o)&&(yield{inputType:e.Text,data:s},s=[]),27!==o)if(o<32||127===o){let t=e.UnsupportedControlChar;switch(o){case 1:t=e.CtrlA;break;case 3:t=e.CtrlC;break;case 4:t=e.CtrlD;break;case 5:t=e.CtrlE;break;case 11:t=e.CtrlK;break;case 17:t=e.CtrlQ;break;case 19:t=e.CtrlS;break;case 21:t=e.CtrlU;break;case 13:t=e.Enter;break;case 127:t=e.Backspace;break;case 12:t=e.CtrlL}yield{inputType:t,data:[r]}}else s.push(r);else{const t=i.next();if(t.done){s.push("");continue}let r=e.UnsupportedEscape;if("["!==t.value){if("\r"===t.value)r=e.AltEnter;yield{inputType:r,data:["",t.value]};continue}const o=i.next();if(o.done)continue;if(o.value>="0"&&o.value<="9"){let t=o.value;const s=i.next();if(s.done)return;if(s.value>="0"&&s.value<="9")t+=s.value;else if("~"!==s.value)continue;if("3"===t)r=e.Delete;yield{inputType:r,data:["","[",t,"~"]};continue}switch(o.value){case"A":r=e.ArrowUp;break;case"B":r=e.ArrowDown;break;case"C":r=e.ArrowRight;break;case"D":r=e.ArrowLeft;break;case"F":r=e.End;break;case"H":r=e.Home;break;case"\r":r=e.AltEnter}yield{inputType:r,data:["","[",o.value]}}}s.length>0&&(yield{inputType:e.Text,data:s})}(t))},function(t){t[t.Text=0]="Text",t[t.AltEnter=1]="AltEnter",t[t.ArrowUp=2]="ArrowUp",t[t.ArrowDown=3]="ArrowDown",t[t.ArrowLeft=4]="ArrowLeft",t[t.ArrowRight=5]="ArrowRight",t[t.Delete=6]="Delete",t[t.Backspace=7]="Backspace",t[t.CtrlA=8]="CtrlA",t[t.CtrlC=9]="CtrlC",t[t.CtrlD=10]="CtrlD",t[t.CtrlE=11]="CtrlE",t[t.CtrlK=12]="CtrlK",t[t.CtrlL=13]="CtrlL",t[t.CtrlQ=14]="CtrlQ",t[t.CtrlS=15]="CtrlS",t[t.CtrlU=16]="CtrlU",t[t.End=17]="End",t[t.Enter=18]="Enter",t[t.Home=19]="Home",t[t.ShiftEnter=20]="ShiftEnter",t[t.UnsupportedControlChar=21]="UnsupportedControlChar",t[t.UnsupportedEscape=22]="UnsupportedEscape"}(e||(r.InputType=e={}));var o={},h={};Object.defineProperty(h,"__esModule",{value:!0}),h.LineBuffer=void 0;h.LineBuffer=class{constructor(){this.buf="",this.pos=0}buffer(){return this.buf}pos_buffer(){return this.buf.slice(0,this.pos)}length(){return this.buf.length}char_length(){return[...this.buf].length}update(t,e){this.buf=t,this.pos=e}insert(t){const e=t.length,s=this.pos===this.buf.length;return this.buf=s?this.buf+t:this.buf.slice(0,this.pos)+t+this.buf.slice(this.pos),this.pos+=e,s}moveBack(t){const e=this.prevPos(t);return void 0!==e&&(this.pos=e,!0)}moveForward(t){const e=this.nextPos(t);return void 0!==e&&(this.pos=e,!0)}moveHome(){const t=this.startOfLine();return this.pos>t&&(this.pos=t,!0)}moveEnd(){const t=this.endOfLine();return this.pos!==t&&(this.pos=t,!0)}startOfLine(){const t=this.buf.slice(0,this.pos).lastIndexOf("\n");return-1!==t?t+1:0}endOfLine(){const t=this.buf.slice(this.pos).indexOf("\n");return-1!==t?this.pos+t:this.buf.length}moveLineUp(t){const e=this.buf.slice(0,this.pos).lastIndexOf("\n");if(-1===e)return!1;const s=[...this.buf.slice(e+1,this.pos)].length;let i=this.buf.slice(0,e).lastIndexOf("\n");-1===i?i=0:i+=1;let r=e;for(let e=1;e0&&(h=o.map((t=>t.length)).reduce(((t,e)=>t+e),0),h=i+h),this.pos=h,!0}moveLineDown(t){const e=this.buf.slice(this.pos).indexOf("\n");if(-1===e)return!1;let s=this.buf.slice(0,this.pos).lastIndexOf("\n");-1===s?s=0:s+=1;const i=[...this.buf.slice(s,this.pos)].length;let r=this.pos+e+1,o=this.buf.slice(r).indexOf("\n");o=-1===o?this.buf.length:r+o;for(let e=1;et.length)).reduce(((t,e)=>t+e),0)+r:this.pos=o,!0}set_pos(t){this.pos=t}prevPos(t){if(0===this.pos)return;const e=this.buf.slice(0,this.pos);return this.pos-[...e].slice(-t).map((t=>t.length)).reduce(((t,e)=>t+e),0)}nextPos(t){if(this.pos===this.buf.length)return;const e=this.buf.slice(this.pos);return this.pos+[...e].slice(0,t).map((t=>t.length)).reduce(((t,e)=>t+e),0)}backspace(t){const e=this.prevPos(t);return void 0!==e&&(this.buf=this.buf.slice(0,e)+this.buf.slice(this.pos),this.pos=e,!0)}delete(t){const e=this.nextPos(t);return void 0!==e&&(this.buf=this.buf.slice(0,this.pos)+this.buf.slice(e),!0)}deleteEndOfLine(){if(0==this.buf.length||this.pos==this.buf.length)return!1;const t=this.pos,e=this.endOfLine();return t==e?this.delete(1):this.buf=this.buf.slice(0,t)+this.buf.slice(e),!0}};var n=s&&s.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(o,"__esModule",{value:!0}),o.State=o.Layout=o.Position=void 0;const a=h,l=n(t);class u{constructor(t,e){this.row=void 0!==t?t:0,this.col=void 0!==e?e:0}}o.Position=u;class c{constructor(t){this.promptSize=t,this.cursor=new u,this.end=new u}}o.Layout=c;o.State=class{constructor(t,e,s,i){this.line=new a.LineBuffer,this.highlighting=!1,this.prompt=t,this.tty=e,this.highlighter=s,this.history=i,this.promptSize=e.calculatePosition(t,new u),this.layout=new c(this.promptSize)}buffer(){return this.line.buffer()}shouldHighlight(){return this.highlighter.highlightChar(this.line.buf,this.line.pos)?(this.highlighting=!0,!0):!!this.highlighting&&(this.highlighting=!1,!0)}clearScreen(){this.tty.clearScreen(),this.layout.cursor=new u,this.layout.end=new u,this.refresh()}editInsert(t){const e=this.line.insert(t),s=t.includes("\n");if(e&&!s){const e=(0,l.default)(t);e>0&&this.layout.cursor.col+e0)return;const t=this.history.prev();void 0!==t&&this.update(t)}nextHistory(){if(-1===this.history.cursor)return;const t=this.history.next();void 0!==t?this.update(t):this.update("")}moveCursor(){const t=this.tty.calculatePosition(this.line.pos_buffer(),this.promptSize);t!==this.layout.cursor&&(this.shouldHighlight()?this.refresh():(this.tty.moveCursor(this.layout.cursor,t),this.layout.promptSize=Object.assign({},this.promptSize),this.layout.cursor=Object.assign({},t)))}};var p={};Object.defineProperty(p,"__esModule",{value:!0}),p.History=void 0;p.History=class{constructor(t){this.entries=[],this.cursor=-1,this.maxEntries=t}saveToLocalStorage(){const t=null===window||void 0===window?void 0:window.localStorage;void 0!==t&&t.setItem("history",JSON.stringify(this.entries))}restoreFromLocalStorage(){const t=null===window||void 0===window?void 0:window.localStorage;if(void 0!==t){const e=t.getItem("history");if(null==e)return;try{const s=JSON.parse(e);Array.isArray(s)&&void 0===s.find((t=>"string"!=typeof t))?this.entries=s:(this.entries=[],t.setItem("history","[]"))}catch(e){this.entries=[],t.setItem("history","[]")}}}append(t){this.resetCursor(),this.entries.includes(t)?(this.entries.splice(this.entries.indexOf(t),1),this.entries.unshift(t)):this.entries.unshift(t),this.entries.length>this.maxEntries&&this.entries.pop(),this.saveToLocalStorage()}resetCursor(){this.cursor=-1}next(){if(-1!==this.cursor)return this.cursor-=1,this.entries[this.cursor]}prev(){if(!(this.cursor+1>=this.entries.length))return this.cursor+=1,this.entries[this.cursor]}};var d={},f=s&&s.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(d,"__esModule",{value:!0}),d.Tty=void 0;const y=f(t);d.Tty=class{constructor(t,e,s,i){this.tabWidth=s,this.col=t,this.row=e,this.out=i}write(t){return this.out.write(t)}print(t){return this.out.print(t)}println(t){return this.out.println(t)}clearScreen(){this.out.write("")}calculatePosition(t,e){const s=Object.assign({},e);let i=0;return[...t].forEach((t=>{if("\n"===t)return s.row+=1,void(s.col=0);let e=0;if("\t"===t)e=this.tabWidth-s.col%this.tabWidth;else{let s;[s,i]=function(t,e){return 1===e?"["===t?[0,2]:[0,0]:2===e?";"===t||t[0]>="0"&&t[0]<="9"?[0,e]:[0,0]:""===t?[0,1]:"\n"===t?[0,e]:[(0,y.default)(t),e]}(t,i),e=s}s.col+=e,s.col>this.col&&(s.row+=1,s.col=e)})),s.col===this.col&&(s.col=0,s.row+=1),s}computeLayout(t,e){const s=Object.assign({},t),i=e.pos,r=this.calculatePosition(e.buf.slice(0,e.pos),t);return{promptSize:s,cursor:r,end:i===e.buf.length?Object.assign({},r):this.calculatePosition(e.buf.slice(i),r)}}refreshLine(t,e,s,i,r){const o=i.cursor,h=i.end;this.clearOldRows(s),this.write(r.highlightPrompt(t)),this.write(r.highlight(e.buf,e.pos)),0===h.col&&h.row>0&&"\n"!==e.buf[e.buf.length-1]&&this.write("\n");const n=h.row-o.row;n>0&&this.write(`[${n}A`),o.col>0?this.write(`\r[${o.col}C`):this.write("\r")}clearOldRows(t){const e=t.cursor.row,s=t.end.row,i=Math.max(s-e,0);i>0&&this.write(`[${i}B`);for(let t=0;tt.row){const s=e.row-t.row;1===s?this.write(""):this.write(`[${s}B`)}else if(e.rowt.col){const s=e.col-t.col;1===s?this.write(""):this.write(`[${s}C`)}else if(e.col",this.tty(),this.highlighter,this.history),this.checkHandler=()=>!0,this.ctrlCHandler=()=>{},this.pauseHandler=t=>{},this.history.restoreFromLocalStorage()}activate(t){this.term=t,this.term.onData(this.readData.bind(this)),this.term.attachCustomKeyEventHandler(this.handleKeyEvent.bind(this))}dispose(){this.disposables.forEach((t=>t.dispose()))}appendHistory(t){this.history.append(t)}setHighlighter(t){this.highlighter=t}setCheckHandler(t){this.checkHandler=t}setCtrlCHandler(t){this.ctrlCHandler=t}setPauseHandler(t){this.pauseHandler=t}writeReady(){return!this.highWater}write(t){const e=(t="\n"===t?"\r\n":(t=t.replace(/^\n/,"\r\n")).replace(/([^\r])\n/g,"$1\r\n")).length;this.watermark+=e,this.watermark>this.highWatermark&&(this.highWater=!0),this.term&&this.term.write(t,(()=>{this.watermark=Math.max(this.watermark-e,0),this.highWater&&this.watermark{void 0!==this.term?(this.state=new g.State(t,this.tty(),this.highlighter,this.history),this.state.refresh(),this.activeRead={prompt:t,resolve:e,reject:s}):s("addon is not active")}))}handleKeyEvent(t){return"Enter"!==t.key||!t.shiftKey||("keydown"===t.type&&this.readKey({inputType:b.InputType.ShiftEnter,data:["\r"]}),!1)}readData(t){const e=(0,b.parseInput)(t);e.length>1||e[0].inputType===b.InputType.Text&&e[0].data.length>1?this.readPaste(e):this.readKey(e[0])}readPaste(t){const e=t.map((t=>t.inputType===b.InputType.Enter?{inputType:b.InputType.Text,data:["\n"]}:t));for(const t of e)t.inputType===b.InputType.Text?this.state.editInsert(t.data.join("")):this.readKey(t)}readKey(t){var e,s,i;if(void 0!==this.activeRead)switch(t.inputType){case b.InputType.Text:this.state.editInsert(t.data.join(""));break;case b.InputType.AltEnter:case b.InputType.ShiftEnter:this.state.editInsert("\n");break;case b.InputType.Enter:this.checkHandler(this.state.buffer())?(this.state.moveCursorToEnd(),null===(e=this.term)||void 0===e||e.write("\r\n"),this.history.append(this.state.buffer()),null===(s=this.activeRead)||void 0===s||s.resolve(this.state.buffer()),this.activeRead=void 0):this.state.editInsert("\n");break;case b.InputType.CtrlC:this.state.moveCursorToEnd(),null===(i=this.term)||void 0===i||i.write("^C\r\n"),this.state=new g.State(this.activeRead.prompt,this.tty(),this.highlighter,this.history),this.state.refresh();break;case b.InputType.CtrlS:this.pauseHandler(!1);break;case b.InputType.CtrlU:this.state.update("");break;case b.InputType.CtrlK:this.state.editDeleteEndOfLine();break;case b.InputType.CtrlQ:this.pauseHandler(!0);break;case b.InputType.CtrlL:this.state.clearScreen();break;case b.InputType.Home:case b.InputType.CtrlA:this.state.moveCursorHome();break;case b.InputType.End:case b.InputType.CtrlE:this.state.moveCursorEnd();break;case b.InputType.Backspace:this.state.editBackspace(1);break;case b.InputType.Delete:case b.InputType.CtrlD:this.state.editDelete(1);break;case b.InputType.ArrowLeft:this.state.moveCursorBack(1);break;case b.InputType.ArrowRight:this.state.moveCursorForward(1);break;case b.InputType.ArrowUp:this.state.moveCursorUp(1);break;case b.InputType.ArrowDown:this.state.moveCursorDown(1);case b.InputType.UnsupportedControlChar:case b.InputType.UnsupportedEscape:}else switch(t.inputType){case b.InputType.CtrlC:this.ctrlCHandler();break;case b.InputType.CtrlL:this.write("")}}};var k=i.__esModule;export{v as Readline,k as __esModule,i as default}; diff --git a/core/src/3rd-party/xterm.css b/core/src/3rd-party/xterm.css new file mode 100644 index 00000000000..bfff09b1257 --- /dev/null +++ b/core/src/3rd-party/xterm.css @@ -0,0 +1,7 @@ +/** + * Minified by jsDelivr using clean-css v5.3.2. + * Original file: /npm/@xterm/xterm@5.5.0/css/xterm.css + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:0}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm .xterm-cursor-pointer,.xterm.xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) ::selection{color:transparent}.xterm .xterm-accessibility-tree{user-select:text;white-space:pre}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative} diff --git a/core/src/3rd-party/xterm.js b/core/src/3rd-party/xterm.js new file mode 100644 index 00000000000..7d1b7706ff4 --- /dev/null +++ b/core/src/3rd-party/xterm.js @@ -0,0 +1,7 @@ +/** + * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0. + * Original file: /npm/@xterm/xterm@5.5.0/lib/xterm.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +var e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function t(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}var s=t,r=i;function n(e){if(s===setTimeout)return setTimeout(e,0);if((s===t||!s)&&setTimeout)return s=setTimeout,setTimeout(e,0);try{return s(e,0)}catch(t){try{return s.call(null,e,0)}catch(t){return s.call(this,e,0)}}}"function"==typeof e.setTimeout&&(s=setTimeout),"function"==typeof e.clearTimeout&&(r=clearTimeout);var o,a=[],h=!1,c=-1;function l(){h&&o&&(h=!1,o.length?a=o.concat(a):c=-1,a.length&&d())}function d(){if(!h){var e=n(l);h=!0;for(var t=a.length;t;){for(o=a,a=[];++c1)for(var i=1;i(()=>{var e={4567:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.AccessibilityManager=void 0;const n=i(9042),o=i(9924),a=i(844),h=i(4725),c=i(2585),l=i(3656);let d=t.AccessibilityManager=class extends a.Disposable{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let e=0;ethis._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new o.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((e=>this._handleResize(e.rows)))),this.register(this._terminal.onRender((e=>this._refreshRows(e.start,e.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((e=>this._handleChar(e)))),this.register(this._terminal.onLineFeed((()=>this._handleChar("\n")))),this.register(this._terminal.onA11yTab((e=>this._handleTab(e)))),this.register(this._terminal.onKey((e=>this._handleKey(e.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,l.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,a.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=n.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){const i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){const e=i.lines.get(i.ydisp+r),t=[],n=e?.translateToString(!0,void 0,void 0,t)||"",o=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(0===n.length?(a.innerText=" ",this._rowColumns.set(a,[0,1])):(a.textContent=n,this._rowColumns.set(a,t)),a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",s))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){const i=e.target,s=this._rowElements[0===t?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")===(0===t?"1":`${this._terminal.buffer.lines.length}`))return;if(e.relatedTarget!==s)return;let r,n;if(0===t?(r=i,n=this._rowElements.pop(),this._rowContainer.removeChild(n)):(r=this._rowElements.shift(),n=i,this._rowContainer.removeChild(r)),r.removeEventListener("focus",this._topBoundaryFocusListener),n.removeEventListener("focus",this._bottomBoundaryFocusListener),0===t){const e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement("afterbegin",e)}else{const e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===t?-1:1),this._rowElements[0===t?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(0===this._rowElements.length)return;const e=document.getSelection();if(!e)return;if(e.isCollapsed)return void(this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection());if(!e.anchorNode||!e.focusNode)return void console.error("anchorNode and/or focusNode are null");let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;const s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:s.textContent?.length??0}),!this._rowContainer.contains(i.node))return;const r=({node:e,offset:t})=>{const i=e instanceof Text?e.parentNode:e;let s=parseInt(i?.getAttribute("aria-posinset"),10)-1;if(isNaN(s))return console.warn("row is invalid. Race condition?"),null;const r=this._rowColumns.get(i);if(!r)return console.warn("columns is null. Race condition?"),null;let n=t=this._terminal.cols&&(++s,n=0),{row:s,column:n}},n=r(t),o=r(i);if(n&&o){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;ee;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{function i(e){return e.replace(/\r?\n/g,"\r")}function s(e,t){return t?"[200~"+e+"[201~":e}function r(e,t,r,n){e=s(e=i(e),r.decPrivateModes.bracketedPasteMode&&!0!==n.rawOptions.ignoreBracketedPasteMode),r.triggerDataEvent(e,!0),t.value=""}function n(e,t,i){const s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}Object.defineProperty(t,"__esModule",{value:!0}),t.rightClickHandler=t.moveTextAreaUnderMouseCursor=t.paste=t.handlePasteEvent=t.copyHandler=t.bracketTextForPaste=t.prepareTextForTerminal=void 0,t.prepareTextForTerminal=i,t.bracketTextForPaste=s,t.copyHandler=function(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()},t.handlePasteEvent=function(e,t,i,s){e.stopPropagation(),e.clipboardData&&r(e.clipboardData.getData("text/plain"),t,i,s)},t.paste=r,t.moveTextAreaUnderMouseCursor=n,t.rightClickHandler=function(e,t,i,s,r){n(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}},7239:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorContrastCache=void 0;const s=i(1505);t.ColorContrastCache=class{constructor(){this._color=new s.TwoKeyMap,this._css=new s.TwoKeyMap}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},3656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDisposableDomListener=void 0,t.addDisposableDomListener=function(e,t,i,s){e.addEventListener(t,i,s);let r=!1;return{dispose:()=>{r||(r=!0,e.removeEventListener(t,i,s))}}}},3551:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Linkifier=void 0;const n=i(3656),o=i(8460),a=i(844),h=i(2585),c=i(4725);let l=t.Linkifier=class extends a.Disposable{get currentLink(){return this._currentLink}constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new o.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new o.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,a.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,a.toDisposable)((()=>{this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,n.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,n.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,n.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,n.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(e){this._lastMouseEvent=e;const t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;const i=e.composedPath();for(let e=0;e{e?.forEach((e=>{e.link.dispose&&e.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(const[s,r]of this._linkProviderService.linkProviders.entries())if(t){const t=this._activeProviderReplies?.get(s);t&&(i=this._checkLinkProviderResult(s,e,i))}else r.provideLinks(e.y,(t=>{if(this._isMouseOut)return;const r=t?.map((e=>({link:e})));this._activeProviderReplies?.set(s,r),i=this._checkLinkProviderResult(s,e,i),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)}))}_removeIntersectingLinks(e,t){const i=new Set;for(let s=0;se?this._bufferService.cols:s.link.range.end.x;for(let e=n;e<=o;e++){if(i.has(e)){r.splice(t--,1);break}i.add(e)}}}}_checkLinkProviderResult(e,t,i){if(!this._activeProviderReplies)return i;const s=this._activeProviderReplies.get(e);let r=!1;for(let t=0;tthis._linkAtPosition(e.link,t)));e&&(i=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let e=0;ethis._linkAtPosition(e.link,t)));if(s){i=!0,this._handleNewLink(s);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;const t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){this._currentLink&&this._lastMouseEvent&&(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,a.disposeArray)(this._linkCacheDisposables))}_handleNewLink(e){if(!this._lastMouseEvent)return;const t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:void 0===e.link.decorations||e.link.decorations.underline,pointerCursor:void 0===e.link.decorations||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((e=>{if(!this._currentLink)return;const t=0===e.start?0:e.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(t,i),this._lastMouseEvent)){const e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}}))))}_linkHover(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){const i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){const i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){const s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};t.Linkifier=l=s([r(1,c.IMouseService),r(2,c.IRenderService),r(3,h.IBufferService),r(4,c.ILinkProviderService)],l)},9042:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.tooMuchOutput=t.promptLabel=void 0,t.promptLabel="Terminal input",t.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkProvider=void 0;const n=i(511),o=i(2585);let a=t.OscLinkProvider=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){const i=this._bufferService.buffer.lines.get(e-1);if(!i)return void t(void 0);const s=[],r=this._optionsService.rawOptions.linkHandler,o=new n.CellData,a=i.getTrimmedLength();let c=-1,l=-1,d=!1;for(let t=0;tr?r.activate(e,t,n):h(0,t),hover:(e,t)=>r?.hover?.(e,t,n),leave:(e,t)=>r?.leave?.(e,t,n)})}d=!1,o.hasExtendedAttrs()&&o.extended.urlId?(l=t,c=o.extended.urlId):(l=-1,c=-1)}}t(s)}};function h(e,t){if(confirm(`Do you want to navigate to ${t}?\n\nWARNING: This link could potentially be dangerous`)){const e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}t.OscLinkProvider=a=s([r(0,o.IBufferService),r(1,o.IOptionsService),r(2,o.IOscLinkService)],a)},6193:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenderDebouncer=void 0,t.RenderDebouncer=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return void this._runRefreshCallbacks();const e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}}},3236:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Terminal=void 0;const s=i(3614),r=i(3656),n=i(3551),o=i(9042),a=i(3730),h=i(1680),c=i(3107),l=i(5744),d=i(2950),_=i(1296),u=i(428),f=i(4269),v=i(5114),p=i(8934),g=i(3230),m=i(9312),S=i(4725),C=i(6731),b=i(8055),w=i(8969),y=i(8460),E=i(844),k=i(6114),L=i(8437),D=i(2584),R=i(7399),x=i(5941),A=i(9074),B=i(2585),T=i(5435),M=i(4567),O=i(779);class P extends w.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(e={}){super(e),this.browser=k,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new E.MutableDisposable),this._onCursorMove=this.register(new y.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new y.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new y.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new y.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new y.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new y.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new y.EventEmitter),this._onBlur=this.register(new y.EventEmitter),this._onA11yCharEmitter=this.register(new y.EventEmitter),this._onA11yTabEmitter=this.register(new y.EventEmitter),this._onWillOpen=this.register(new y.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(A.DecorationService),this._instantiationService.setService(B.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(O.LinkProviderService),this._instantiationService.setService(S.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(a.OscLinkProvider)),this.register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this.register(this._inputHandler.onRequestRefreshRows(((e,t)=>this.refresh(e,t)))),this.register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register(this._inputHandler.onRequestWindowsOptionsReport((e=>this._reportWindowsOptions(e)))),this.register(this._inputHandler.onColor((e=>this._handleColorEvent(e)))),this.register((0,y.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,y.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,y.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,y.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize((e=>this._afterResize(e.cols,e.rows)))),this.register((0,E.toDisposable)((()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)})))}_handleColorEvent(e){if(this._themeService)for(const t of e){let e,i="";switch(t.index){case 256:e="foreground",i="10";break;case 257:e="background",i="11";break;case 258:e="cursor",i="12";break;default:e="ansi",i="4;"+t.index}switch(t.type){case 0:const s=b.color.toColorRGB("ansi"===e?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${D.C0.ESC}]${i};${(0,x.toRgbString)(s)}${D.C1_ESCAPED.ST}`);break;case 1:if("ansi"===e)this._themeService.modifyColors((e=>e.ansi[t.index]=b.channels.toColor(...t.color)));else{const i=e;this._themeService.modifyColors((e=>e[i]=b.channels.toColor(...t.color)))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(M.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(D.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(D.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;const i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,r.addDisposableDomListener)(this.element,"copy",(e=>{this.hasSelection()&&(0,s.copyHandler)(e,this._selectionService)})));const e=e=>(0,s.handlePasteEvent)(e,this.textarea,this.coreService,this.optionsService);this.register((0,r.addDisposableDomListener)(this.textarea,"paste",e)),this.register((0,r.addDisposableDomListener)(this.element,"paste",e)),k.isFirefox?this.register((0,r.addDisposableDomListener)(this.element,"mousedown",(e=>{2===e.button&&(0,s.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this.register((0,r.addDisposableDomListener)(this.element,"contextmenu",(e=>{(0,s.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),k.isLinux&&this.register((0,r.addDisposableDomListener)(this.element,"auxclick",(e=>{1===e.button&&(0,s.moveTextAreaUnderMouseCursor)(e,this.textarea,this.screenElement)})))}_bindKeys(){this.register((0,r.addDisposableDomListener)(this.textarea,"keyup",(e=>this._keyUp(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"keydown",(e=>this._keyDown(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"keypress",(e=>this._keyPress(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionstart",(()=>this._compositionHelper.compositionstart()))),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionupdate",(e=>this._compositionHelper.compositionupdate(e)))),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionend",(()=>this._compositionHelper.compositionend()))),this.register((0,r.addDisposableDomListener)(this.textarea,"input",(e=>this._inputEvent(e)),!0)),this.register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);const t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this._viewportScrollArea=this._document.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this.register((0,r.addDisposableDomListener)(this.screenElement,"mousemove",(e=>this.updateCursorStyle(e)))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement),this.textarea=this._document.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",o.promptLabel),k.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._coreBrowserService=this.register(this._instantiationService.createInstance(v.CoreBrowserService,this.textarea,e.ownerDocument.defaultView??window,this._document??"undefined"!=typeof window?window.document:null)),this._instantiationService.setService(S.ICoreBrowserService,this._coreBrowserService),this.register((0,r.addDisposableDomListener)(this.textarea,"focus",(e=>this._handleTextAreaFocus(e)))),this.register((0,r.addDisposableDomListener)(this.textarea,"blur",(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(u.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(S.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(C.ThemeService),this._instantiationService.setService(S.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(f.CharacterJoinerService),this._instantiationService.setService(S.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(g.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(S.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange((e=>this._onRender.fire(e)))),this.onResize((e=>this._renderService.resize(e.cols,e.rows))),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(d.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(p.MouseService),this._instantiationService.setService(S.IMouseService,this._mouseService),this.linkifier=this.register(this._instantiationService.createInstance(n.Linkifier,this.screenElement)),this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this.viewport=this._instantiationService.createInstance(h.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines((e=>this.scrollLines(e.amount,e.suppressScrollEvent,1))),this.register(this._inputHandler.onRequestSyncScrollBar((()=>this.viewport.syncScrollArea()))),this.register(this.viewport),this.register(this.onCursorMove((()=>{this._renderService.handleCursorMove(),this._syncTextArea()}))),this.register(this.onResize((()=>this._renderService.handleResize(this.cols,this.rows)))),this.register(this.onBlur((()=>this._renderService.handleBlur()))),this.register(this.onFocus((()=>this._renderService.handleFocus()))),this.register(this._renderService.onDimensionsChange((()=>this.viewport.syncScrollArea()))),this._selectionService=this.register(this._instantiationService.createInstance(m.SelectionService,this.element,this.screenElement,this.linkifier)),this._instantiationService.setService(S.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines((e=>this.scrollLines(e.amount,e.suppressScrollEvent)))),this.register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this.register(this._selectionService.onRequestRedraw((e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode)))),this.register(this._selectionService.onLinuxMouseSelection((e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()}))),this.register(this._onScroll.event((e=>{this.viewport.syncScrollArea(),this._selectionService.refresh()}))),this.register((0,r.addDisposableDomListener)(this._viewportElement,"scroll",(()=>this._selectionService.refresh()))),this.register(this._instantiationService.createInstance(c.BufferDecorationRenderer,this.screenElement)),this.register((0,r.addDisposableDomListener)(this.element,"mousedown",(e=>this._selectionService.handleMouseDown(e)))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(M.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",(e=>this._handleScreenReaderModeOptionChange(e)))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(l.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",(e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(l.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(_.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const e=this,t=this.element;function i(t){const i=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!i)return!1;let s,r;switch(t.overrideType||t.type){case"mousemove":r=32,void 0===t.buttons?(s=3,void 0!==t.button&&(s=t.button<3?t.button:3)):s=1&t.buttons?0:4&t.buttons?1:2&t.buttons?2:3;break;case"mouseup":r=0,s=t.button<3?t.button:3;break;case"mousedown":r=1,s=t.button<3?t.button:3;break;case"wheel":if(e._customWheelEventHandler&&!1===e._customWheelEventHandler(t))return!1;if(0===e.viewport.getLinesScrolled(t))return!1;r=t.deltaY<0?0:1,s=4;break;default:return!1}return!(void 0===r||void 0===s||s>4)&&e.coreMouseService.triggerMouseEvent({col:i.col,row:i.row,x:i.x,y:i.y,button:s,action:r,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}const s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},n={mouseup:e=>(i(e),e.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(e)),wheel:e=>(i(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&i(e)},mousemove:e=>{e.buttons||i(e)}};this.register(this.coreMouseService.onProtocolChange((e=>{e?("debug"===this.optionsService.rawOptions.logLevel&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(e)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&e?s.mousemove||(t.addEventListener("mousemove",n.mousemove),s.mousemove=n.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),16&e?s.wheel||(t.addEventListener("wheel",n.wheel,{passive:!1}),s.wheel=n.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),2&e?s.mouseup||(s.mouseup=n.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),4&e?s.mousedrag||(s.mousedrag=n.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,r.addDisposableDomListener)(t,"mousedown",(e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return i(e),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(e)}))),this.register((0,r.addDisposableDomListener)(t,"wheel",(e=>{if(!s.wheel){if(this._customWheelEventHandler&&!1===this._customWheelEventHandler(e))return!1;if(!this.buffer.hasScrollback){const t=this.viewport.getLinesScrolled(e);if(0===t)return;const i=D.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(e.deltaY<0?"A":"B");let s="";for(let e=0;e{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(e),this.cancel(e)}),{passive:!0})),this.register((0,r.addDisposableDomListener)(t,"touchmove",(e=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(e)?void 0:this.cancel(e)}),{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t,i=0){1===i?(super.scrollLines(e,t,i),this.refresh(0,this.rows-1)):this.viewport?.scrollLines(e)}paste(e){(0,s.paste)(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;const t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;t||"Dead"!==e.key&&"AltGraph"!==e.key||(this._unprocessedDeadKey=!0);const i=(0,R.evaluateKeyboardEvent)(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===i.type||2===i.type){const t=this.rows-1;return this.scrollLines(2===i.type?-t:t),this.cancel(e,!0)}return 1===i.type&&this.selectAll(),!!this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key||!!(e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&1===e.key.length&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(i.key!==D.C0.ETX&&i.key!==D.C0.CR||(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey?this.cancel(e,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(e,t){const i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return"keypress"===t.type?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(function(e){return 16===e.keyCode||17===e.keyCode||18===e.keyCode}(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled)return!1;if(this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(null===e.which||void 0===e.which)t=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)||(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(e){if(e.data&&"insertText"===e.inputType&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e!==this.cols||t!==this.rows?super.resize(e,t):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(e,t){this._charSizeService?.measure(),this.viewport?.syncScrollArea(!0)}clear(){if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeBasedDebouncer=void 0,t.TimeBasedDebouncer=class{constructor(e,t=1e3){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t;const s=Date.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){const e=s-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),t)}}_innerRefresh(){if(void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return;const e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}}},1680:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Viewport=void 0;const n=i(3656),o=i(4725),a=i(8460),h=i(844),c=i(2585);let l=t.Viewport=class extends h.Disposable{constructor(e,t,i,s,r,o,h,c){super(),this._viewportElement=e,this._scrollArea=t,this._bufferService=i,this._optionsService=s,this._charSizeService=r,this._renderService=o,this._coreBrowserService=h,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new a.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,n.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange((e=>this._renderDimensions=e))),this._handleThemeChange(c.colors),this.register(c.onChangeColors((e=>this._handleThemeChange(e)))),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.syncScrollArea()))),setTimeout((()=>this.syncScrollArea()))}_handleThemeChange(e){this._viewportElement.style.backgroundColor=e.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame((()=>this.syncScrollArea()))}_refresh(e){if(e)return this._innerRefresh(),void(null!==this._refreshAnimationFrame&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));null===this._refreshAnimationFrame&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderDimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderDimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const e=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderDimensions.css.canvas.height);this._lastRecordedBufferHeight!==e&&(this._lastRecordedBufferHeight=e,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const e=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==e&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=e),this._refreshAnimationFrame=null}syncScrollArea(e=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(e);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(e)}_handleScroll(e){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const t=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:t,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||-1===this._smoothScrollState.origin||-1===this._smoothScrollState.target)return;const e=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(e*(this._smoothScrollState.target-this._smoothScrollState.origin)),e<1?this._coreBrowserService.window.requestAnimationFrame((()=>this._smoothScroll())):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(e,t){const i=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(t<0&&0!==this._viewportElement.scrollTop||t>0&&i0&&(i=e),s=""}}return{bufferElements:r,cursorElement:i}}getLinesScrolled(e){if(0===e.deltaY||e.shiftKey)return 0;let t=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(t/=this._currentRowHeight+0,this._wheelPartialScroll+=t,t=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._bufferService.rows),t}_applyScrollModifier(e,t){const i=this._optionsService.rawOptions.fastScrollModifier;return"alt"===i&&t.altKey||"ctrl"===i&&t.ctrlKey||"shift"===i&&t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(e){this._lastTouchY=e.touches[0].pageY}handleTouchMove(e){const t=this._lastTouchY-e.touches[0].pageY;return this._lastTouchY=e.touches[0].pageY,0!==t&&(this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))}};t.Viewport=l=s([r(2,c.IBufferService),r(3,c.IOptionsService),r(4,o.ICharSizeService),r(5,o.IRenderService),r(6,o.ICoreBrowserService),r(7,o.IThemeService)],l)},3107:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferDecorationRenderer=void 0;const n=i(4725),o=i(844),a=i(2585);let h=t.BufferDecorationRenderer=class extends o.Disposable{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange((()=>this._doRefreshDecorations()))),this.register(this._renderService.onDimensionsChange((()=>{this._dimensionsChanged=!0,this._queueRefresh()}))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt}))),this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh()))),this.register(this._decorationService.onDecorationRemoved((e=>this._removeDecoration(e)))),this.register((0,o.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){void 0===this._animationFrame&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(const e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){const t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer","top"===e?.options?.layer),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",t.style.top=(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){const t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose((()=>{this._decorationElements.delete(e),i.remove()}))),i.style.top=t*this._renderService.dimensions.css.cell.height+"px",i.style.display=this._altBufferIsActive?"none":"block",e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;const i=e.options.x??0;"right"===(e.options.anchor||"left")?t.style.right=i?i*this._renderService.dimensions.css.cell.width+"px":"":t.style.left=i?i*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};t.BufferDecorationRenderer=h=s([r(1,a.IBufferService),r(2,n.ICoreBrowserService),r(3,a.IDecorationService),r(4,n.IRenderService)],h)},5871:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorZoneStore=void 0,t.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(const t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position))return void this._addLineToZone(t,e.marker.line)}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}}},5744:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OverviewRulerRenderer=void 0;const n=i(5871),o=i(4725),a=i(844),h=i(2585),c={full:0,left:0,center:0,right:0},l={full:0,left:0,center:0,right:0},d={full:0,left:0,center:0,right:0};let _=t.OverviewRulerRenderer=class extends a.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(e,t,i,s,r,o,h){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=o,this._coreBrowserService=h,this._colorZoneStore=new n.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement);const c=this._canvas.getContext("2d");if(!c)throw new Error("Ctx cannot be null");this._ctx=c,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,a.toDisposable)((()=>{this._canvas?.remove()})))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this.register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0))))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"}))),this.register(this._bufferService.onScroll((()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",(()=>this._queueRefresh(!0)))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh(!0)))),this._queueRefresh(!0)}_refreshDrawConstants(){const e=Math.floor(this._canvas.width/3),t=Math.ceil(this._canvas.width/3);l.full=this._canvas.width,l.left=e,l.center=t,l.right=e,this._refreshDrawHeightConstants(),d.full=0,d.left=0,d.center=l.left,d.right=l.left+l.center}_refreshDrawHeightConstants(){c.full=Math.round(2*this._coreBrowserService.dpr);const e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);c.left=t,c.center=t,c.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1;const e=this._colorZoneStore.zones;for(const t of e)"full"!==t.position&&this._renderColorZone(t);for(const t of e)"full"===t.position&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(d[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-c[e.position||"full"]/2),l[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+c[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,void 0===this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};t.OverviewRulerRenderer=_=s([r(2,h.IBufferService),r(3,h.IDecorationService),r(4,o.IRenderService),r(5,h.IOptionsService),r(6,o.ICoreBrowserService)],_)},2950:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositionHelper=void 0;const n=i(4725),o=i(2585),a=i(2584);let h=t.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(229===e.keyCode)return!1;if(16===e.keyCode||17===e.keyCode||18===e.keyCode)return!1;this._finalizeComposition(!1)}return 229!==e.keyCode||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){const e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let t;this._isSendingComposition=!1,e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,e.end):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}}),0)}else{this._isSendingComposition=!1;const e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){const e=this._textarea.value;setTimeout((()=>{if(!this._isComposing){const t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0)),0)}}};t.CompositionHelper=h=s([r(2,o.IBufferService),r(3,o.IOptionsService),r(4,o.ICoreService),r(5,n.IRenderService)],h)},9806:(e,t)=>{function i(e,t,i){const s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}Object.defineProperty(t,"__esModule",{value:!0}),t.getCoords=t.getCoordsRelativeToElement=void 0,t.getCoordsRelativeToElement=i,t.getCoords=function(e,t,s,r,n,o,a,h,c){if(!o)return;const l=i(e,t,s);return l?(l[0]=Math.ceil((l[0]+(c?a/2:0))/a),l[1]=Math.ceil(l[1]/h),l[0]=Math.min(Math.max(l[0],1),r+(c?1:0)),l[1]=Math.min(Math.max(l[1],1),n),l):void 0}},9504:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.moveToCellSequence=void 0;const s=i(2584);function r(e,t,i,s){const r=e-n(e,i),a=t-n(t,i),l=Math.abs(r-a)-function(e,t,i){let s=0;const r=e-n(e,i),a=t-n(t,i);for(let n=0;n=0&&et?"A":"B"}function a(e,t,i,s,r,n){let o=e,a=t,h="";for(;o!==i||a!==s;)o+=r?1:-1,r&&o>n.cols-1?(h+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(h+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return h+n.buffer.translateBufferLineToString(a,!1,e,o)}function h(e,t){const i=t?"O":"[";return s.C0.ESC+i+e}function c(e,t){e=Math.floor(e);let i="";for(let s=0;s0?s-n(s,o):t;const _=s,u=function(e,t,i,s,o,a){let h;return h=r(i,s,o,a).length>0?s-n(s,o):t,e=i&&he?"D":"C",c(Math.abs(o-e),h(d,s));d=l>t?"D":"C";const _=Math.abs(l-t);return c(function(e,t){return t.cols-e}(l>t?e:o,i)+(_-1)*i.cols+1+((l>t?o:e)-1),h(d,s))}},1296:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRenderer=void 0;const n=i(3787),o=i(2550),a=i(2223),h=i(6171),c=i(6052),l=i(4725),d=i(8055),_=i(8460),u=i(844),f=i(2585),v="xterm-dom-renderer-owner-",p="xterm-rows",g="xterm-fg-",m="xterm-bg-",S="xterm-focus",C="xterm-selection";let b=1,w=t.DomRenderer=class extends u.Disposable{constructor(e,t,i,s,r,a,l,d,f,g,m,S,w){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=a,this._linkifier2=l,this._charSizeService=f,this._optionsService=g,this._bufferService=m,this._coreBrowserService=S,this._themeService=w,this._terminalClass=b++,this._rowElements=[],this._selectionRenderModel=(0,c.createSelectionRenderModel)(),this.onRequestRedraw=this.register(new _.EventEmitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(p),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(C),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,h.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._themeService.onChangeColors((e=>this._injectCss(e)))),this._injectCss(this._themeService.colors),this._rowFactory=d.createInstance(n.DomRendererRowFactory,document),this._element.classList.add(v+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline((e=>this._handleLinkHover(e)))),this.register(this._linkifier2.onHideLinkUnderline((e=>this._handleLinkLeave(e)))),this.register((0,u.toDisposable)((()=>{this._element.classList.remove(v+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new o.WidthCache(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const t=`${this._terminalSelector} .${p} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${p} { color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${p} .xterm-dim { color: ${d.color.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;const i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${p}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${p}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${p}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${C} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${C} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${C} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(const[i,s]of e.ansi.entries())t+=`${this._terminalSelector} .${g}${i} { color: ${s.css}; }${this._terminalSelector} .${g}${i}.xterm-dim { color: ${d.color.multiplyOpacity(s,.5).css}; }${this._terminalSelector} .${m}${i} { background-color: ${s.css}; }`;t+=`${this._terminalSelector} .${g}${a.INVERTED_DEFAULT_COLOR} { color: ${d.color.opaque(e.background).css}; }${this._terminalSelector} .${g}${a.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${d.color.multiplyOpacity(d.color.opaque(e.background),.5).css}; }${this._terminalSelector} .${m}${a.INVERTED_DEFAULT_COLOR} { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){const e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){const e=this._document.createElement("div");this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(S),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(S),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t)return;this._selectionRenderModel.update(this._terminal,e,t,i);const s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow;if(n>=this._bufferService.rows||o<0)return;const a=this._document.createDocumentFragment();if(i){const i=e[0]>t[0];a.appendChild(this._createSelectionElement(n,i?t[0]:e[0],i?e[0]:t[0],o-n+1))}else{const i=s===n?e[0]:0,h=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,i,h));const c=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,c)),n!==o){const e=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,i,s=1){const r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width;let o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=s*this.dimensions.css.cell.height+"px",r.style.top=e*this.dimensions.css.cell.height+"px",r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const e of this._rowElements)e.replaceChildren()}renderRows(e,t){const i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._optionsService.rawOptions.cursorBlink,o=this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let h=e;h<=t;h++){const e=h+i.ydisp,t=this._rowElements[h],c=i.lines.get(e);if(!t||!c)break;t.replaceChildren(...this._rowFactory.createRow(c,e,e===s,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${v}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);const o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);const a=this._bufferService.buffer,h=a.ybase+a.y,c=Math.min(a.x,r-1),l=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,_=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=i;o<=s;++o){const u=o+a.ydisp,f=this._rowElements[o],v=a.lines.get(u);if(!f||!v)break;f.replaceChildren(...this._rowFactory.createRow(v,u,u===h,d,_,c,l,this.dimensions.css.cell.width,this._widthCache,n?o===i?e:0:-1,n?(o===s?t:r)-1:-1))}}};t.DomRenderer=w=s([r(7,f.IInstantiationService),r(8,l.ICharSizeService),r(9,f.IOptionsService),r(10,f.IBufferService),r(11,l.ICoreBrowserService),r(12,l.IThemeService)],w)},3787:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRendererRowFactory=void 0;const n=i(2223),o=i(643),a=i(511),h=i(2585),c=i(8055),l=i(4725),d=i(4269),_=i(6171),u=i(3734);let f=t.DomRendererRowFactory=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new a.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,a,h,l,_,f,p){const g=[],m=this._characterJoinerService.getJoinedCharacters(t),S=this._themeService.colors;let C,b=e.getNoBgTrimmedLength();i&&b0&&M===m[0][0]){O=!0;const t=m.shift();I=new d.JoinedCellData(this._workCell,e.translateToString(!0,t[0],t[1]),t[1]-t[0]),P=t[1]-1,b=I.getWidth()}const H=this._isCellInSelection(M,t),F=i&&M===a,W=T&&M>=f&&M<=p;let U=!1;this._decorationService.forEachDecorationAtCell(M,t,void 0,(e=>{U=!0}));let N=I.getChars()||o.WHITESPACE_CELL_CHAR;if(" "===N&&(I.isUnderline()||I.isOverline())&&(N=" "),A=b*l-_.get(N,I.isBold(),I.isItalic()),C){if(w&&(H&&x||!H&&!x&&I.bg===E)&&(H&&x&&S.selectionForeground||I.fg===k)&&I.extended.ext===L&&W===D&&A===R&&!F&&!O&&!U){I.isInvisible()?y+=o.WHITESPACE_CELL_CHAR:y+=N,w++;continue}w&&(C.textContent=y),C=this._document.createElement("span"),w=0,y=""}else C=this._document.createElement("span");if(E=I.bg,k=I.fg,L=I.extended.ext,D=W,R=A,x=H,O&&a>=M&&a<=P&&(a=M),!this._coreService.isCursorHidden&&F&&this._coreService.isCursorInitialized)if(B.push("xterm-cursor"),this._coreBrowserService.isFocused)h&&B.push("xterm-cursor-blink"),B.push("bar"===s?"xterm-cursor-bar":"underline"===s?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":B.push("xterm-cursor-outline");break;case"block":B.push("xterm-cursor-block");break;case"bar":B.push("xterm-cursor-bar");break;case"underline":B.push("xterm-cursor-underline")}if(I.isBold()&&B.push("xterm-bold"),I.isItalic()&&B.push("xterm-italic"),I.isDim()&&B.push("xterm-dim"),y=I.isInvisible()?o.WHITESPACE_CELL_CHAR:I.getChars()||o.WHITESPACE_CELL_CHAR,I.isUnderline()&&(B.push(`xterm-underline-${I.extended.underlineStyle}`)," "===y&&(y=" "),!I.isUnderlineColorDefault()))if(I.isUnderlineColorRGB())C.style.textDecorationColor=`rgb(${u.AttributeData.toColorRGB(I.getUnderlineColor()).join(",")})`;else{let e=I.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&I.isBold()&&e<8&&(e+=8),C.style.textDecorationColor=S.ansi[e].css}I.isOverline()&&(B.push("xterm-overline")," "===y&&(y=" ")),I.isStrikethrough()&&B.push("xterm-strikethrough"),W&&(C.style.textDecoration="underline");let $=I.getFgColor(),j=I.getFgColorMode(),z=I.getBgColor(),K=I.getBgColorMode();const q=!!I.isInverse();if(q){const e=$;$=z,z=e;const t=j;j=K,K=t}let V,G,X,J=!1;switch(this._decorationService.forEachDecorationAtCell(M,t,void 0,(e=>{"top"!==e.options.layer&&J||(e.backgroundColorRGB&&(K=50331648,z=e.backgroundColorRGB.rgba>>8&16777215,V=e.backgroundColorRGB),e.foregroundColorRGB&&(j=50331648,$=e.foregroundColorRGB.rgba>>8&16777215,G=e.foregroundColorRGB),J="top"===e.options.layer)})),!J&&H&&(V=this._coreBrowserService.isFocused?S.selectionBackgroundOpaque:S.selectionInactiveBackgroundOpaque,z=V.rgba>>8&16777215,K=50331648,J=!0,S.selectionForeground&&(j=50331648,$=S.selectionForeground.rgba>>8&16777215,G=S.selectionForeground)),J&&B.push("xterm-decoration-top"),K){case 16777216:case 33554432:X=S.ansi[z],B.push(`xterm-bg-${z}`);break;case 50331648:X=c.channels.toColor(z>>16,z>>8&255,255&z),this._addStyle(C,`background-color:#${v((z>>>0).toString(16),"0",6)}`);break;default:q?(X=S.foreground,B.push(`xterm-bg-${n.INVERTED_DEFAULT_COLOR}`)):X=S.background}switch(V||I.isDim()&&(V=c.color.multiplyOpacity(X,.5)),j){case 16777216:case 33554432:I.isBold()&&$<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&($+=8),this._applyMinimumContrast(C,X,S.ansi[$],I,V,void 0)||B.push(`xterm-fg-${$}`);break;case 50331648:const e=c.channels.toColor($>>16&255,$>>8&255,255&$);this._applyMinimumContrast(C,X,e,I,V,G)||this._addStyle(C,`color:#${v($.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(C,X,S.foreground,I,V,G)||q&&B.push(`xterm-fg-${n.INVERTED_DEFAULT_COLOR}`)}B.length&&(C.className=B.join(" "),B.length=0),F||O||U?C.textContent=y:w++,A!==this.defaultSpacing&&(C.style.letterSpacing=`${A}px`),g.push(C),M=P}return C&&w&&(C.textContent=y),g}_applyMinimumContrast(e,t,i,s,r,n){if(1===this._optionsService.rawOptions.minimumContrastRatio||(0,_.treatGlyphAsBackgroundColor)(s.getCode()))return!1;const o=this._getContrastCache(s);let a;if(r||n||(a=o.getColor(t.rgba,i.rgba)),void 0===a){const e=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);a=c.color.ensureContrastRatio(r||t,n||i,e),o.setColor((r||t).rgba,(n||i).rgba,a??null)}return!!a&&(this._addStyle(e,`color:${a.css}`),!0)}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){const i=this._selectionStart,s=this._selectionEnd;return!(!i||!s)&&(this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0])}};function v(e,t,i){for(;e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.WidthCache=void 0,t.WidthCache=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const i=e.createElement("span");i.classList.add("xterm-char-measure-element");const s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";const r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";const n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&1===e.length&&(s=e.charCodeAt(0))<256){if(-9999!==this._flat[s])return this._flat[s];const t=this._measure(e,0);return t>0&&(this._flat[s]=t),t}let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(void 0===n){let s=0;t&&(s|=1),i&&(s|=2),n=this._measure(e,s),n>0&&this._holey.set(r,n)}return n}_measure(e,t){const i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}}},2223:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TEXT_BASELINE=t.DIM_OPACITY=t.INVERTED_DEFAULT_COLOR=void 0;const s=i(6114);t.INVERTED_DEFAULT_COLOR=257,t.DIM_OPACITY=.5,t.TEXT_BASELINE=s.isFirefox||s.isLegacyEdge?"bottom":"ideographic"},6171:(e,t)=>{function i(e){return 57508<=e&&e<=57558}function s(e){return e>=128512&&e<=128591||e>=127744&&e<=128511||e>=128640&&e<=128767||e>=9728&&e<=9983||e>=9984&&e<=10175||e>=65024&&e<=65039||e>=129280&&e<=129535||e>=127462&&e<=127487}Object.defineProperty(t,"__esModule",{value:!0}),t.computeNextVariantOffset=t.createRenderDimensions=t.treatGlyphAsBackgroundColor=t.allowRescaling=t.isEmoji=t.isRestrictedPowerlineGlyph=t.isPowerlineGlyph=t.throwIfFalsy=void 0,t.throwIfFalsy=function(e){if(!e)throw new Error("value must not be falsy");return e},t.isPowerlineGlyph=i,t.isRestrictedPowerlineGlyph=function(e){return 57520<=e&&e<=57527},t.isEmoji=s,t.allowRescaling=function(e,t,r,n){return 1===t&&r>Math.ceil(1.5*n)&&void 0!==e&&e>255&&!s(e)&&!i(e)&&!function(e){return 57344<=e&&e<=63743}(e)},t.treatGlyphAsBackgroundColor=function(e){return i(e)||function(e){return 9472<=e&&e<=9631}(e)},t.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},t.computeNextVariantOffset=function(e,t,i=0){return(e-(2*Math.round(t)-i))%(2*Math.round(t))}},6052:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createSelectionRenderModel=void 0;class i{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1])return void this.clear();const r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,a=Math.max(n,0),h=Math.min(o,e.rows-1);a>=e.rows||h<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=a,this.viewportCappedEndRow=h,this.startCol=t[0],this.endCol=i[0])}isCellSelected(e,t,i){return!!this.hasSelection&&(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol)}}t.createSelectionRenderModel=function(){return new i}},456:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionModel=void 0,t.SelectionModel=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharSizeService=void 0;const n=i(2585),o=i(8460),a=i(844);let h=t.CharSizeService=class extends a.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this.register(new o.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this.register(new d(this._optionsService))}catch{this._measureStrategy=this.register(new l(e,t,this._optionsService))}this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],(()=>this.measure())))}measure(){const e=this._measureStrategy.measure();e.width===this.width&&e.height===this.height||(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};t.CharSizeService=h=s([r(2,n.IOptionsService)],h);class c extends a.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){void 0!==e&&e>0&&void 0!==t&&t>0&&(this._result.width=e,this._result.height=t)}}class l extends c{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}}class d extends c{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}}},4269:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharacterJoinerService=t.JoinedCellData=void 0;const n=i(3734),o=i(643),a=i(511),h=i(2585);class c extends n.AttributeData{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.JoinedCellData=c;let l=t.CharacterJoinerService=class e{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new a.CellData}register(e){const t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t1){const e=this._getJoinedRanges(s,a,n,t,r);for(let t=0;t1){const e=this._getJoinedRanges(s,a,n,t,r);for(let t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserService=void 0;const s=i(844),r=i(8460),n=i(3656);class o extends s.Disposable{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=new a(this._window),this._onDprChange=this.register(new r.EventEmitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this.register(new r.EventEmitter),this.onWindowChange=this._onWindowChange.event,this.register(this.onWindowChange((e=>this._screenDprMonitor.setWindow(e)))),this.register((0,r.forwardEvent)(this._screenDprMonitor.onDprChange,this._onDprChange)),this._textarea.addEventListener("focus",(()=>this._isFocused=!0)),this._textarea.addEventListener("blur",(()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return void 0===this._cachedIsFocused&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask((()=>this._cachedIsFocused=void 0))),this._cachedIsFocused}}t.CoreBrowserService=o;class a extends s.Disposable{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this.register(new s.MutableDisposable),this._onDprChange=this.register(new r.EventEmitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this.register((0,s.toDisposable)((()=>this.clearListener())))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,n.addDisposableDomListener)(this._parentWindow,"resize",(()=>this._setDprAndFireIfDiffers()))}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}}},779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkProviderService=void 0;const s=i(844);class r extends s.Disposable{constructor(){super(),this.linkProviders=[],this.register((0,s.toDisposable)((()=>this.linkProviders.length=0)))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{const t=this.linkProviders.indexOf(e);-1!==t&&this.linkProviders.splice(t,1)}}}}t.LinkProviderService=r},8934:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseService=void 0;const n=i(4725),o=i(9806);let a=t.MouseService=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return(0,o.getCoords)(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){const i=(0,o.getCoordsRelativeToElement)(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};t.MouseService=a=s([r(0,n.IRenderService),r(1,n.ICharSizeService)],a)},3230:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RenderService=void 0;const n=i(6193),o=i(4725),a=i(8460),h=i(844),c=i(7226),l=i(2585);let d=t.RenderService=class extends h.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(e,t,i,s,r,o,l,d){super(),this._rowCount=e,this._charSizeService=s,this._renderer=this.register(new h.MutableDisposable),this._pausedResizeTask=new c.DebouncedIdleTask,this._observerDisposable=this.register(new h.MutableDisposable),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new a.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new a.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new a.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new a.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new n.RenderDebouncer(((e,t)=>this._renderRows(e,t)),l),this.register(this._renderDebouncer),this.register(l.onDprChange((()=>this.handleDevicePixelRatioChange()))),this.register(o.onResize((()=>this._fullRefresh()))),this.register(o.buffers.onBufferActivate((()=>this._renderer.value?.clear()))),this.register(i.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this.register(r.onDecorationRegistered((()=>this._fullRefresh()))),this.register(r.onDecorationRemoved((()=>this._fullRefresh()))),this.register(i.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],(()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()}))),this.register(i.onMultipleOptionChange(["cursorBlink","cursorStyle"],(()=>this.refreshRows(o.buffer.y,o.buffer.y,!0)))),this.register(d.onChangeColors((()=>this._fullRefresh()))),this._registerIntersectionObserver(l.window,t),this.register(l.onWindowChange((e=>this._registerIntersectionObserver(e,t))))}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){const i=new e.IntersectionObserver((e=>this._handleIntersectionChange(e[e.length-1])),{threshold:0});i.observe(t),this._observerDisposable.value=(0,h.toDisposable)((()=>i.disconnect()))}}_handleIntersectionChange(e){this._isPaused=void 0===e.isIntersecting?0===e.intersectionRatio:!e.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){this._isPaused?this._needsFullRefresh=!0:(i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount))}_renderRows(e,t){this._renderer.value&&(e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0)}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw((e=>this.refreshRows(e.start,e.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>this._renderer.value?.handleResize(e,t))):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,i){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,this._renderer.value?.handleSelectionChanged(e,t,i)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};t.RenderService=d=s([r(2,l.IOptionsService),r(3,o.ICharSizeService),r(4,l.IDecorationService),r(5,l.IBufferService),r(6,o.ICoreBrowserService),r(7,o.IThemeService)],d)},9312:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionService=void 0;const n=i(9806),o=i(9504),a=i(456),h=i(4725),c=i(8460),l=i(844),d=i(6114),_=i(4841),u=i(511),f=i(2585),v=String.fromCharCode(160),p=new RegExp(v,"g");let g=t.SelectionService=class extends l.Disposable{constructor(e,t,i,s,r,n,o,h,d){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=h,this._coreBrowserService=d,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new u.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new c.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new c.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new c.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new c.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((e=>this._handleTrim(e))),this.register(this._bufferService.buffers.onBufferActivate((e=>this._handleBufferActivate(e)))),this.enable(),this._model=new a.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,l.toDisposable)((()=>{this._removeMouseDownListeners()})))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t||e[0]===t[0]&&e[1]===t[1])}get selectionText(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";const i=this._bufferService.buffer,s=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";const r=e[0]e.replace(p," "))).join(d.isWindows?"\r\n":"\n")}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),d.isLinux&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})}_isClickInSelection(e){const t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!!(i&&s&&t)&&this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){const i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!(!i||!s)&&this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){const i=this._linkifier.currentLink?.link?.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=(0,_.getRangeLength)(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const s=this._getMouseBufferCoords(e);return!!s&&(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){const t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=(0,n.getCoordsRelativeToElement)(this._coreBrowserService.window,e,this._screenElement)[1];const i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-50),50),t/=50,t/Math.abs(t)+Math.round(14*t))}shouldForceSelection(e){return d.isMac?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,(2!==e.button||!this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):1===e.detail?this._handleSingleClick(e):2===e.detail?this._handleDoubleClick(e):3===e.detail&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&0===t.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){const t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(d.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;const t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);2===this._activeSelectionMode?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){const t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&void 0!==t[0]&&void 0!==t[1]){const e=(0,o.moveToCellSequence)(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!(!e||!t||e[0]===t[0]&&e[1]===t[1]);i?e&&t&&(this._oldSelectionStart&&this._oldSelectionEnd&&e[0]===this._oldSelectionStart[0]&&e[1]===this._oldSelectionStart[1]&&t[0]===this._oldSelectionEnd[0]&&t[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(e,t,i)):this._oldHasSelection&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim((e=>this._handleTrim(e)))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){const r=e.loadCell(s,this._workCell).getChars().length;0===this._workCell.getWidth()?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;const r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;const o=r.translateBufferLineToString(e[1],!1);let a=this._convertViewportColToCharacterIndex(n,e[0]),h=a;const c=e[0]-a;let l=0,d=0,_=0,u=0;if(" "===o.charAt(a)){for(;a>0&&" "===o.charAt(a-1);)a--;for(;h1&&(u+=s-1,h+=s-1);t>0&&a>0&&!this._isCharWordSeparator(n.loadCell(t-1,this._workCell));){n.loadCell(t-1,this._workCell);const e=this._workCell.getChars().length;0===this._workCell.getWidth()?(l++,t--):e>1&&(_+=e-1,a-=e-1),a--,t--}for(;i1&&(u+=e-1,h+=e-1),h++,i++}}h++;let f=a+c-l+_,v=Math.min(this._bufferService.cols,h-a+l+d-_-u);if(t||""!==o.slice(a,h).trim()){if(i&&0===f&&32!==n.getCodePoint(0)){const t=r.lines.get(e[1]-1);if(t&&n.isWrapped&&32!==t.getCodePoint(this._bufferService.cols-1)){const t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){const e=this._bufferService.cols-t.start;f-=e,v+=e}}}if(s&&f+v===this._bufferService.cols&&32!==n.getCodePoint(this._bufferService.cols-1)){const t=r.lines.get(e[1]+1);if(t?.isWrapped&&32!==t.getCodePoint(0)){const t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(v+=t.length)}}return{start:f,length:v}}}_selectWordAt(e,t){const i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){const t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return 0!==e.getWidth()&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){const t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,_.getRangeLength)(i,this._bufferService.cols)}};t.SelectionService=g=s([r(3,f.IBufferService),r(4,f.ICoreService),r(5,h.IMouseService),r(6,f.IOptionsService),r(7,h.IRenderService),r(8,h.ICoreBrowserService)],g)},4725:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ILinkProviderService=t.IThemeService=t.ICharacterJoinerService=t.ISelectionService=t.IRenderService=t.IMouseService=t.ICoreBrowserService=t.ICharSizeService=void 0;const s=i(8343);t.ICharSizeService=(0,s.createDecorator)("CharSizeService"),t.ICoreBrowserService=(0,s.createDecorator)("CoreBrowserService"),t.IMouseService=(0,s.createDecorator)("MouseService"),t.IRenderService=(0,s.createDecorator)("RenderService"),t.ISelectionService=(0,s.createDecorator)("SelectionService"),t.ICharacterJoinerService=(0,s.createDecorator)("CharacterJoinerService"),t.IThemeService=(0,s.createDecorator)("ThemeService"),t.ILinkProviderService=(0,s.createDecorator)("LinkProviderService")},6731:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ThemeService=t.DEFAULT_ANSI_COLORS=void 0;const n=i(7239),o=i(8055),a=i(8460),h=i(844),c=i(2585),l=o.css.toColor("#ffffff"),d=o.css.toColor("#000000"),_=o.css.toColor("#ffffff"),u=o.css.toColor("#000000"),f={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const e=[o.css.toColor("#2e3436"),o.css.toColor("#cc0000"),o.css.toColor("#4e9a06"),o.css.toColor("#c4a000"),o.css.toColor("#3465a4"),o.css.toColor("#75507b"),o.css.toColor("#06989a"),o.css.toColor("#d3d7cf"),o.css.toColor("#555753"),o.css.toColor("#ef2929"),o.css.toColor("#8ae234"),o.css.toColor("#fce94f"),o.css.toColor("#729fcf"),o.css.toColor("#ad7fa8"),o.css.toColor("#34e2e2"),o.css.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){const s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:o.channels.toCss(s,r,n),rgba:o.channels.toRgba(s,r,n)})}for(let t=0;t<24;t++){const i=8+10*t;e.push({css:o.channels.toCss(i,i,i),rgba:o.channels.toRgba(i,i,i)})}return e})());let v=t.ThemeService=class extends h.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new n.ColorContrastCache,this._halfContrastCache=new n.ColorContrastCache,this._onChangeColors=this.register(new a.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:l,background:d,cursor:_,cursorAccent:u,selectionForeground:void 0,selectionBackgroundTransparent:f,selectionBackgroundOpaque:o.color.blend(d,f),selectionInactiveBackgroundTransparent:f,selectionInactiveBackgroundOpaque:o.color.blend(d,f),ansi:t.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange("theme",(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){const i=this._colors;if(i.foreground=p(e.foreground,l),i.background=p(e.background,d),i.cursor=p(e.cursor,_),i.cursorAccent=p(e.cursorAccent,u),i.selectionBackgroundTransparent=p(e.selectionBackground,f),i.selectionBackgroundOpaque=o.color.blend(i.background,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundTransparent=p(e.selectionInactiveBackground,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundOpaque=o.color.blend(i.background,i.selectionInactiveBackgroundTransparent),i.selectionForeground=e.selectionForeground?p(e.selectionForeground,o.NULL_COLOR):void 0,i.selectionForeground===o.NULL_COLOR&&(i.selectionForeground=void 0),o.color.isOpaque(i.selectionBackgroundTransparent)){const e=.3;i.selectionBackgroundTransparent=o.color.opacity(i.selectionBackgroundTransparent,e)}if(o.color.isOpaque(i.selectionInactiveBackgroundTransparent)){const e=.3;i.selectionInactiveBackgroundTransparent=o.color.opacity(i.selectionInactiveBackgroundTransparent,e)}if(i.ansi=t.DEFAULT_ANSI_COLORS.slice(),i.ansi[0]=p(e.black,t.DEFAULT_ANSI_COLORS[0]),i.ansi[1]=p(e.red,t.DEFAULT_ANSI_COLORS[1]),i.ansi[2]=p(e.green,t.DEFAULT_ANSI_COLORS[2]),i.ansi[3]=p(e.yellow,t.DEFAULT_ANSI_COLORS[3]),i.ansi[4]=p(e.blue,t.DEFAULT_ANSI_COLORS[4]),i.ansi[5]=p(e.magenta,t.DEFAULT_ANSI_COLORS[5]),i.ansi[6]=p(e.cyan,t.DEFAULT_ANSI_COLORS[6]),i.ansi[7]=p(e.white,t.DEFAULT_ANSI_COLORS[7]),i.ansi[8]=p(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),i.ansi[9]=p(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),i.ansi[10]=p(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),i.ansi[11]=p(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),i.ansi[12]=p(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),i.ansi[13]=p(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),i.ansi[14]=p(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),i.ansi[15]=p(e.brightWhite,t.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){const s=Math.min(i.ansi.length-16,e.extendedAnsi.length);for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.CircularList=void 0;const s=i(8460),r=i(844);class n extends r.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this.register(new s.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new s.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new s.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;const t=new Array(e);for(let i=0;ithis._length)for(let t=this._length;t=e;t--)this._array[this._getCyclicIndex(t+i.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;tthis._maxLength){const e=this._length+i.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let s=t-1;s>=0;s--)this.set(e+s+i,this.get(e+s));const s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s{Object.defineProperty(t,"__esModule",{value:!0}),t.clone=void 0,t.clone=function e(t,i=5){if("object"!=typeof t)return t;const s=Array.isArray(t)?[]:{};for(const r in t)s[r]=i<=1?t[r]:t[r]&&e(t[r],i-1);return s}},8055:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.contrastRatio=t.toPaddedHex=t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0;let i=0,s=0,r=0,n=0;var o,a,h,c,l;function d(e){const t=e.toString(16);return t.length<2?"0"+t:t}function _(e,t){return e>>0},e.toColor=function(t,i,s,r){return{css:e.toCss(t,i,s,r),rgba:e.toRgba(t,i,s,r)}}}(o||(t.channels=o={})),function(e){function t(e,t){return n=Math.round(255*t),[i,s,r]=l.toChannels(e.rgba),{css:o.toCss(i,s,r,n),rgba:o.toRgba(i,s,r,n)}}e.blend=function(e,t){if(n=(255&t.rgba)/255,1===n)return{css:t.css,rgba:t.rgba};const a=t.rgba>>24&255,h=t.rgba>>16&255,c=t.rgba>>8&255,l=e.rgba>>24&255,d=e.rgba>>16&255,_=e.rgba>>8&255;return i=l+Math.round((a-l)*n),s=d+Math.round((h-d)*n),r=_+Math.round((c-_)*n),{css:o.toCss(i,s,r),rgba:o.toRgba(i,s,r)}},e.isOpaque=function(e){return!(255&~e.rgba)},e.ensureContrastRatio=function(e,t,i){const s=l.ensureContrastRatio(e.rgba,t.rgba,i);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},e.opaque=function(e){const t=(255|e.rgba)>>>0;return[i,s,r]=l.toChannels(t),{css:o.toCss(i,s,r),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,i){return n=255&e.rgba,t(e,n*i/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(a||(t.color=a={})),function(e){let t,a;try{const e=document.createElement("canvas");e.width=1,e.height=1;const i=e.getContext("2d",{willReadFrequently:!0});i&&(t=i,t.globalCompositeOperation="copy",a=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return i=parseInt(e.slice(1,2).repeat(2),16),s=parseInt(e.slice(2,3).repeat(2),16),r=parseInt(e.slice(3,4).repeat(2),16),o.toColor(i,s,r);case 5:return i=parseInt(e.slice(1,2).repeat(2),16),s=parseInt(e.slice(2,3).repeat(2),16),r=parseInt(e.slice(3,4).repeat(2),16),n=parseInt(e.slice(4,5).repeat(2),16),o.toColor(i,s,r,n);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}const h=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(h)return i=parseInt(h[1]),s=parseInt(h[2]),r=parseInt(h[3]),n=Math.round(255*(void 0===h[5]?1:parseFloat(h[5]))),o.toColor(i,s,r,n);if(!t||!a)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=a,t.fillStyle=e,"string"!=typeof t.fillStyle)throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[i,s,r,n]=t.getImageData(0,0,1,1).data,255!==n)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(i,s,r,n),css:e}}}(h||(t.css=h={})),function(e){function t(e,t,i){const s=e/255,r=t/255,n=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(c||(t.rgb=c={})),function(e){function t(e,t,i){const s=e>>24&255,r=e>>16&255,n=e>>8&255;let o=t>>24&255,a=t>>16&255,h=t>>8&255,l=_(c.relativeLuminance2(o,a,h),c.relativeLuminance2(s,r,n));for(;l0||a>0||h>0);)o-=Math.max(0,Math.ceil(.1*o)),a-=Math.max(0,Math.ceil(.1*a)),h-=Math.max(0,Math.ceil(.1*h)),l=_(c.relativeLuminance2(o,a,h),c.relativeLuminance2(s,r,n));return(o<<24|a<<16|h<<8|255)>>>0}function a(e,t,i){const s=e>>24&255,r=e>>16&255,n=e>>8&255;let o=t>>24&255,a=t>>16&255,h=t>>8&255,l=_(c.relativeLuminance2(o,a,h),c.relativeLuminance2(s,r,n));for(;l>>0}e.blend=function(e,t){if(n=(255&t)/255,1===n)return t;const a=t>>24&255,h=t>>16&255,c=t>>8&255,l=e>>24&255,d=e>>16&255,_=e>>8&255;return i=l+Math.round((a-l)*n),s=d+Math.round((h-d)*n),r=_+Math.round((c-_)*n),o.toRgba(i,s,r)},e.ensureContrastRatio=function(e,i,s){const r=c.relativeLuminance(e>>8),n=c.relativeLuminance(i>>8);if(_(r,n)>8));if(o_(r,c.relativeLuminance(t>>8))?n:t}return n}const o=a(e,i,s),h=_(r,c.relativeLuminance(o>>8));if(h_(r,c.relativeLuminance(n>>8))?o:n}return o}},e.reduceLuminance=t,e.increaseLuminance=a,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(l||(t.rgba=l={})),t.toPaddedHex=d,t.contrastRatio=_},8969:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreTerminal=void 0;const s=i(844),r=i(2585),n=i(4348),o=i(7866),a=i(744),h=i(7302),c=i(6975),l=i(8460),d=i(1753),_=i(1480),u=i(7994),f=i(9282),v=i(5435),p=i(5981),g=i(2660);let m=!1;class S extends s.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new l.EventEmitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(const t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this.register(new s.MutableDisposable),this._onBinary=this.register(new l.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new l.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new l.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new l.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new l.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new l.EventEmitter),this._instantiationService=new n.InstantiationService,this.optionsService=this.register(new h.OptionsService(e)),this._instantiationService.setService(r.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(a.BufferService)),this._instantiationService.setService(r.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(o.LogService)),this._instantiationService.setService(r.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(c.CoreService)),this._instantiationService.setService(r.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(d.CoreMouseService)),this._instantiationService.setService(r.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(_.UnicodeService)),this._instantiationService.setService(r.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(u.CharsetService),this._instantiationService.setService(r.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(g.OscLinkService),this._instantiationService.setService(r.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new v.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,l.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,l.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,l.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,l.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new p.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this.register((0,l.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=r.LogLevelEnum.WARN&&!m&&(this._logService.warn("writeSync is unreliable and will be removed soon."),m=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,a.MINIMUM_COLS),t=Math.max(t,a.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t,i){this._bufferService.scrollLines(e,t,i)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){const t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1;const t=this.optionsService.rawOptions.windowsPty;t&&void 0!==t.buildNumber&&void 0!==t.buildNumber?e=!!("conpty"===t.backend&&t.buildNumber<21376):this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const e=[];e.push(this.onLineFeed(f.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},(()=>((0,f.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,s.toDisposable)((()=>{for(const t of e)t.dispose()}))}}}t.CoreTerminal=S},8460:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed)for(let t=0;tt.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},5435:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0;const n=i(2584),o=i(7116),a=i(2015),h=i(844),c=i(482),l=i(8437),d=i(8460),_=i(643),u=i(511),f=i(3734),v=i(2585),p=i(1480),g=i(6242),m=i(6351),S=i(5941),C={"(":0,")":1,"*":2,"+":3,"-":1,".":2},b=131072;function w(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var y;!function(e){e[e.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",e[e.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"}(y||(t.WindowsOptionsReportType=y={}));let E=0;class k extends h.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,i,s,r,h,_,f,v=new a.EscapeSequenceParser){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=h,this._coreMouseService=_,this._unicodeService=f,this._parser=v,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new c.StringToUtf32,this._utf8Decoder=new c.Utf8ToUtf32,this._workCell=new u.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new d.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new d.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new d.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new d.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new d.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new d.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new d.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new d.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new d.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new d.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new d.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new d.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new L(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})})),this._parser.setOscHandlerFallback(((e,t,i)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:i})})),this._parser.setDcsHandlerFallback(((e,t,i)=>{"HOOK"===t&&(i=i.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:t,payload:i})})),this._parser.setPrintHandler(((e,t,i)=>this.print(e,t,i))),this._parser.registerCsiHandler({final:"@"},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:"A"},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:"B"},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:"C"},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:"D"},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:"E"},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:"F"},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:"G"},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:"H"},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:"I"},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:"J"},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:"K"},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:"L"},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:"M"},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:"P"},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:"S"},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:"T"},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:"X"},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:"Z"},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:"a"},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:"b"},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:"c"},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:">",final:"c"},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:"d"},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:"e"},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:"f"},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:"g"},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:"h"},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:"l"},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:"m"},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:"n"},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:"r"},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:"s"},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:"t"},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:"u"},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(n.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(n.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(n.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(n.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(n.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(n.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(n.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(n.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(n.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new g.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new g.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new g.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new g.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new g.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new g.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new g.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new g.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new g.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new g.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new g.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new g.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(const e in o.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:e},(()=>this.selectCharset("("+e))),this._parser.registerEscHandler({intermediates:")",final:e},(()=>this.selectCharset(")"+e))),this._parser.registerEscHandler({intermediates:"*",final:e},(()=>this.selectCharset("*"+e))),this._parser.registerEscHandler({intermediates:"+",final:e},(()=>this.selectCharset("+"+e))),this._parser.registerEscHandler({intermediates:"-",final:e},(()=>this.selectCharset("-"+e))),this._parser.registerEscHandler({intermediates:".",final:e},(()=>this.selectCharset("."+e))),this._parser.registerEscHandler({intermediates:"/",final:e},(()=>this.selectCharset("/"+e)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error("Parsing error: ",e),e))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new m.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=v.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t("#SLOW_TIMEOUT")),5e3)))]).catch((e=>{if("#SLOW_TIMEOUT"!==e)throw e;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0;const o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>b&&(n=this._parseStack.position+b)}if(this._logService.logLevel<=v.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+("string"==typeof e?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join("")}"`),"string"==typeof e?e.split("").map((e=>e.charCodeAt(0))):e),this._parseBuffer.lengthb)for(let t=n;t0&&2===f.getWidth(this._activeBuffer.x-1)&&f.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let v=this._parser.precedingJoinState;for(let g=t;ga)if(h){const e=f;let t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),f=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&f instanceof l.BufferLine&&f.copyCellsFrom(e,t,0,m,!1);t=0;)f.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(d&&(f.insertCells(this._activeBuffer.x,r-m,this._activeBuffer.getNullCell(u)),2===f.getWidth(a-1)&&f.setCellFromCodepoint(a-1,_.NULL_CELL_CODE,_.NULL_CELL_WIDTH,u)),f.setCellFromCodepoint(this._activeBuffer.x++,s,r,u),r>0)for(;--r;)f.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=v,this._activeBuffer.x0&&0===f.getWidth(this._activeBuffer.x)&&!f.hasContent(this._activeBuffer.x)&&f.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return"t"!==e.final||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!w(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new m.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new g.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(0===this._activeBuffer.x&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){const t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){const t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){const t=e.params[0];return 0===t?delete this._activeBuffer.tabs[this._activeBuffer.x]:3===t&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){const t=e.params[0];return 1===t&&(this._curAttrData.bg|=536870912),2!==t&&0!==t||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){const n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){const i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){let i;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 3:const e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let h=a;for(let e=1;e0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(n.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(n.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(n.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(n.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(n.C0.ESC+"[>83;40003;0c")),!0}_is(e){return 0===(this._optionsService.rawOptions.termName+"").indexOf(e)}setMode(e){for(let t=0;te?1:2,u=e.params[0];return f=u,v=t?2===u?4:4===u?_(o.modes.insertMode):12===u?3:20===u?_(d.convertEol):0:1===u?_(i.applicationCursorKeys):3===u?d.windowOptions.setWinLines?80===h?2:132===h?1:0:0:6===u?_(i.origin):7===u?_(i.wraparound):8===u?3:9===u?_("X10"===s):12===u?_(d.cursorBlink):25===u?_(!o.isCursorHidden):45===u?_(i.reverseWraparound):66===u?_(i.applicationKeypad):67===u?4:1e3===u?_("VT200"===s):1002===u?_("DRAG"===s):1003===u?_("ANY"===s):1004===u?_(i.sendFocus):1005===u?4:1006===u?_("SGR"===r):1015===u?4:1016===u?_("SGR_PIXELS"===r):1048===u?1:47===u||1047===u||1049===u?_(c===l):2004===u?_(i.bracketedPasteMode):0,o.triggerDataEvent(`${n.C0.ESC}[${t?"":"?"}${f};${v}$y`),!0;var f,v}_updateAttrColor(e,t,i,s,r){return 2===t?(e|=50331648,e&=-16777216,e|=f.AttributeData.fromColorRGB([i,s,r])):5===t&&(e&=-50331904,e|=33554432|255&i),e}_extractColor(e,t,i){const s=[0,0,-1,0,0,0];let r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){const i=e.getSubParams(t+n);let o=0;do{5===s[1]&&(r=1),s[n+o+1+r]=i[o]}while(++o=2||2===s[1]&&n+r>=5)break;s[1]&&(r=1)}while(++n+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,0===e&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=l.DEFAULT_ATTR_DATA.fg,e.bg=l.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(1===e.length&&0===e.params[0])return this._processSGR0(this._curAttrData),!0;const t=e.length;let i;const s=this._curAttrData;for(let r=0;r=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777224|i-90):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777224|i-100):0===i?this._processSGR0(s):1===i?s.fg|=134217728:3===i?s.bg|=67108864:4===i?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):5===i?s.fg|=536870912:7===i?s.fg|=67108864:8===i?s.fg|=1073741824:9===i?s.fg|=2147483648:2===i?s.bg|=134217728:21===i?this._processUnderline(2,s):22===i?(s.fg&=-134217729,s.bg&=-134217729):23===i?s.bg&=-67108865:24===i?(s.fg&=-268435457,this._processUnderline(0,s)):25===i?s.fg&=-536870913:27===i?s.fg&=-67108865:28===i?s.fg&=-1073741825:29===i?s.fg&=2147483647:39===i?(s.fg&=-67108864,s.fg|=16777215&l.DEFAULT_ATTR_DATA.fg):49===i?(s.bg&=-67108864,s.bg|=16777215&l.DEFAULT_ATTR_DATA.bg):38===i||48===i||58===i?r+=this._extractColor(e,r,s):53===i?s.bg|=1073741824:55===i?s.bg&=-1073741825:59===i?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):100===i?(s.fg&=-67108864,s.fg|=16777215&l.DEFAULT_ATTR_DATA.fg,s.bg&=-67108864,s.bg|=16777215&l.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${n.C0.ESC}[0n`);break;case 6:const e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(6===e.params[0]){const e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){const t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const i=t%2==1;return this._optionsService.options.cursorBlink=i,!0}setScrollRegion(e){const t=e.params[0]||1;let i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||0===i)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!w(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;const t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==t&&this._onRequestWindowsOptionsReport.fire(y.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(y.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${n.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:0!==t&&2!==t||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),0!==t&&1!==t||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:0!==t&&2!==t||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),0!==t&&1!==t||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){const t=[],i=e.split(";");for(;i.length>1;){const e=i.shift(),s=i.shift();if(/^\d+$/.exec(e)){const i=parseInt(e);if(D(i))if("?"===s)t.push({type:0,index:i});else{const e=(0,S.parseColor)(s);e&&t.push({type:1,index:i,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){const t=e.split(";");return!(t.length<2)&&(t[1]?this._createHyperlink(t[0],t[1]):!t[0]&&this._finishHyperlink())}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();const i=e.split(":");let s;const r=i.findIndex((e=>e.startsWith("id=")));return-1!==r&&(s=i[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){const i=e.split(";");for(let e=0;e=this._specialColors.length);++e,++t)if("?"===i[e])this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{const s=(0,S.parseColor)(i[e]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;const t=[],i=e.split(";");for(let e=0;e=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){const e=new u.CellData;e.content=1<<22|"E".charCodeAt(0),e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${n.C0.ESC}${e}${n.C0.ESC}\\`),!0))('"q'===e?`P1$r${this._curAttrData.isProtected()?1:0}"q`:'"p'===e?'P1$r61;1"p':"r"===e?`P1$r${i.scrollTop+1};${i.scrollBottom+1}r`:"m"===e?"P1$r0m":" q"===e?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=k;let L=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(E=e,e=t,t=E),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function D(e){return 0<=e&&e<256}L=s([r(0,v.IBufferService)],L)},844:(e,t)=>{function i(e){for(const t of e)t.dispose();e.length=0}Object.defineProperty(t,"__esModule",{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){const t=this._disposables.indexOf(e);-1!==t&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=i,t.getDisposeArrayDisposable=function(e){return{dispose:()=>i(e)}}},1505:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class i{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=i,t.FourKeyMap=class{constructor(){this._data=new i}set(e,t,s,r,n){this._data.get(e,t)||this._data.set(e,t,new i),this._data.get(e,t).set(s,r,n)}get(e,t,i,s){return this._data.get(e,t)?.get(i,s)}clear(){this._data.clear()}}},6114:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.getSafariVersion=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.isNode="title"in E;const i=t.isNode?"node":navigator.userAgent,s=t.isNode?"node":navigator.platform;t.isFirefox=i.includes("Firefox"),t.isLegacyEdge=i.includes("Edge"),t.isSafari=/^((?!chrome|android).)*safari/i.test(i),t.getSafariVersion=function(){if(!t.isSafari)return 0;const e=i.match(/Version\/(\d+)/);return null===e||e.length<2?0:parseInt(e[1])},t.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(s),t.isIpad="iPad"===s,t.isIphone="iPhone"===s,t.isWindows=["Windows","Win16","Win32","WinCE"].includes(s),t.isLinux=s.indexOf("Linux")>=0,t.isChromeOS=/\bCrOS\b/.test(i)},6106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedList=void 0;let i=0;t.SortedList=class{constructor(e){this._getKey=e,this._array=[]}clear(){this._array.length=0}insert(e){0!==this._array.length?(i=this._search(this._getKey(e)),this._array.splice(i,0,e)):this._array.push(e)}delete(e){if(0===this._array.length)return!1;const t=this._getKey(e);if(void 0===t)return!1;if(i=this._search(t),-1===i)return!1;if(this._getKey(this._array[i])!==t)return!1;do{if(this._array[i]===e)return this._array.splice(i,1),!0}while(++i=this._array.length)&&this._getKey(this._array[i])===e))do{yield this._array[i]}while(++i=this._array.length)&&this._getKey(this._array[i])===e))do{t(this._array[i])}while(++i=t;){let s=t+i>>1;const r=this._getKey(this._array[s]);if(r>e)i=s-1;else{if(!(r0&&this._getKey(this._array[s-1])===e;)s--;return s}t=s+1}}return t}}},7226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;const s=i(6114);class r{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ir)return s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),void this._start();s=r}this.clear()}}class n extends r{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){const t=Date.now()+e;return{timeRemaining:()=>Math.max(0,t-Date.now())}}}t.PriorityTaskQueue=n,t.IdleTaskQueue=!s.isNode&&"requestIdleCallback"in window?class extends r{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:n,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},9282:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateWindowsModeWrappedState=void 0;const s=i(643);t.updateWindowsModeWrappedState=function(e){const t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1),i=t?.get(e.cols-1),r=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);r&&i&&(r.isWrapped=i[s.CHAR_DATA_CODE_INDEX]!==s.NULL_CELL_CODE&&i[s.CHAR_DATA_CODE_INDEX]!==s.WHITESPACE_CELL_CODE)}},3734:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class i{constructor(){this.fg=0,this.bg=0,this.extended=new s}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){const e=new i;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=i;class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){const e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new s(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}}t.ExtendedAttrs=s},9092:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;const s=i(6349),r=i(7226),n=i(3734),o=i(8437),a=i(4634),h=i(511),c=i(643),l=i(4863),d=i(7116);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=h.CellData.fromCharData([0,c.NULL_CELL_CHAR,c.NULL_CELL_WIDTH,c.NULL_CELL_CODE]),this._whitespaceCell=h.CellData.fromCharData([0,c.WHITESPACE_CELL_CHAR,c.WHITESPACE_CELL_WIDTH,c.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new r.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new s.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new n.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new n.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const e=this.ybase+this.y-this.ydisp;return e>=0&&et.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:i}fillViewportRows(e){if(0===this.lines.length){void 0===e&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new s.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){const i=this.getNullCell(o.DEFAULT_ATTR_DATA);let s=0;const r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,i)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){const e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&"conpty"===e.backend&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){const i=(0,a.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA));if(i.length>0){const s=(0,a.reflowLargerCreateNewLayout)(this.lines,i);(0,a.reflowLargerApplyNewLayout)(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){const s=this.getNullCell(o.DEFAULT_ATTR_DATA);let r=i;for(;r-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length=0;n--){let h=this.lines.get(n);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;const c=[h];for(;h.isWrapped&&n>0;)h=this.lines.get(--n),c.unshift(h);const l=this.ybase+this.y;if(l>=n&&l0&&(s.push({start:n+c.length+r,newLines:v}),r+=v.length),c.push(...v);let p=_.length-1,g=_[p];0===g&&(p--,g=_[p]);let m=c.length-u-1,S=d;for(;m>=0;){const e=Math.min(S,g);if(void 0===c[p])break;if(c[p].copyCellsFrom(c[m],S-e,g-e,e,!0),g-=e,0===g&&(p--,g=_[p]),S-=e,0===S){m--;const e=Math.max(m,0);S=(0,a.getWrappedLineTrimmedLength)(c,e,this._cols)}}for(let t=0;t0;)0===this.ybase?this.y0){const e=[],t=[];for(let e=0;e=0;c--)if(a&&a.start>n+h){for(let e=a.newLines.length-1;e>=0;e--)this.lines.set(c--,a.newLines[e]);c++,e.push({index:n+1,amount:a.newLines.length}),h+=a.newLines.length,a=s[++o]}else this.lines.set(c,t[n--]);let c=0;for(let t=e.length-1;t>=0;t--)e[t].index+=c,this.lines.onInsertEmitter.fire(e[t]),c+=e[t].amount;const l=Math.max(0,i+r-this.lines.maxLength);l>0&&this.lines.onTrimEmitter.fire(l)}}translateBufferLineToString(e,t,i=0,s){const r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.linee.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},8437:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;const s=i(3734),r=i(511),n=i(643),o=i(482);t.DEFAULT_ATTR_DATA=Object.freeze(new s.AttributeData);let a=0;class h{constructor(e,t,i=!1){this.isWrapped=i,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);const s=t||r.CellData.fromCharData([0,n.NULL_CELL_CHAR,n.NULL_CELL_WIDTH,n.NULL_CELL_CODE]);for(let t=0;t>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):i]}set(e,t){this._data[3*e+1]=t[n.CHAR_DATA_ATTR_INDEX],t[n.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[n.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[n.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[n.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){const t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){const t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):""}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return a=3*e,t.content=this._data[a+0],t.fg=this._data[a+1],t.bg=this._data[a+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,i,s){268435456&s.bg&&(this._extendedAttrs[e]=s.extended),this._data[3*e+0]=t|i<<22,this._data[3*e+1]=s.fg,this._data[3*e+2]=s.bg}addCodepointToCell(e,t,i){let s=this._data[3*e+0];2097152&s?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&s?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&s)+(0,o.stringFromCodePoint)(t),s&=-2097152,s|=2097152):s=t|1<<22,i&&(s&=-12582913,s|=i<<22),this._data[3*e+0]=s}insertCells(e,t,i){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t=0;--i)this.setCell(e+t+i,this.loadCell(e+i,s));for(let s=0;sthis.length){if(this._data.buffer.byteLength>=4*i)this._data=new Uint32Array(this._data.buffer,0,i);else{const e=new Uint32Array(i);e.set(this._data),this._data=e}for(let i=this.length;i=e&&delete this._combined[s]}const s=Object.keys(this._extendedAttrs);for(let t=0;t=e&&delete this._extendedAttrs[i]}}return this.length=e,4*i*2=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,i,s,r){const n=e._data;if(r)for(let r=s-1;r>=0;r--){for(let e=0;e<3;e++)this._data[3*(i+r)+e]=n[3*(t+r)+e];268435456&n[3*(t+r)+2]&&(this._extendedAttrs[i+r]=e._extendedAttrs[t+r])}else for(let r=0;r=t&&(this._combined[r-t+i]=e._combined[r])}}translateToString(e,t,i,s){t=t??0,i=i??this.length,e&&(i=Math.min(i,this.getTrimmedLength())),s&&(s.length=0);let r="";for(;t>22||1}return s&&s.push(t),r}}t.BufferLine=h},4841:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRangeLength=void 0,t.getRangeLength=function(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}},4634:(e,t)=>{function i(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();const s=!e[t].hasContent(i-1)&&1===e[t].getWidth(i-1),r=2===e[t+1].getWidth(0);return s&&r?i-1:i}Object.defineProperty(t,"__esModule",{value:!0}),t.getWrappedLineTrimmedLength=t.reflowSmallerGetNewLineLengths=t.reflowLargerApplyNewLayout=t.reflowLargerCreateNewLayout=t.reflowLargerGetLinesToRemove=void 0,t.reflowLargerGetLinesToRemove=function(e,t,s,r,n){const o=[];for(let a=0;a=a&&r0&&(e>d||0===l[e].getTrimmedLength());e--)v++;v>0&&(o.push(a+l.length-v),o.push(v)),a+=l.length-1}return o},t.reflowLargerCreateNewLayout=function(e,t){const i=[];let s=0,r=t[s],n=0;for(let o=0;oi(e,r,t))).reduce(((e,t)=>e+t));let o=0,a=0,h=0;for(;hc&&(o-=c,a++);const l=2===e[a].getWidth(o-1);l&&o--;const d=l?s-1:s;r.push(d),h+=d}return r},t.getWrappedLineTrimmedLength=i},5295:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferSet=void 0;const s=i(8460),r=i(844),n=i(9092);class o extends r.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this.register(new s.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new n.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new n.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},511:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CellData=void 0;const s=i(482),r=i(643),n=i(3734);class o extends n.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new n.ExtendedAttrs,this.combinedData=""}static fromCharData(e){const t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,s.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[r.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[r.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(2===e[r.CHAR_DATA_CHAR_INDEX].length){const i=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){const s=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|e[r.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[r.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[r.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[r.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR="",t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=" ",t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},4863:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Marker=void 0;const s=i(8460),r=i(844);class n{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=n._nextId++,this._onDispose=this.register(new s.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,r.disposeArray)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=n,n._nextId=1},7116:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},t.CHARSETS.A={"#":"£"},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},t.CHARSETS.C=t.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},t.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},t.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},t.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},t.CHARSETS.E=t.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},t.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},t.CHARSETS.H=t.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(e,t)=>{var i,s,r;Object.defineProperty(t,"__esModule",{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="",e.BS="\b",e.HT="\t",e.LF="\n",e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""}(i||(t.C0=i={})),function(e){e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"}(s||(t.C1=s={})),function(e){e.ST=`${i.ESC}\\`}(r||(t.C1_ESCAPED=r={}))},7399:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateKeyboardEvent=void 0;const s=i(2584),r={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};t.evaluateKeyboardEvent=function(e,t,i,n){const o={type:0,cancel:!1,key:void 0},a=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?o.key=t?s.C0.ESC+"OA":s.C0.ESC+"[A":"UIKeyInputLeftArrow"===e.key?o.key=t?s.C0.ESC+"OD":s.C0.ESC+"[D":"UIKeyInputRightArrow"===e.key?o.key=t?s.C0.ESC+"OC":s.C0.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(o.key=t?s.C0.ESC+"OB":s.C0.ESC+"[B");break;case 8:o.key=e.ctrlKey?"\b":s.C0.DEL,e.altKey&&(o.key=s.C0.ESC+o.key);break;case 9:if(e.shiftKey){o.key=s.C0.ESC+"[Z";break}o.key=s.C0.HT,o.cancel=!0;break;case 13:o.key=e.altKey?s.C0.ESC+s.C0.CR:s.C0.CR,o.cancel=!0;break;case 27:o.key=s.C0.ESC,e.altKey&&(o.key=s.C0.ESC+s.C0.ESC),o.cancel=!0;break;case 37:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"D",o.key===s.C0.ESC+"[1;3D"&&(o.key=s.C0.ESC+(i?"b":"[1;5D"))):o.key=t?s.C0.ESC+"OD":s.C0.ESC+"[D";break;case 39:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"C",o.key===s.C0.ESC+"[1;3C"&&(o.key=s.C0.ESC+(i?"f":"[1;5C"))):o.key=t?s.C0.ESC+"OC":s.C0.ESC+"[C";break;case 38:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"A",i||o.key!==s.C0.ESC+"[1;3A"||(o.key=s.C0.ESC+"[1;5A")):o.key=t?s.C0.ESC+"OA":s.C0.ESC+"[A";break;case 40:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"B",i||o.key!==s.C0.ESC+"[1;3B"||(o.key=s.C0.ESC+"[1;5B")):o.key=t?s.C0.ESC+"OB":s.C0.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(o.key=s.C0.ESC+"[2~");break;case 46:o.key=a?s.C0.ESC+"[3;"+(a+1)+"~":s.C0.ESC+"[3~";break;case 36:o.key=a?s.C0.ESC+"[1;"+(a+1)+"H":t?s.C0.ESC+"OH":s.C0.ESC+"[H";break;case 35:o.key=a?s.C0.ESC+"[1;"+(a+1)+"F":t?s.C0.ESC+"OF":s.C0.ESC+"[F";break;case 33:e.shiftKey?o.type=2:e.ctrlKey?o.key=s.C0.ESC+"[5;"+(a+1)+"~":o.key=s.C0.ESC+"[5~";break;case 34:e.shiftKey?o.type=3:e.ctrlKey?o.key=s.C0.ESC+"[6;"+(a+1)+"~":o.key=s.C0.ESC+"[6~";break;case 112:o.key=a?s.C0.ESC+"[1;"+(a+1)+"P":s.C0.ESC+"OP";break;case 113:o.key=a?s.C0.ESC+"[1;"+(a+1)+"Q":s.C0.ESC+"OQ";break;case 114:o.key=a?s.C0.ESC+"[1;"+(a+1)+"R":s.C0.ESC+"OR";break;case 115:o.key=a?s.C0.ESC+"[1;"+(a+1)+"S":s.C0.ESC+"OS";break;case 116:o.key=a?s.C0.ESC+"[15;"+(a+1)+"~":s.C0.ESC+"[15~";break;case 117:o.key=a?s.C0.ESC+"[17;"+(a+1)+"~":s.C0.ESC+"[17~";break;case 118:o.key=a?s.C0.ESC+"[18;"+(a+1)+"~":s.C0.ESC+"[18~";break;case 119:o.key=a?s.C0.ESC+"[19;"+(a+1)+"~":s.C0.ESC+"[19~";break;case 120:o.key=a?s.C0.ESC+"[20;"+(a+1)+"~":s.C0.ESC+"[20~";break;case 121:o.key=a?s.C0.ESC+"[21;"+(a+1)+"~":s.C0.ESC+"[21~";break;case 122:o.key=a?s.C0.ESC+"[23;"+(a+1)+"~":s.C0.ESC+"[23~";break;case 123:o.key=a?s.C0.ESC+"[24;"+(a+1)+"~":s.C0.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(i&&!n||!e.altKey||e.metaKey)!i||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?o.key=e.key:e.key&&e.ctrlKey&&("_"===e.key&&(o.key=s.C0.US),"@"===e.key&&(o.key=s.C0.NUL)):65===e.keyCode&&(o.type=1);else{const t=r[e.keyCode],i=t?.[e.shiftKey?1:0];if(i)o.key=s.C0.ESC+i;else if(e.keyCode>=65&&e.keyCode<=90){const t=e.ctrlKey?e.keyCode-64:e.keyCode+32;let i=String.fromCharCode(t);e.shiftKey&&(i=i.toUpperCase()),o.key=s.C0.ESC+i}else if(32===e.keyCode)o.key=s.C0.ESC+(e.ctrlKey?s.C0.NUL:" ");else if("Dead"===e.key&&e.code.startsWith("Key")){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),o.key=s.C0.ESC+t,o.cancel=!0}}else e.keyCode>=65&&e.keyCode<=90?o.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?o.key=s.C0.NUL:e.keyCode>=51&&e.keyCode<=55?o.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?o.key=s.C0.DEL:219===e.keyCode?o.key=s.C0.ESC:220===e.keyCode?o.key=s.C0.FS:221===e.keyCode&&(o.key=s.C0.GS)}return o}},482:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=t.utf32ToString=t.stringFromCodePoint=void 0,t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t=0,i=e.length){let s="";for(let r=t;r65535?(t-=65536,s+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):s+=String.fromCharCode(t)}return s},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){const i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){const i=e.charCodeAt(r++);56320<=i&&i<=57343?t[s++]=1024*(this._interim-55296)+i-56320+65536:(t[s++]=this._interim,t[s++]=i),this._interim=0}for(let n=r;n=i)return this._interim=r,s;const o=e.charCodeAt(n);56320<=o&&o<=57343?t[s++]=1024*(r-55296)+o-56320+65536:(t[s++]=r,t[s++]=o)}else 65279!==r&&(t[s++]=r)}return s}},t.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){const i=e.length;if(!i)return 0;let s,r,n,o,a=0,h=0,c=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let n,o=0;for(;(n=63&this.interim[++o])&&o<4;)r<<=6,r|=n;const h=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,l=h-o;for(;c=i)return 0;if(n=e[c++],128!=(192&n)){c--,s=!0;break}this.interim[o++]=n,r<<=6,r|=63&n}s||(2===h?r<128?c--:t[a++]=r:3===h?r<2048||r>=55296&&r<=57343||65279===r||(t[a++]=r):r<65536||r>1114111||(t[a++]=r)),this.interim.fill(0)}const l=i-4;let d=c;for(;d=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(h=(31&s)<<6|63&r,h<128){d--;continue}t[a++]=h}else if(224==(240&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(h=(15&s)<<12|(63&r)<<6|63&n,h<2048||h>=55296&&h<=57343||65279===h)continue;t[a++]=h}else if(240==(248&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=n,a;if(o=e[d++],128!=(192&o)){d--;continue}if(h=(7&s)<<18|(63&r)<<12|(63&n)<<6|63&o,h<65536||h>1114111)continue;t[a++]=h}}return a}}},225:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeV6=void 0;const s=i(1480),r=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],n=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let o;t.UnicodeV6=class{constructor(){if(this.version="6",!o){o=new Uint8Array(65536),o.fill(1),o[0]=0,o.fill(0,1,32),o.fill(0,127,160),o.fill(2,4352,4448),o[9001]=2,o[9002]=2,o.fill(2,11904,42192),o[12351]=1,o.fill(2,44032,55204),o.fill(2,63744,64256),o.fill(2,65040,65050),o.fill(2,65072,65136),o.fill(2,65280,65377),o.fill(2,65504,65511);for(let e=0;et[r][1])return!1;for(;r>=s;)if(i=s+r>>1,e>t[i][1])s=i+1;else{if(!(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),r=0===i&&0!==t;if(r){const e=s.UnicodeService.extractWidth(t);0===e?r=!1:e>i&&(i=e)}return s.UnicodeService.createPropertyValue(0,i,r)}}},5981:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WriteBuffer=void 0;const s=i(8460),r=i(844);class n extends r.Disposable{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new s.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(void 0!==t&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let i;for(this._isSyncWriting=!0;i=this._writeBuffer.shift();){this._action(i);const e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){const i=e||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const e=this._writeBuffer[this._bufferOffset],s=this._action(e,t);if(s){const e=e=>Date.now()-i>=12?setTimeout((()=>this._innerWrite(0,e))):this._innerWrite(i,e);return void s.catch((e=>(queueMicrotask((()=>{throw e})),Promise.resolve(!1)))).then(e)}const r=this._callbacks[this._bufferOffset];if(r&&r(),this._bufferOffset++,this._pendingData-=e.length,Date.now()-i>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=n},5941:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toRgbString=t.parseColor=void 0;const i=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,s=/^[\da-f]+$/;function r(e,t){const i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}t.parseColor=function(e){if(!e)return;let t=e.toLowerCase();if(0===t.indexOf("rgb:")){t=t.slice(4);const e=i.exec(t);if(e){const t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(0===t.indexOf("#")&&(t=t.slice(1),s.exec(t)&&[3,6,9,12].includes(t.length))){const e=t.length/3,i=[0,0,0];for(let s=0;s<3;++s){const r=parseInt(t.slice(e*s,e*s+e),16);i[s]=1===e?r<<4:2===e?r:3===e?r>>4:r>>8}return i}},t.toRgbString=function(e,t=16){const[i,s,n]=e;return`rgb:${r(i,t)}/${r(s,t)}/${r(n,t)}`}},5770:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},6351:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DcsHandler=t.DcsParser=void 0;const s=i(482),r=i(8742),n=i(5770),o=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);const i=this._handlers[e];return i.push(t),{dispose:()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=o,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t);else this._handlerFb(this._ident,"HOOK",t)}put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._ident,"PUT",(0,s.utf32ToString)(e,t,i))}unhook(e,t=!0){if(this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].unhook(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._ident,"UNHOOK",e);this._active=o,this._ident=0}};const a=new r.Params;a.addParam(0),t.DcsHandler=class{constructor(e){this._handler=e,this._data="",this._params=a,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():a,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=(0,s.utf32ToString)(e,t,i),this._data.length>n.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then((e=>(this._params=a,this._data="",this._hitLimit=!1,e)));return this._params=a,this._data="",this._hitLimit=!1,t}}},2015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;const s=i(844),r=i(8742),n=i(6242),o=i(6351);class a{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;rt)),i=(e,i)=>t.slice(e,i),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));const n=i(0,14);let o;for(o in e.setDefault(1,0),e.addMany(s,0,2,0),n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(h,0,2,0),e.add(h,8,5,8),e.add(h,6,0,6),e.add(h,11,0,11),e.add(h,13,13,13),e}();class c extends s.Disposable{constructor(e=t.VT500_TRANSITION_TABLE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new r.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,i)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,s.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new n.OscParser),this._dcsParser=this.register(new o.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let t=0;ts||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=s}}if(1!==e.final.length)throw new Error("final must be a single byte");const s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){const t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){const i=this._identifier(e,[48,126]);void 0===this._escHandlers[i]&&(this._escHandlers[i]=[]);const s=this._escHandlers[i];return s.push(t),{dispose:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){const i=this._identifier(e);void 0===this._csiHandlers[i]&&(this._csiHandlers[i]=[]);const s=this._csiHandlers[i];return s.push(t),{dispose:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,0!==this._parseStack.state&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s,r=0,n=0,o=0;if(this._parseStack.state)if(2===this._parseStack.state)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(void 0===i||1===this._parseStack.state)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const t=this._parseStack.handlers;let n=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](this._params),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 4:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],s=this._dcsParser.unhook(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],s=this._oscParser.end(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let i=o;i>4){case 2:for(let s=i+1;;++s){if(s>=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=0&&(s=o[a](this._params),!0!==s);a--)if(s instanceof Promise)return this._preserveStack(3,o,a,n,i),s;a<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do{switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}}while(++i47&&r<60);i--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:const c=this._escHandlers[this._collect<<8|r];let l=c?c.length-1:-1;for(;l>=0&&(s=c[l](),!0!==s);l--)if(s instanceof Promise)return this._preserveStack(4,c,l,n,i),s;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let s=i+1;;++s)if(s>=t||24===(r=e[s])||26===r||27===r||r>127&&r=t||(r=e[s])<32||r>127&&r{Object.defineProperty(t,"__esModule",{value:!0}),t.OscHandler=t.OscParser=void 0;const s=i(5770),r=i(482),n=[];t.OscParser=class{constructor(){this._state=0,this._active=n,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);const i=this._handlers[e];return i.push(t),{dispose:()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=n}reset(){if(2===this._state)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=n,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||n,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,"START")}_put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._id,"PUT",(0,r.utf32ToString)(e,t,i))}start(){this.reset(),this._state=1}put(e,t,i){if(3!==this._state){if(1===this._state)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(0!==this._state){if(3!==this._state)if(1===this._state&&this._start(),this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].end(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._id,"END",e);this._active=n,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=(0,r.utf32ToString)(e,t,i),this._data.length>s.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then((e=>(this._data="",this._hitLimit=!1,e)));return this._data="",this._hitLimit=!1,t}}},8742:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Params=void 0;const i=2147483647;class s{static fromArray(e){const t=new s;if(!e.length)return t;for(let i=Array.isArray(e[0])?1:0;i256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const e=new s(this.maxLength,this.maxSubParamsLength);return e.params.set(this.params),e.length=this.length,e._subParams.set(this._subParams),e._subParamsLength=this._subParamsLength,e._subParamsIdx.set(this._subParamsIdx),e._rejectDigits=this._rejectDigits,e._rejectSubDigits=this._rejectSubDigits,e._digitIsSub=this._digitIsSub,e}toArray(){const e=[];for(let t=0;t>8,s=255&this._subParamsIdx[t];s-i>0&&e.push(Array.prototype.slice.call(this._subParams,i,s))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>i?i:e}}addSubParam(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>i?i:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){const t=this._subParamsIdx[e]>>8,i=255&this._subParamsIdx[e];return i-t>0?this._subParams.subarray(t,i):null}getSubParamsAll(){const e={};for(let t=0;t>8,s=255&this._subParamsIdx[t];s-i>0&&(e[t]=this._subParams.slice(i,s))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const s=this._digitIsSub?this._subParams:this.params,r=s[t-1];s[t-1]=~r?Math.min(10*r+e,i):e}}t.Params=s},5741:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){const i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferApiView=void 0;const s=i(3785),r=i(511);t.BufferApiView=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){const t=this._buffer.lines.get(e);if(t)return new s.BufferLineApiView(t)}getNullCell(){return new r.CellData}}},3785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLineApiView=void 0;const s=i(511);t.BufferLineApiView=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new s.CellData)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}}},8285:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferNamespaceApi=void 0;const s=i(8771),r=i(8460),n=i(844);class o extends n.Disposable{constructor(e){super(),this._core=e,this._onBufferChange=this.register(new r.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new s.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new s.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=o},7975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,(e=>t(e.toArray())))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,((e,i)=>t(e,i.toArray())))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}}},7090:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}}},744:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;const n=i(8460),o=i(844),a=i(5295),h=i(2585);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let c=t.BufferService=class extends o.Disposable{get buffer(){return this.buffers.active}constructor(e){super(),this.isUserScrolling=!1,this._onResize=this.register(new n.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new n.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(e.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this.register(new a.BufferSet(e,this))}resize(e,t){this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){const i=this.buffer;let s;s=this._cachedBlankLine,s&&s.length===this.cols&&s.getFg(0)===e.fg&&s.getBg(0)===e.bg||(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;const r=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(0===i.scrollTop){const e=i.lines.isFull;n===i.lines.length-1?e?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(n+1,0,s.clone()),e?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{const e=n-r+1;i.lines.shiftElements(r+1,e-1,-1),i.lines.set(n,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t,i){const s=this.buffer;if(e<0){if(0===s.ydisp)return;this.isUserScrolling=!0}else e+s.ydisp>=s.ybase&&(this.isUserScrolling=!1);const r=s.ydisp;s.ydisp=Math.max(Math.min(s.ydisp+e,s.ybase),0),r!==s.ydisp&&(t||this._onScroll.fire(s.ydisp))}};t.BufferService=c=s([r(0,h.IOptionsService)],c)},7994:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}}},1753:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreMouseService=void 0;const n=i(2585),o=i(8460),a=i(844),h={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>32!==e.action},DRAG:{events:23,restrict:e=>32!==e.action||3!==e.button},ANY:{events:31,restrict:e=>!0}};function c(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(i|=64,i|=e.action):(i|=3&e.button,4&e.button&&(i|=64),8&e.button&&(i|=128),32===e.action?i|=32:0!==e.action||t||(i|=3)),i}const l=String.fromCharCode,d={DEFAULT:e=>{const t=[c(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`${l(t[0])}${l(t[1])}${l(t[2])}`},SGR:e=>{const t=0===e.action&&4!==e.button?"m":"M";return`[<${c(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{const t=0===e.action&&4!==e.button?"m":"M";return`[<${c(e,!0)};${e.x};${e.y}${t}`}};let _=t.CoreMouseService=class extends a.Disposable{constructor(e,t){super(),this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new o.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const e of Object.keys(h))this.addProtocol(e,h[e]);for(const e of Object.keys(d))this.addEncoding(e,d[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return 0!==this._protocols[this._activeProtocol].events}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows)return!1;if(4===e.button&&32===e.action)return!1;if(3===e.button&&32!==e.action)return!1;if(4!==e.button&&(2===e.action||3===e.action))return!1;if(e.col++,e.row++,32===e.action&&this._lastEvent&&this._equalEvents(this._lastEvent,e,"SGR_PIXELS"===this._activeEncoding))return!1;if(!this._protocols[this._activeProtocol].restrict(e))return!1;const t=this._encodings[this._activeEncoding](e);return t&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x)return!1;if(e.y!==t.y)return!1}else{if(e.col!==t.col)return!1;if(e.row!==t.row)return!1}return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};t.CoreMouseService=_=s([r(0,n.IBufferService),r(1,n.ICoreService)],_)},6975:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreService=void 0;const n=i(1439),o=i(8460),a=i(844),h=i(2585),c=Object.freeze({insertMode:!1}),l=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let d=t.CoreService=class extends a.Disposable{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new o.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new o.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new o.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new o.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,n.clone)(c),this.decPrivateModes=(0,n.clone)(l)}reset(){this.modes=(0,n.clone)(c),this.decPrivateModes=(0,n.clone)(l)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;const i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`,(()=>e.split("").map((e=>e.charCodeAt(0))))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`,(()=>e.split("").map((e=>e.charCodeAt(0))))),this._onBinary.fire(e))}};t.CoreService=d=s([r(0,h.IBufferService),r(1,h.ILogService),r(2,h.IOptionsService)],d)},9074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DecorationService=void 0;const s=i(8055),r=i(8460),n=i(844),o=i(6106);let a=0,h=0;class c extends n.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new o.SortedList((e=>e?.marker.line)),this._onDecorationRegistered=this.register(new r.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new r.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,n.toDisposable)((()=>this.reset())))}registerDecoration(e){if(e.marker.isDisposed)return;const t=new l(e);if(t){const e=t.marker.onDispose((()=>t.dispose()));t.onDispose((()=>{t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())})),this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(const e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,r=0;for(const n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e{a=t.options.x??0,h=a+(t.options.width??1),e>=a&&e{Object.defineProperty(t,"__esModule",{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;const s=i(2585),r=i(8343);class n{constructor(...e){this._entries=new Map;for(const[t,i]of e)this.set(t,i)}set(e,t){const i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(const[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}}t.ServiceCollection=n,t.InstantiationService=class{constructor(){this._services=new n,this._services.set(s.IInstantiationService,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){const i=(0,r.getServiceDependencies)(e).sort(((e,t)=>e.index-t.index)),s=[];for(const t of i){const i=this._services.get(t.id);if(!i)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id}.`);s.push(i)}const n=i.length>0?i[0].index:t.length;if(t.length!==n)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${n+1} conflicts with ${t.length} static arguments`);return new e(...[...t,...s])}}},7866:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.traceCall=t.setTraceLogger=t.LogService=void 0;const n=i(844),o=i(2585),a={trace:o.LogLevelEnum.TRACE,debug:o.LogLevelEnum.DEBUG,info:o.LogLevelEnum.INFO,warn:o.LogLevelEnum.WARN,error:o.LogLevelEnum.ERROR,off:o.LogLevelEnum.OFF};let h,c=t.LogService=class extends n.Disposable{get logLevel(){return this._logLevel}constructor(e){super(),this._optionsService=e,this._logLevel=o.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),h=this}_updateLogLevel(){this._logLevel=a[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tJSON.stringify(e))).join(", ")})`);const t=s.apply(this,e);return h.trace(`GlyphRenderer#${s.name} return`,t),t}}},7302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;const s=i(8460),r=i(844),n=i(6114);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:n.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const o=["normal","bold","100","200","300","400","500","600","700","800","900"];class a extends r.Disposable{constructor(e){super(),this._onOptionChange=this.register(new s.EventEmitter),this.onOptionChange=this._onOptionChange.event;const i={...t.DEFAULT_OPTIONS};for(const t in e)if(t in i)try{const s=e[t];i[t]=this._sanitizeAndValidateOption(t,s)}catch(e){console.error(e)}this.rawOptions=i,this.options={...i},this._setupOptions(),this.register((0,r.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(e,t){return this.onOptionChange((i=>{i===e&&t(this.rawOptions[e])}))}onMultipleOptionChange(e,t){return this.onOptionChange((i=>{-1!==e.indexOf(i)&&t()}))}_setupOptions(){const e=e=>{if(!(e in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${e}"`);return this.rawOptions[e]},i=(e,i)=>{if(!(e in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${e}"`);i=this._sanitizeAndValidateOption(e,i),this.rawOptions[e]!==i&&(this.rawOptions[e]=i,this._onOptionChange.fire(e))};for(const t in this.rawOptions){const s={get:e.bind(this,t),set:i.bind(this,t)};Object.defineProperty(this.options,t,s)}}_sanitizeAndValidateOption(e,i){switch(e){case"cursorStyle":if(i||(i=t.DEFAULT_OPTIONS[e]),!function(e){return"block"===e||"underline"===e||"bar"===e}(i))throw new Error(`"${i}" is not a valid value for ${e}`);break;case"wordSeparator":i||(i=t.DEFAULT_OPTIONS[e]);break;case"fontWeight":case"fontWeightBold":if("number"==typeof i&&1<=i&&i<=1e3)break;i=o.includes(i)?i:t.DEFAULT_OPTIONS[e];break;case"cursorWidth":i=Math.floor(i);case"lineHeight":case"tabStopWidth":if(i<1)throw new Error(`${e} cannot be less than 1, value: ${i}`);break;case"minimumContrastRatio":i=Math.max(1,Math.min(21,Math.round(10*i)/10));break;case"scrollback":if((i=Math.min(i,4294967295))<0)throw new Error(`${e} cannot be less than 0, value: ${i}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(i<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${i}`);break;case"rows":case"cols":if(!i&&0!==i)throw new Error(`${e} must be numeric, value: ${i}`);break;case"windowsPty":i=i??{}}return i}}t.OptionsService=a},2660:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkService=void 0;const n=i(2585);let o=t.OscLinkService=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){const t=this._bufferService.buffer;if(void 0===e.id){const i=t.addMarker(t.ybase+t.y),s={data:e,id:this._nextId++,lines:[i]};return i.onDispose((()=>this._removeMarkerFromLink(s,i))),this._dataByLinkId.set(s.id,s),s.id}const i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;const n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose((()=>this._removeMarkerFromLink(o,n))),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){const i=this._dataByLinkId.get(e);if(i&&i.lines.every((e=>e.line!==t))){const e=this._bufferService.buffer.addMarker(t);i.lines.push(e),e.onDispose((()=>this._removeMarkerFromLink(i,e)))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){const i=e.lines.indexOf(t);-1!==i&&(e.lines.splice(i,1),0===e.lines.length&&(void 0!==e.data.id&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};t.OscLinkService=o=s([r(0,n.IBufferService)],o)},8343:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;const i="di$target",s="di$dependencies";t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[s]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);const r=function(e,t,n){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");!function(e,t,r){t[i]===t?t[s].push({id:e,index:r}):(t[s]=[{id:e,index:r}],t[i]=t)}(r,e,n)};return r.toString=()=>e,t.serviceRegistry.set(e,r),r}},2585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;const s=i(8343);var r;t.IBufferService=(0,s.createDecorator)("BufferService"),t.ICoreMouseService=(0,s.createDecorator)("CoreMouseService"),t.ICoreService=(0,s.createDecorator)("CoreService"),t.ICharsetService=(0,s.createDecorator)("CharsetService"),t.IInstantiationService=(0,s.createDecorator)("InstantiationService"),function(e){e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.OFF=5]="OFF"}(r||(t.LogLevelEnum=r={})),t.ILogService=(0,s.createDecorator)("LogService"),t.IOptionsService=(0,s.createDecorator)("OptionsService"),t.IOscLinkService=(0,s.createDecorator)("OscLinkService"),t.IUnicodeService=(0,s.createDecorator)("UnicodeService"),t.IDecorationService=(0,s.createDecorator)("DecorationService")},1480:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeService=void 0;const s=i(8460),r=i(225);class n{static extractShouldJoin(e){return!!(1&e)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,i=!1){return(16777215&e)<<3|(3&t)<<1|(i?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new s.EventEmitter,this.onChange=this._onChange.event;const e=new r.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw new Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0,i=0;const s=e.length;for(let r=0;r=s)return t+this.wcwidth(o);const i=e.charCodeAt(r);56320<=i&&i<=57343?o=1024*(o-55296)+i-56320+65536:t+=this.wcwidth(i)}const a=this.charProperties(o,i);let h=n.extractWidth(a);n.extractShouldJoin(a)&&(h-=n.extractWidth(i)),t+=h,i=a}return t}charProperties(e,t){return this._activeProvider.charProperties(e,t)}}t.UnicodeService=n}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s].call(n.exports,n,n.exports,i),n.exports}var s={};return(()=>{var e=s;Object.defineProperty(e,"__esModule",{value:!0}),e.Terminal=void 0;const t=i(9042),r=i(3236),n=i(844),o=i(5741),a=i(8285),h=i(7975),c=i(7090),l=["cols","rows"];class d extends n.Disposable{constructor(e){super(),this._core=this.register(new r.Terminal(e)),this._addonManager=this.register(new o.AddonManager),this._publicOptions={...this._core.options};const t=e=>this._core.options[e],i=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(const e in this._core.options){const s={get:t.bind(this,e),set:i.bind(this,e)};Object.defineProperty(this._publicOptions,e,s)}}_checkReadonlyOptions(e){if(l.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new h.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new c.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new a.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const e=this._core.coreService.decPrivateModes;let t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any"}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(const t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write("\r\n",t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return t}_verifyIntegers(...e){for(const t of e)if(t===1/0||isNaN(t)||t%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(const t of e)if(t&&(t===1/0||isNaN(t)||t%1!=0||t<0))throw new Error("This API only accepts positive integers")}}e.Terminal=d})(),s})())(),D=k.exports.Terminal,R=k.exports.__esModule;export{D as Terminal,R as __esModule,L as default}; diff --git a/core/src/3rd-party/xterm_addon-fit.js b/core/src/3rd-party/xterm_addon-fit.js new file mode 100644 index 00000000000..6fad4c1ef1e --- /dev/null +++ b/core/src/3rd-party/xterm_addon-fit.js @@ -0,0 +1,7 @@ +/** + * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0. + * Original file: /npm/@xterm/addon-fit@0.10.0/lib/addon-fit.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +var e,t,r={exports:{}};self;var s=r.exports=(e=t={},Object.defineProperty(e,"__esModule",{value:!0}),e.FitAddon=void 0,e.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core,t=e._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;const r=0===this._terminal.options.scrollback?0:e.viewport.scrollBarWidth,s=window.getComputedStyle(this._terminal.element.parentElement),i=parseInt(s.getPropertyValue("height")),o=Math.max(0,parseInt(s.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),l=i-(parseInt(n.getPropertyValue("padding-top"))+parseInt(n.getPropertyValue("padding-bottom"))),a=o-(parseInt(n.getPropertyValue("padding-right"))+parseInt(n.getPropertyValue("padding-left")))-r;return{cols:Math.max(2,Math.floor(a/t.css.cell.width)),rows:Math.max(1,Math.floor(l/t.css.cell.height))}}},t),i=r.exports.FitAddon,o=r.exports.__esModule;export{i as FitAddon,o as __esModule,s as default}; diff --git a/core/src/3rd-party/xterm_addon-web-links.js b/core/src/3rd-party/xterm_addon-web-links.js new file mode 100644 index 00000000000..ee1cffdb311 --- /dev/null +++ b/core/src/3rd-party/xterm_addon-web-links.js @@ -0,0 +1,7 @@ +/** + * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0. + * Original file: /npm/@xterm/addon-web-links@0.11.0/lib/addon-web-links.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +var e={exports:{}};self;var t=e.exports=(()=>{var e={6:(e,t)=>{function r(e){try{const t=new URL(e),r=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(r.toLocaleLowerCase())}catch(e){return!1}}Object.defineProperty(t,"__esModule",{value:!0}),t.LinkComputer=t.WebLinkProvider=void 0,t.WebLinkProvider=class{constructor(e,t,r,n={}){this._terminal=e,this._regex=t,this._handler=r,this._options=n}provideLinks(e,t){const r=n.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(r))}_addCallbacks(e){return e.map((e=>(e.leave=this._options.leave,e.hover=(t,r)=>{if(this._options.hover){const{range:n}=e;this._options.hover(t,r,n)}},e)))}};class n{static computeLink(e,t,o,s){const i=new RegExp(t.source,(t.flags||"")+"g"),[a,l]=n._getWindowedLineStrings(e-1,o),c=a.join("");let d;const p=[];for(;d=i.exec(c);){const e=d[0];if(!r(e))continue;const[t,i]=n._mapStrIdx(o,l,0,d.index),[a,c]=n._mapStrIdx(o,t,i,e.length);if(-1===t||-1===i||-1===a||-1===c)continue;const h={start:{x:i+1,y:t+1},end:{x:c,y:a+1}};p.push({range:h,text:e,activate:s})}return p}static _getWindowedLineStrings(e,t){let r,n=e,o=e,s=0,i="";const a=[];if(r=t.buffer.active.getLine(e)){const e=r.translateToString(!0);if(r.isWrapped&&" "!==e[0]){for(s=0;(r=t.buffer.active.getLine(--n))&&s<2048&&(i=r.translateToString(!0),s+=i.length,a.push(i),r.isWrapped&&-1===i.indexOf(" ")););a.reverse()}for(a.push(e),s=0;(r=t.buffer.active.getLine(++o))&&r.isWrapped&&s<2048&&(i=r.translateToString(!0),s+=i.length,a.push(i),-1===i.indexOf(" ")););}return[a,n]}static _mapStrIdx(e,t,r,n){const o=e.buffer.active,s=o.getNullCell();let i=r;for(;n;){const e=o.getLine(t);if(!e)return[-1,-1];for(let r=i;r{var e=n;Object.defineProperty(e,"__esModule",{value:!0}),e.WebLinksAddon=void 0;const t=r(6),o=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function s(e,t){const r=window.open();if(r){try{r.opener=null}catch{}r.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}e.WebLinksAddon=class{constructor(e=s,t={}){this._handler=e,this._options=t}activate(e){this._terminal=e;const r=this._options,n=r.urlRegex||o;this._linkProvider=this._terminal.registerLinkProvider(new t.WebLinkProvider(this._terminal,n,this._handler,r))}dispose(){this._linkProvider?.dispose()}}})(),n})(),r=e.exports.WebLinksAddon,n=e.exports.__esModule;export{r as WebLinksAddon,n as __esModule,t as default}; diff --git a/core/src/all-done.js b/core/src/all-done.js new file mode 100644 index 00000000000..c1b1e23f903 --- /dev/null +++ b/core/src/all-done.js @@ -0,0 +1,18 @@ +import withResolvers from "@webreflection/utils/with-resolvers"; +import TYPES from "./types.js"; + +const waitForIt = []; + +for (const [TYPE] of TYPES) { + const selectors = [`script[type="${TYPE}"]`, `${TYPE}-script`]; + for (const element of document.querySelectorAll(selectors.join(","))) { + const { promise, resolve } = withResolvers(); + waitForIt.push(promise); + element.addEventListener(`${TYPE}:done`, resolve, { once: true }); + } +} + +// wait for all the things then cleanup +Promise.all(waitForIt).then(() => { + dispatchEvent(new Event("py:all-done")); +}); diff --git a/core/src/config.js b/core/src/config.js new file mode 100644 index 00000000000..b7ed1338ef2 --- /dev/null +++ b/core/src/config.js @@ -0,0 +1,160 @@ +/** + * This file parses a generic or config attribute + * to use as base config for all py-script elements, importing + * also a queue of plugins *before* the interpreter (if any) resolves. + */ +import { $$ } from "basic-devtools"; + +import TYPES from "./types.js"; +import allPlugins from "./plugins.js"; +import { robustFetch as fetch, getText } from "./fetch.js"; +import { ErrorCode } from "./exceptions.js"; + +const { BAD_CONFIG, CONFLICTING_CODE } = ErrorCode; + +const badURL = (url, expected = "") => { + let message = `(${BAD_CONFIG}): Invalid URL: ${url}`; + if (expected) message += `\nexpected ${expected} content`; + throw new Error(message); +}; + +/** + * Given a string, returns its trimmed content as text, + * fetching it from a file if the content is a URL. + * @param {string} config either JSON, TOML, or a file to fetch + * @param {string?} type the optional type to enforce + * @returns {{json: boolean, toml: boolean, text: string}} + */ +export const configDetails = async (config, type) => { + let text = config?.trim(); + // we only support an object as root config + let url = "", + toml = false, + json = /^{/.test(text) && /}$/.test(text); + // handle files by extension (relaxing urls parts after) + if (!json && /\.(\w+)(?:\?\S*)?$/.test(text)) { + const ext = RegExp.$1; + if (ext === "json" && type !== "toml") json = true; + else if (ext === "toml" && type !== "json") toml = true; + else badURL(text, type); + url = text; + text = (await fetch(url).then(getText)).trim(); + } + return { json, toml: toml || (!json && !!text), text, url }; +}; + +const conflictError = (reason) => new Error(`(${CONFLICTING_CODE}): ${reason}`); + +const relative_url = (url, base = location.href) => new URL(url, base).href; + +const syntaxError = (type, url, { message }) => { + let str = `(${BAD_CONFIG}): Invalid ${type}`; + if (url) str += ` @ ${url}`; + return new SyntaxError(`${str}\n${message}`); +}; + +const configs = new Map(); + +for (const [TYPE] of TYPES) { + /** @type {() => Promise<[...any]>} A Promise wrapping any plugins which should be loaded. */ + let plugins; + + /** @type {any} The PyScript configuration parsed from the JSON or TOML object*. May be any of the return types of JSON.parse() or toml-j0.4's parse() ( {number | string | boolean | null | object | Array} ) */ + let parsed; + + /** @type {Error | undefined} The error thrown when parsing the PyScript config, if any.*/ + let error; + + /** @type {string | undefined} The `configURL` field to normalize all config operations as opposite of guessing it once resolved */ + let configURL; + + let config, + type, + pyElement, + pyConfigs = $$(`${TYPE}-config`), + attrConfigs = $$( + [ + `script[type="${TYPE}"][config]:not([worker])`, + `${TYPE}-script[config]:not([worker])`, + ].join(","), + ); + + // throw an error if there are multiple or + if (pyConfigs.length > 1) { + error = conflictError(`Too many ${TYPE}-config`); + } else { + // throw an error if there are and config="x" attributes + if (pyConfigs.length && attrConfigs.length) { + error = conflictError( + `Ambiguous ${TYPE}-config VS config attribute`, + ); + } else if (pyConfigs.length) { + [pyElement] = pyConfigs; + config = pyElement.getAttribute("src") || pyElement.textContent; + type = pyElement.getAttribute("type"); + } else if (attrConfigs.length) { + [pyElement, ...attrConfigs] = attrConfigs; + config = pyElement.getAttribute("config"); + // throw an error if dirrent scripts use different configs + if ( + attrConfigs.some((el) => el.getAttribute("config") !== config) + ) { + error = conflictError( + "Unable to use different configs on main", + ); + } + } + } + + // catch possible fetch errors + if (!error && config) { + try { + const { json, toml, text, url } = await configDetails(config, type); + if (url) configURL = relative_url(url); + config = text; + if (json || type === "json") { + try { + parsed = JSON.parse(text); + } catch (e) { + error = syntaxError("JSON", url, e); + } + } else if (toml || type === "toml") { + try { + const { parse } = await import( + /* webpackIgnore: true */ "./3rd-party/toml.js" + ); + parsed = parse(text); + } catch (e) { + error = syntaxError("TOML", url, e); + } + } + } catch (e) { + error = e; + } + } + + // parse all plugins and optionally ignore only + // those flagged as "undesired" via `!` prefix + plugins = async () => { + const toBeAwaited = []; + for (const [key, value] of Object.entries(allPlugins)) { + if (error) { + if (key === "error") { + // show on page the config is broken, meaning that + // it was not possible to disable error plugin neither + // as that part wasn't correctly parsed anyway + value().then(({ notify }) => notify(error.message)); + } + } else if (!parsed?.plugins?.includes(`!${key}`)) { + toBeAwaited.push(value().then(({ default: p }) => p)); + } else if (key === "error") { + toBeAwaited.push(value().then(({ notOnDOM }) => notOnDOM())); + } + } + return await Promise.all(toBeAwaited); + }; + + configs.set(TYPE, { config: parsed, configURL, plugins, error }); +} + +export { configs, relative_url }; diff --git a/core/src/core.css b/core/src/core.css new file mode 100644 index 00000000000..7fb91da8ad5 --- /dev/null +++ b/core/src/core.css @@ -0,0 +1,61 @@ +py-script, +py-config, +mpy-script, +mpy-config { + display: none; +} + +/* PyEditor */ +.py-editor-box, +.mpy-editor-box { + padding: 0.5rem; +} +.py-editor-input, +.mpy-editor-input { + position: relative; +} +.py-editor-box::before, +.mpy-editor-box::before { + content: attr(data-env); + display: block; + font-size: x-small; + text-align: end; +} +.py-editor-output, +.mpy-editor-output { + white-space: pre; +} +.py-editor-run-button, +.mpy-editor-run-button { + position: absolute; + display: flex; + right: 0.5rem; + bottom: 0.5rem; + opacity: 0; + transition: opacity 0.25s; + z-index: 1; + padding: 0; +} +.py-editor-box:hover .py-editor-run-button, +.mpy-editor-box:hover .mpy-editor-run-button, +.py-editor-run-button:focus, +.py-editor-run-button.running, +.mpy-editor-run-button:focus, +.mpy-editor-run-button.running { + opacity: 1; +} + +py-terminal span, +mpy-terminal span { + letter-spacing: 0 !important; +} + +dialog.pyscript-fs { + border-radius: 8px; + border-width: 1px; +} + +dialog.pyscript-fs > div { + display: flex; + justify-content: space-between; +} diff --git a/core/src/core.js b/core/src/core.js new file mode 100644 index 00000000000..3a167f961ac --- /dev/null +++ b/core/src/core.js @@ -0,0 +1,370 @@ +/*! (c) PyScript Development Team */ + +import "./zero-redirect.js"; +import stickyModule from "sticky-module"; +import withResolvers from "@webreflection/utils/with-resolvers"; + +import { + INVALID_CONTENT, + Hook, + XWorker, + assign, + dedent, + define, + defineProperty, + dispatch, + isSync, + queryTarget, + unescape, + whenDefined, +} from "polyscript/exports"; + +import "./all-done.js"; +import TYPES from "./types.js"; +import { configs, relative_url } from "./config.js"; +import sync from "./sync.js"; +import bootstrapNodeAndPlugins from "./plugins-helper.js"; +import { ErrorCode } from "./exceptions.js"; +import { robustFetch as fetch, getText } from "./fetch.js"; +import { + hooks, + main, + worker, + codeFor, + createFunction, + inputFailure, +} from "./hooks.js"; +import * as fs from "./fs.js"; + +import codemirror from "./plugins/codemirror.js"; +export { codemirror }; + +import { stdlib, optional } from "./stdlib.js"; +export { stdlib, optional, inputFailure }; + +export const donkey = (options) => + import(/* webpackIgnore: true */ "./plugins/donkey.js").then((module) => + module.default(options), + ); + +// generic helper to disambiguate between custom element and script +const isScript = ({ tagName }) => tagName === "SCRIPT"; + +// Used to create either Pyodide or MicroPython workers +// with the PyScript module available within the code +const [PyWorker, MPWorker] = [...TYPES.entries()].map( + ([TYPE, interpreter]) => + /** + * A `Worker` facade able to bootstrap on the worker thread only a PyScript module. + * @param {string} file the python file to run ina worker. + * @param {{config?: string | object, async?: boolean}} [options] optional configuration for the worker. + * @returns {Promise} + */ + async function PyScriptWorker(file, options) { + await configs.get(TYPE).plugins; + const xworker = XWorker.call( + new Hook(null, hooked.get(TYPE)), + file, + { + ...options, + type: interpreter, + }, + ); + assign(xworker.sync, sync); + return xworker.ready; + }, +); + +// avoid multiple initialization of the same library +const [ + { + PyWorker: exportedPyWorker, + MPWorker: exportedMPWorker, + hooks: exportedHooks, + config: exportedConfig, + whenDefined: exportedWhenDefined, + }, + alreadyLive, +] = stickyModule("@pyscript/core", { + PyWorker, + MPWorker, + hooks, + config: {}, + whenDefined, +}); + +export { + TYPES, + relative_url, + exportedPyWorker as PyWorker, + exportedMPWorker as MPWorker, + exportedHooks as hooks, + exportedConfig as config, + exportedWhenDefined as whenDefined, +}; + +export const offline_interpreter = (config) => + config?.interpreter && relative_url(config.interpreter); + +const hooked = new Map(); + +for (const [TYPE, interpreter] of TYPES) { + // avoid any dance if the module already landed + if (alreadyLive) break; + + const dispatchDone = (element, isAsync, result) => { + if (isAsync) result.then(() => dispatch(element, TYPE, "done")); + else dispatch(element, TYPE, "done"); + }; + + const { config, configURL, plugins, error } = configs.get(TYPE); + + // create a unique identifier when/if needed + let id = 0; + const getID = (prefix = TYPE) => `${prefix}-${id++}`; + + /** + * Given a generic DOM Element, tries to fetch the 'src' attribute, if present. + * It either throws an error if the 'src' can't be fetched or it returns a fallback + * content as source. + */ + const fetchSource = async (tag, io, asText) => { + if (tag.hasAttribute("src")) { + try { + return await fetch(tag.getAttribute("src")).then(getText); + } catch (error) { + io.stderr(error); + } + } + + if (asText) return dedent(tag.textContent); + + const code = dedent(unescape(tag.innerHTML)); + console.warn( + `Deprecated: use + + + + +

+
+
diff --git a/core/tests/javascript/config-url.html b/core/tests/javascript/config-url.html
new file mode 100644
index 00000000000..9f28969dd57
--- /dev/null
+++ b/core/tests/javascript/config-url.html
@@ -0,0 +1,25 @@
+
+
+
+  
+  
+  PyScript Next Plugin
+  
+  
+  
+  
+  
+
+
diff --git a/core/tests/javascript/config-url/config.json b/core/tests/javascript/config-url/config.json
new file mode 100644
index 00000000000..422aff92077
--- /dev/null
+++ b/core/tests/javascript/config-url/config.json
@@ -0,0 +1,7 @@
+{
+    "files":{
+        "{FROM}": "./src",
+        "{TO}": "./runtime",
+        "{FROM}/test.py": "{TO}/test.py"
+    }
+}
diff --git a/core/tests/javascript/config-url/src/test.py b/core/tests/javascript/config-url/src/test.py
new file mode 100644
index 00000000000..fc0bf83179e
--- /dev/null
+++ b/core/tests/javascript/config-url/src/test.py
@@ -0,0 +1,8 @@
+from pyscript import RUNNING_IN_WORKER, document
+
+classList = document.documentElement.classList
+
+if RUNNING_IN_WORKER:
+    classList.add("worker")
+else:
+    classList.add("main")
diff --git a/core/tests/javascript/config_type.html b/core/tests/javascript/config_type.html
new file mode 100644
index 00000000000..e75b60d6856
--- /dev/null
+++ b/core/tests/javascript/config_type.html
@@ -0,0 +1,23 @@
+
+
+
+    
+    
+    
+    
+
+
+    
+    
+
+
diff --git a/core/tests/javascript/fetch/a.py b/core/tests/javascript/fetch/a.py
new file mode 100644
index 00000000000..e1b904b7caa
--- /dev/null
+++ b/core/tests/javascript/fetch/a.py
@@ -0,0 +1 @@
+print("a")
diff --git a/core/tests/javascript/fetch/config.json b/core/tests/javascript/fetch/config.json
new file mode 100644
index 00000000000..71accc39b61
--- /dev/null
+++ b/core/tests/javascript/fetch/config.json
@@ -0,0 +1,5 @@
+{
+    "fetch": [{
+         "files": ["./a.py"]
+    }]
+}
diff --git a/core/tests/javascript/fetch/index.html b/core/tests/javascript/fetch/index.html
new file mode 100644
index 00000000000..701a6d34f20
--- /dev/null
+++ b/core/tests/javascript/fetch/index.html
@@ -0,0 +1,95 @@
+
+
+    
+        
+        
+        
+    
+    
+      
+      
+      
+    
+
diff --git a/core/tests/javascript/ffi.html b/core/tests/javascript/ffi.html
new file mode 100644
index 00000000000..16f7ece424a
--- /dev/null
+++ b/core/tests/javascript/ffi.html
@@ -0,0 +1,26 @@
+
+
+    
+        
+        
+        PyScript FFI
+        
+        
+    
+    
+      
+      
+    
+
diff --git a/core/tests/javascript/hooks.html b/core/tests/javascript/hooks.html
new file mode 100644
index 00000000000..857ed4f5c22
--- /dev/null
+++ b/core/tests/javascript/hooks.html
@@ -0,0 +1,60 @@
+
+
+
+  
+  
+  PyScript Next Plugin Bug?
+  
+  
+
+
+  
+  
+
+
diff --git a/core/tests/javascript/issue-2093/error.js b/core/tests/javascript/issue-2093/error.js
new file mode 100644
index 00000000000..e7dd853a03e
--- /dev/null
+++ b/core/tests/javascript/issue-2093/error.js
@@ -0,0 +1,6 @@
+const { error } = console;
+
+console.error = (...args) => {
+  error(...args);
+  document.documentElement.classList.add('errored');
+};
diff --git a/core/tests/javascript/issue-2093/index.html b/core/tests/javascript/issue-2093/index.html
new file mode 100644
index 00000000000..ff6720c1727
--- /dev/null
+++ b/core/tests/javascript/issue-2093/index.html
@@ -0,0 +1,16 @@
+
+
+    
+        
+        
+        
+        
+        
+    
+    
+      
+    
+
diff --git a/core/tests/javascript/js-storage.html b/core/tests/javascript/js-storage.html
new file mode 100644
index 00000000000..7a3d1f1e70c
--- /dev/null
+++ b/core/tests/javascript/js-storage.html
@@ -0,0 +1,28 @@
+
+
+
+    
+    
+    
+    
+
+
+  
+
+
diff --git a/core/tests/javascript/js_modules.html b/core/tests/javascript/js_modules.html
new file mode 100644
index 00000000000..bb0c5e90557
--- /dev/null
+++ b/core/tests/javascript/js_modules.html
@@ -0,0 +1,39 @@
+
+
+
+    
+    
+    
+    
+
+
+    
+        [js_modules.main]
+        "./js_modules.js" = "random_js"
+    
+    
+        from pyscript.js_modules.random_js import default as value
+        from pyscript.js_modules import random_js
+        from pyscript import js_modules
+
+        print("mpy", value)
+        print("mpy", random_js.default)
+        print("mpy", js_modules.random_js.default)
+    
+    
+        [js_modules.main]
+        "./js_modules.js" = "random_js"
+    
+    
+        from pyscript.js_modules.random_js import default as value
+        from pyscript.js_modules import random_js
+        from pyscript import js_modules, document
+
+        print("py", value)
+        print("py", random_js.default)
+        print("py", js_modules.random_js.default)
+
+        document.documentElement.classList.add('done')
+    
+
+
diff --git a/core/tests/javascript/js_modules.js b/core/tests/javascript/js_modules.js
new file mode 100644
index 00000000000..b6daef7f175
--- /dev/null
+++ b/core/tests/javascript/js_modules.js
@@ -0,0 +1 @@
+export default Math.random();
diff --git a/core/tests/javascript/loader/index.html b/core/tests/javascript/loader/index.html
new file mode 100644
index 00000000000..4e0bd4c81e9
--- /dev/null
+++ b/core/tests/javascript/loader/index.html
@@ -0,0 +1,29 @@
+
+
+
+  
+  
+  
+  
+
+
+  
+    packages = ["matplotlib"]
+  
+  
+
+
diff --git a/core/tests/javascript/media.html b/core/tests/javascript/media.html
new file mode 100644
index 00000000000..449fee1ef98
--- /dev/null
+++ b/core/tests/javascript/media.html
@@ -0,0 +1,39 @@
+
+
+
+  Pyodide Media Module Test
+  
+  
+
+
+

Pyodide Media Module Test

+
Running tests...
+ + + + diff --git a/core/tests/javascript/mpy-error.html b/core/tests/javascript/mpy-error.html new file mode 100644 index 00000000000..a8c62206bec --- /dev/null +++ b/core/tests/javascript/mpy-error.html @@ -0,0 +1,14 @@ + + + + + + + + + diff --git a/core/tests/javascript/mpy-no-error.html b/core/tests/javascript/mpy-no-error.html new file mode 100644 index 00000000000..6084dcc2388 --- /dev/null +++ b/core/tests/javascript/mpy-no-error.html @@ -0,0 +1,14 @@ + + + + + + + + + diff --git a/core/tests/javascript/mpy-no-error.toml b/core/tests/javascript/mpy-no-error.toml new file mode 100644 index 00000000000..4e7f1f7e4d3 --- /dev/null +++ b/core/tests/javascript/mpy-no-error.toml @@ -0,0 +1 @@ +plugins = ["!error"] diff --git a/core/tests/javascript/mpy.html b/core/tests/javascript/mpy.html new file mode 100644 index 00000000000..1d928af0e4b --- /dev/null +++ b/core/tests/javascript/mpy.html @@ -0,0 +1,30 @@ + + + + + + PyScript Next + + + + + + + + from pyscript import display + display("Hello", "M-PyScript Main 2", append=False) + + + from pyscript import display, document + display("Hello", "M-PyScript Worker", append=False) + document.documentElement.classList.add('worker') + + + diff --git a/core/tests/javascript/py-terminal-main.html b/core/tests/javascript/py-terminal-main.html new file mode 100644 index 00000000000..005ee224313 --- /dev/null +++ b/core/tests/javascript/py-terminal-main.html @@ -0,0 +1,14 @@ + + + + + + PyTerminal Main + + + + + + + + diff --git a/core/tests/javascript/py-terminal-worker.html b/core/tests/javascript/py-terminal-worker.html new file mode 100644 index 00000000000..ae791faec19 --- /dev/null +++ b/core/tests/javascript/py-terminal-worker.html @@ -0,0 +1,15 @@ + + + + + + PyTerminal Main + + + + + + + + + diff --git a/core/tests/javascript/py-terminal.html b/core/tests/javascript/py-terminal.html new file mode 100644 index 00000000000..701d36217a8 --- /dev/null +++ b/core/tests/javascript/py-terminal.html @@ -0,0 +1,18 @@ + + + + + + PyTerminal + + + + + + + + diff --git a/core/tests/javascript/py-terminals.html b/core/tests/javascript/py-terminals.html new file mode 100644 index 00000000000..1e0c0132911 --- /dev/null +++ b/core/tests/javascript/py-terminals.html @@ -0,0 +1,27 @@ + + + + + + PyTerminal Main + + + + + + + + + diff --git a/core/tests/javascript/pyodide-cache/cached.toml b/core/tests/javascript/pyodide-cache/cached.toml new file mode 100644 index 00000000000..ec4f4aa85c5 --- /dev/null +++ b/core/tests/javascript/pyodide-cache/cached.toml @@ -0,0 +1 @@ +packages = ["numpy", "matplotlib"] diff --git a/core/tests/javascript/pyodide-cache/index.html b/core/tests/javascript/pyodide-cache/index.html new file mode 100644 index 00000000000..506997de05d --- /dev/null +++ b/core/tests/javascript/pyodide-cache/index.html @@ -0,0 +1,41 @@ + + + + + + + + + diff --git a/core/tests/javascript/pyodide-cache/index.py b/core/tests/javascript/pyodide-cache/index.py new file mode 100644 index 00000000000..de77e97fa59 --- /dev/null +++ b/core/tests/javascript/pyodide-cache/index.py @@ -0,0 +1,6 @@ +import numpy as np +import matplotlib as mpl + +# just do something with the packages +print(len(dir(np))) +print(len(dir(mpl))) diff --git a/core/tests/javascript/pyodide-cache/never.toml b/core/tests/javascript/pyodide-cache/never.toml new file mode 100644 index 00000000000..a13dd158b34 --- /dev/null +++ b/core/tests/javascript/pyodide-cache/never.toml @@ -0,0 +1,2 @@ +packages_cache = "never" +packages = ["numpy", "matplotlib"] diff --git a/core/tests/javascript/pyodide-lockfile/index.html b/core/tests/javascript/pyodide-lockfile/index.html new file mode 100644 index 00000000000..28ad1a3531a --- /dev/null +++ b/core/tests/javascript/pyodide-lockfile/index.html @@ -0,0 +1,17 @@ + + + + + + + + + + + + diff --git a/core/tests/javascript/storage.html b/core/tests/javascript/storage.html new file mode 100644 index 00000000000..3aea830bf70 --- /dev/null +++ b/core/tests/javascript/storage.html @@ -0,0 +1,46 @@ + + + + + + @pyscript/core storage + + + + + + + diff --git a/core/tests/javascript/terminal.py b/core/tests/javascript/terminal.py new file mode 100644 index 00000000000..731afad113f --- /dev/null +++ b/core/tests/javascript/terminal.py @@ -0,0 +1,8 @@ +from pyscript import document + +classList = document.documentElement.classList + +if not __terminal__: + classList.add("error") +else: + classList.add("ok") diff --git a/core/tests/javascript/workers/config.toml b/core/tests/javascript/workers/config.toml new file mode 100644 index 00000000000..7cb628e8bd5 --- /dev/null +++ b/core/tests/javascript/workers/config.toml @@ -0,0 +1,2 @@ +[files] +"./test.py" = "./test.py" diff --git a/core/tests/javascript/workers/create_named/index.html b/core/tests/javascript/workers/create_named/index.html new file mode 100644 index 00000000000..faedf30403f --- /dev/null +++ b/core/tests/javascript/workers/create_named/index.html @@ -0,0 +1,18 @@ + + + + mpy using py named worker + + + + + + + + diff --git a/core/tests/javascript/workers/mpy/index.html b/core/tests/javascript/workers/mpy/index.html new file mode 100644 index 00000000000..31d74920630 --- /dev/null +++ b/core/tests/javascript/workers/mpy/index.html @@ -0,0 +1,16 @@ + + + + mpy using py named worker + + + + + + + + + diff --git a/core/tests/javascript/workers/py/index.html b/core/tests/javascript/workers/py/index.html new file mode 100644 index 00000000000..46c2117fb66 --- /dev/null +++ b/core/tests/javascript/workers/py/index.html @@ -0,0 +1,16 @@ + + + + py using mpy named worker + + + + + + + + + diff --git a/core/tests/javascript/workers/test.py b/core/tests/javascript/workers/test.py new file mode 100644 index 00000000000..08b5dc70f2d --- /dev/null +++ b/core/tests/javascript/workers/test.py @@ -0,0 +1,13 @@ +from pyscript import document, workers + + +async def test(name): + # retrieve sync utilities from the named worker + named = await workers[name] + + # invoke the runtime_version __export__ + show it + version = await named.runtime_version() + document.body.append(version) + + # flag the expectations around name done + document.documentElement.classList.add(name) diff --git a/core/tests/javascript/workers/worker.py b/core/tests/javascript/workers/worker.py new file mode 100644 index 00000000000..3b81275327a --- /dev/null +++ b/core/tests/javascript/workers/worker.py @@ -0,0 +1,7 @@ +def runtime_version(): + import sys + + return sys.version + + +__export__ = ["runtime_version"] diff --git a/core/tests/javascript/ws/index.html b/core/tests/javascript/ws/index.html new file mode 100644 index 00000000000..323b8cb3ff1 --- /dev/null +++ b/core/tests/javascript/ws/index.html @@ -0,0 +1,33 @@ + + + + + + + + + + + + diff --git a/core/tests/javascript/ws/index.js b/core/tests/javascript/ws/index.js new file mode 100644 index 00000000000..d26d84f942c --- /dev/null +++ b/core/tests/javascript/ws/index.js @@ -0,0 +1,35 @@ +import { serve, file } from 'bun'; + +import path, { dirname, join } from 'path'; +import { fileURLToPath } from 'url'; + +const dir = dirname(fileURLToPath(import.meta.url)); + +console.log('http://localhost:5037/'); + +serve({ + port: 5037, + fetch(req, server) { + if (server.upgrade(req)) return; + const url = new URL(req.url); + let { pathname } = url; + if (pathname === '/') pathname = '/index.html'; + else if (/^\/dist\//.test(pathname)) pathname = `/../../..${pathname}`; + else if (pathname === '/favicon.ico') + return new Response('Not Found', { status: 404 }); + const response = new Response(file(`${dir}${pathname}`)); + const { headers } = response; + headers.set('Cross-Origin-Opener-Policy', 'same-origin'); + headers.set('Cross-Origin-Embedder-Policy', 'require-corp'); + headers.set('Cross-Origin-Resource-Policy', 'cross-origin'); + return response; + }, + websocket: { + message(ws, message) { + ws.send(message); + }, + close() { + process.exit(0); + } + }, +}); diff --git a/core/tests/javascript/ws/index.spec.js b/core/tests/javascript/ws/index.spec.js new file mode 100644 index 00000000000..669be352f8a --- /dev/null +++ b/core/tests/javascript/ws/index.spec.js @@ -0,0 +1,6 @@ +import { test, expect } from '@playwright/test'; + +test('MicroPython WebSocket', async ({ page }) => { + await page.goto('http://localhost:5037/'); + await page.waitForSelector('html.ok'); +}); diff --git a/core/tests/js_tests.spec.js b/core/tests/js_tests.spec.js new file mode 100644 index 00000000000..b891b4095a7 --- /dev/null +++ b/core/tests/js_tests.spec.js @@ -0,0 +1,194 @@ +import { test, expect } from '@playwright/test'; + +test.setTimeout(120 * 1000); + +test('MicroPython display', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/mpy.html'); + await page.waitForSelector('html.done.worker'); + const body = await page.evaluate(() => document.body.innerText); + await expect(body.trim()).toBe([ + 'M-PyScript Main 1', + 'M-PyScript Main 2', + 'M-PyScript Worker', + ].join('\n')); +}); + +test('MicroPython hooks', async ({ page }) => { + const logs = []; + page.on('console', msg => { + const text = msg.text(); + if (!text.startsWith('[')) + logs.push(text); + }); + await page.goto('http://localhost:8080/tests/javascript/hooks.html'); + await page.waitForSelector('html.done.worker'); + await expect(logs.join('\n')).toBe([ + 'main onReady', + 'main onBeforeRun', + 'main codeBeforeRun', + 'actual code in main', + 'main codeAfterRun', + 'main onAfterRun', + 'worker onReady', + 'worker onBeforeRun', + 'worker codeBeforeRun', + 'actual code in worker', + 'worker codeAfterRun', + 'worker onAfterRun', + ].join('\n')); +}); + +test('MicroPython + Pyodide js_modules', async ({ page }) => { + const logs = []; + page.on('console', msg => { + const text = msg.text(); + if (!text.startsWith('[')) + logs.push(text); + }); + await page.goto('http://localhost:8080/tests/javascript/js_modules.html'); + await page.waitForSelector('html.done'); + await expect(logs.length).toBe(6); + await expect(logs[0]).toBe(logs[1]); + await expect(logs[1]).toBe(logs[2]); + await expect(logs[3]).toBe(logs[4]); + await expect(logs[4]).toBe(logs[5]); +}); + +test('MicroPython + configURL', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/config-url.html'); + await page.waitForSelector('html.main.worker'); +}); + +test('Pyodide + terminal on Main', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/py-terminal-main.html'); + await page.waitForSelector('html.ok'); +}); + + +test('Pyodide + terminal on Worker', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/py-terminal-worker.html'); + await page.waitForSelector('html.ok'); +}); + +test('Pyodide + multiple terminals via Worker', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/py-terminals.html'); + await page.waitForSelector('html.first.second'); +}); + +test('MicroPython + Pyodide fetch', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/fetch/index.html'); + await page.waitForSelector('html.mpy.py'); +}); + +test('MicroPython + Pyodide ffi', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/ffi.html'); + await page.waitForSelector('html.mpy.py'); +}); + +test('MicroPython + Storage', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/storage.html'); + await page.waitForSelector('html.ok'); +}); + +test('MicroPython + JS Storage', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/js-storage.html'); + await page.waitForSelector('html.ok'); +}); + +test('MicroPython using named Pyodide Worker', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/workers/mpy/index.html'); + await page.waitForSelector('html.pyodide_version'); +}); + +test('MicroPython creating a named Pyodide Worker', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/workers/create_named/index.html'); + await page.waitForSelector('html.pyodide_version'); +}); + +test('Pyodide using named MicroPython Worker', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/workers/py/index.html'); + await page.waitForSelector('html.micropython_version'); +}); + +test('MicroPython Editor setup error', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/issue-2093/index.html'); + await page.waitForSelector('html.errored'); +}); + +test('MicroPython async @when listener', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/async-listener.html'); + await page.waitForSelector('html.ok'); +}); + +test('Pyodide loader', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/loader/index.html'); + await page.waitForSelector('html.ok'); + const body = await page.evaluate(() => document.body.textContent); + await expect(body.includes('Loaded Pyodide')).toBe(true); +}); + +test('Py and Mpy config["type"]', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/config_type.html'); + await page.waitForSelector('html.mpy.py'); +}); + +test('Pyodide lockFileURL vs CDN', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/pyodide-cache/'); + await page.waitForSelector('html.done'); + const body = await page.evaluate(() => document.body.textContent); + await expect(body).toBe('OK'); +}); + +test('Pyodide pinned lockFileURL', async ({ page }) => { + const logs = []; + page.on('console', msg => { + const text = msg.text(); + if (!text.startsWith('[')) + logs.push(text); + }); + await page.goto('http://localhost:8080/tests/javascript/pyodide-lockfile/'); + await page.waitForSelector('html.done'); + let body = await page.evaluate(() => document.body.lastChild.textContent); + await expect(body).toBe('OK'); + await expect(!!logs.splice(0).length).toBe(true); + await page.reload(); + await page.waitForSelector('html.done'); + body = await page.evaluate(() => document.body.lastChild.textContent); + await expect(body).toBe('OK'); + await expect(logs.splice(0).length).toBe(0); +}); + +test('MicroPython buffered error', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/mpy-error.html'); + await page.waitForSelector('html.ok'); + const body = await page.evaluate(() => document.body.textContent.trim()); + await expect(body).toBe('This is an error'); +}); + +test('MicroPython buffered NO error', async ({ page }) => { + await page.goto('http://localhost:8080/tests/javascript/mpy-no-error.html'); + await page.waitForSelector('html.ok'); + const body = await page.evaluate(() => document.body.textContent.trim()); + await expect(body).toBe(''); +}); + +test('Pyodide media module', async ({ page }) => { + await page.context().grantPermissions(['camera', 'microphone']); + await page.context().addInitScript(() => { + const originalEnumerateDevices = navigator.mediaDevices.enumerateDevices; + navigator.mediaDevices.enumerateDevices = async function() { + const realDevices = await originalEnumerateDevices.call(this); + if (!realDevices || realDevices.length === 0) { + return [ + { deviceId: 'camera1', groupId: 'group1', kind: 'videoinput', label: 'Simulated Camera' }, + { deviceId: 'mic1', groupId: 'group2', kind: 'audioinput', label: 'Simulated Microphone' } + ]; + } + return realDevices; + }; + }); + await page.goto('http://localhost:8080/tests/javascript/media.html'); + await page.waitForSelector('html.media-ok', { timeout: 10000 }); + const isSuccess = await page.evaluate(() => document.documentElement.classList.contains('media-ok')); + expect(isSuccess).toBe(true); +}); diff --git a/core/tests/manual/a.py b/core/tests/manual/a.py new file mode 100644 index 00000000000..e1b904b7caa --- /dev/null +++ b/core/tests/manual/a.py @@ -0,0 +1 @@ +print("a") diff --git a/core/tests/manual/all-done.html b/core/tests/manual/all-done.html new file mode 100644 index 00000000000..031f972f870 --- /dev/null +++ b/core/tests/manual/all-done.html @@ -0,0 +1,39 @@ + + + + + + + + + + + + print(2) + + + print(3) + + + + print(5) + + + diff --git a/core/tests/manual/async.html b/core/tests/manual/async.html new file mode 100644 index 00000000000..67dbbdd543d --- /dev/null +++ b/core/tests/manual/async.html @@ -0,0 +1,21 @@ + + + + + + + + + import asyncio + print('py-script sleep') + await asyncio.sleep(1) + print('py-script done') + + + + diff --git a/core/tests/manual/bad.toml b/core/tests/manual/bad.toml new file mode 100644 index 00000000000..b79b726d1e9 --- /dev/null +++ b/core/tests/manual/bad.toml @@ -0,0 +1 @@ +files = [ diff --git a/core/tests/manual/camera.html b/core/tests/manual/camera.html new file mode 100644 index 00000000000..d04ff55dbae --- /dev/null +++ b/core/tests/manual/camera.html @@ -0,0 +1,24 @@ + + + + + + PyScript Media Example + + + + + + + + + + + + + +
+ + + + diff --git a/core/tests/manual/camera.py b/core/tests/manual/camera.py new file mode 100644 index 00000000000..a1fd3cfe344 --- /dev/null +++ b/core/tests/manual/camera.py @@ -0,0 +1,31 @@ +from pyscript import display, document, media, when, window +from pyscript.web import page + +devicesSelect = page["#devices"][0] +video = page["video"][0] +devices = {} + + +async def list_media_devices(event=None): + """List the available media devices.""" + global devices + for i, device in enumerate(await media.list_devices()): + devices[device.id] = device + label = f"{i} - ({device.kind}) {device.label} [{device.id}]" + devicesSelect.options.add(value=device.id, html=label) + + +@when("click", "#pick-device") +async def connect_to_device(e): + """Connect to the selected device.""" + device = devices[devicesSelect.value] + video.srcObject = await device.get_stream() + + +@when("click", "#snap") +async def camera_click(e): + """Take a picture and download it.""" + video.snap().download() + + +await list_media_devices() diff --git a/core/tests/manual/click.html b/core/tests/manual/click.html new file mode 100644 index 00000000000..378e9f99a4c --- /dev/null +++ b/core/tests/manual/click.html @@ -0,0 +1,29 @@ + + + + + + PyScript Next Plugin Bug? + + + + + + + + +
+ + diff --git a/core/tests/manual/code-a-part.html b/core/tests/manual/code-a-part.html new file mode 100644 index 00000000000..fcb3f40e543 --- /dev/null +++ b/core/tests/manual/code-a-part.html @@ -0,0 +1,19 @@ + + + + + + + + + + + + diff --git a/core/tests/manual/combo.html b/core/tests/manual/combo.html new file mode 100644 index 00000000000..aca99474918 --- /dev/null +++ b/core/tests/manual/combo.html @@ -0,0 +1,17 @@ + + + + + + PyScript Error + + + + [[fetch]] + files = ["./a.py"] + + + + diff --git a/core/tests/manual/config.html b/core/tests/manual/config.html new file mode 100644 index 00000000000..e40be7e52e4 --- /dev/null +++ b/core/tests/manual/config.html @@ -0,0 +1,13 @@ + + + + + + PyScript Next Plugin + + + + files = [ + + + diff --git a/core/tests/manual/config/ambiguous-config.html b/core/tests/manual/config/ambiguous-config.html new file mode 100644 index 00000000000..52b7eb85b7f --- /dev/null +++ b/core/tests/manual/config/ambiguous-config.html @@ -0,0 +1,19 @@ + + + + + + PyScript Next + + + + + + name = "first" + + + diff --git a/core/tests/manual/config/index.html b/core/tests/manual/config/index.html new file mode 100644 index 00000000000..18ba75c65e7 --- /dev/null +++ b/core/tests/manual/config/index.html @@ -0,0 +1,16 @@ + + + + + + Document + + + + + diff --git a/core/tests/manual/config/same-config.html b/core/tests/manual/config/same-config.html new file mode 100644 index 00000000000..9b89afcbb1b --- /dev/null +++ b/core/tests/manual/config/same-config.html @@ -0,0 +1,20 @@ + + + + + + PyScript Next + + + + + + OK + + + + diff --git a/core/tests/manual/config/too-many-config.html b/core/tests/manual/config/too-many-config.html new file mode 100644 index 00000000000..47e9d2b9e47 --- /dev/null +++ b/core/tests/manual/config/too-many-config.html @@ -0,0 +1,19 @@ + + + + + + PyScript Next + + + + + + + + + diff --git a/core/tests/manual/config/too-many-py-config.html b/core/tests/manual/config/too-many-py-config.html new file mode 100644 index 00000000000..1c71230bd17 --- /dev/null +++ b/core/tests/manual/config/too-many-py-config.html @@ -0,0 +1,19 @@ + + + + + + PyScript Next + + + + + + name = "first" + name = "second" + + diff --git a/core/tests/manual/create-element.html b/core/tests/manual/create-element.html new file mode 100644 index 00000000000..0dcad343c91 --- /dev/null +++ b/core/tests/manual/create-element.html @@ -0,0 +1,36 @@ + + + + + + + + diff --git a/core/tests/manual/dialog.html b/core/tests/manual/dialog.html new file mode 100644 index 00000000000..649309dae03 --- /dev/null +++ b/core/tests/manual/dialog.html @@ -0,0 +1,31 @@ + + + + + + PyScript Next + + + + + + + + Loading PyScript ... + + + diff --git a/core/tests/manual/display.html b/core/tests/manual/display.html new file mode 100644 index 00000000000..8b1ced46d45 --- /dev/null +++ b/core/tests/manual/display.html @@ -0,0 +1,30 @@ + + + + + + PyScript Next + + + + + + +

hello 2

+ + + diff --git a/core/tests/manual/donkey/index.html b/core/tests/manual/donkey/index.html new file mode 100644 index 00000000000..8d66f712c82 --- /dev/null +++ b/core/tests/manual/donkey/index.html @@ -0,0 +1,15 @@ + + + + + + + + + +
+ + + + + diff --git a/core/tests/manual/donkey/index.js b/core/tests/manual/donkey/index.js new file mode 100644 index 00000000000..870a714b74d --- /dev/null +++ b/core/tests/manual/donkey/index.js @@ -0,0 +1,43 @@ +import { donkey } from '../../../dist/core.js'; + +const runButton = document.querySelector('#run'); +const clearButton = document.querySelector('#clear'); +const killButton = document.querySelector('#kill'); + +const { + execute, // exec(expression) + evaluate, // eval(expression) + process, // process(code) + clear, + kill, +} = await donkey({ terminal: '#container' }); + +clearButton.onclick = async () => { + killButton.disabled = true; + clearButton.disabled = true; + await clear(); + runButton.disabled = false; +}; +killButton.onclick = () => { + killButton.disabled = true; + clearButton.disabled = true; + runButton.disabled = true; + kill(); +}; + +runButton.disabled = false; +runButton.onclick = async () => { + killButton.disabled = false; + clearButton.disabled = false; + runButton.disabled = true; + // multiline code + await execute(` + a = 1 + 2 + print(f'1 + 2 = {a}') + `); + // single expression evaluation + const name = await evaluate('input("what is your name? ")'); + alert(`Hello ${name}`); + killButton.disabled = true; + runButton.disabled = false; +}; diff --git a/core/tests/manual/emoji.html b/core/tests/manual/emoji.html new file mode 100644 index 00000000000..5dbe3cee8bd --- /dev/null +++ b/core/tests/manual/emoji.html @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/core/tests/manual/emoji.py b/core/tests/manual/emoji.py new file mode 100644 index 00000000000..9aaf0ae2d9f --- /dev/null +++ b/core/tests/manual/emoji.py @@ -0,0 +1,17 @@ +import sys + +print(sys.version) +RED = chr(0x1F534) # LARGE RED CIRCLE +GREEN = chr(0x1F7E2) # LARGE GREEN CIRCLE +MOUSE = chr(0x1F42D) # MOUSE FACE +EARTH = chr(0x1F30E) # EARTH GLOBE AMERICAS +FACE = chr(0x1F610) # NEUTRAL FACE +BASMALA = chr(0xFDFD) # ARABIC LIGATURE BISMILLAH AR-RAHMAN AR-RAHEEM + +print("[", RED, "]") +print("[", MOUSE, "]") +print("[", EARTH, "]") +print("[", FACE, "]") +print("[", FACE * 3, "]") +print("[", BASMALA, "]") +print("[", BASMALA + GREEN, "]") diff --git a/core/tests/manual/error.html b/core/tests/manual/error.html new file mode 100644 index 00000000000..f888ed28b65 --- /dev/null +++ b/core/tests/manual/error.html @@ -0,0 +1,23 @@ + + + + + + PyScript Next Plugin + + + + + print(4, 5, 6) + second() + + + print(4, 5, 6) + second() + + + + diff --git a/core/tests/manual/error/index.html b/core/tests/manual/error/index.html new file mode 100644 index 00000000000..04b50f104b2 --- /dev/null +++ b/core/tests/manual/error/index.html @@ -0,0 +1,39 @@ + + + + + + PyScript Error Bug? + + + + + + plugins = ["!error"] + + + + + +
+ + diff --git a/core/tests/manual/error/pyscript.toml b/core/tests/manual/error/pyscript.toml new file mode 100644 index 00000000000..4e7f1f7e4d3 --- /dev/null +++ b/core/tests/manual/error/pyscript.toml @@ -0,0 +1 @@ +plugins = ["!error"] diff --git a/core/tests/manual/fs/index.html b/core/tests/manual/fs/index.html new file mode 100644 index 00000000000..438e6fd0d28 --- /dev/null +++ b/core/tests/manual/fs/index.html @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/core/tests/manual/fs/index.py b/core/tests/manual/fs/index.py new file mode 100644 index 00000000000..5bff05bfef3 --- /dev/null +++ b/core/tests/manual/fs/index.py @@ -0,0 +1,46 @@ +import os +from pyscript import RUNNING_IN_WORKER, fs + + +TEST = "implicit" + +if TEST == "implicit": + await fs.mount("/persistent") + + print( + (RUNNING_IN_WORKER and "Worker") or "Main", + os.listdir("/persistent"), + ) + + from random import random + + with open("/persistent/random.txt", "w") as f: + f.write(str(random())) + + await fs.sync("/persistent") + +elif not RUNNING_IN_WORKER: + from pyscript import document + + button = document.createElement("button") + button.textContent = "mount" + document.body.append(button) + + async def mount(event): + try: + await fs.mount("/persistent") + print(os.listdir("/persistent")) + button.textContent = "unmount" + button.onclick = unmount + + except: + import js + + js.alert("unable to grant access") + + async def unmount(event): + await fs.unmount("/persistent") + button.textContent = "mount" + button.onclick = mount + + button.onclick = mount diff --git a/core/tests/manual/game/aliens.css b/core/tests/manual/game/aliens.css new file mode 100644 index 00000000000..f7a2fc48246 --- /dev/null +++ b/core/tests/manual/game/aliens.css @@ -0,0 +1,30 @@ +/* (c) https://github.com/ryanking13/pyodide-pygame-demo/blob/main/examples/aliens.html */ +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + margin: 0; + padding: 20px; + background-color: #f4f4f4; + color: #333; +} +.demo { + background-color: #fff; + margin: 20px auto; + max-width: 1000px; + box-shadow: 0 2px 4px rgba(0,0,0,0.1); + border-radius: 8px; + overflow: hidden; +} +.demo-header { + background-color: #007bff; + color: #fff; + padding: 15px 20px; + font-size: 20px; +} +.demo-content { + padding: 20px; +} + +#canvas { + margin: 0 auto; + display: block; +} diff --git a/core/tests/manual/game/aliens.py b/core/tests/manual/game/aliens.py new file mode 100644 index 00000000000..78ebf656766 --- /dev/null +++ b/core/tests/manual/game/aliens.py @@ -0,0 +1,399 @@ +"""(c) https://github.com/ryanking13/pyodide-pygame-demo/blob/main/examples/aliens.html +pygame.examples.aliens + +Shows a mini game where you have to defend against aliens. + +What does it show you about pygame? + +* pygame.sprite, the difference between Sprite and Group. +* dirty rectangle optimization for processing for speed. +* music with pygame.mixer.music, including fadeout +* sound effects with pygame.Sound +* event processing, keyboard handling, QUIT handling. +* a main loop frame limited with a game clock from the pygame.time module +* fullscreen switching. + + +Controls +-------- + +* Left and right arrows to move. +* Space bar to shoot. +* f key to toggle between fullscreen. + +""" + +import asyncio +import random +import os +import pathlib + +import pyscript + +# import basic pygame modules +import pygame + +# see if we can load more than standard BMP +if not pygame.image.get_extended(): + msg = "Sorry, extended image module required" + raise SystemExit(msg) + + +# game constants +MAX_SHOTS = 2 # most player bullets onscreen +ALIEN_ODDS = 22 # chances a new alien appears +BOMB_ODDS = 60 # chances a new bomb will drop +ALIEN_RELOAD = 12 # frames between new aliens +SCREENRECT = pygame.Rect(0, 0, 640, 480) +SCORE = 0 + + +main_dir = str(pathlib.Path(pygame.__file__).parent / "examples") + + +def load_image(file): + """loads an image, prepares it for play""" + file = os.path.join(main_dir, "data", file) + try: + surface = pygame.image.load(file) + except pygame.error: + msg = f'Could not load image "{file}" {pygame.get_error()}' + raise SystemExit(msg) + return surface.convert() + + +def load_sound(file): + """because pygame can be be compiled without mixer.""" + if not pygame.mixer: + return None + file = os.path.join(main_dir, "data", file) + try: + return pygame.mixer.Sound(file) + except pygame.error: + print(f"Warning, unable to load, {file}") + return None + + +# Each type of game object gets an init and an update function. +# The update function is called once per frame, and it is when each object should +# change its current position and state. +# +# The Player object actually gets a "move" function instead of update, +# since it is passed extra information about the keyboard. + + +class Player(pygame.sprite.Sprite): + """Representing the player as a moon buggy type car.""" + + speed = 10 + bounce = 24 + gun_offset = -11 + images = [] + + def __init__(self): + pygame.sprite.Sprite.__init__(self, self.containers) + self.image = self.images[0] + self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom) + self.reloading = False + self.origtop = self.rect.top + self.facing = -1 + + def move(self, direction): + if direction: + self.facing = direction + self.rect.move_ip(direction * self.speed, 0) + self.rect = self.rect.clamp(SCREENRECT) + if direction < 0: + self.image = self.images[0] + elif direction > 0: + self.image = self.images[1] + self.rect.top = self.origtop - (self.rect.left // self.bounce % 2) + + def gunpos(self): + pos = self.facing * self.gun_offset + self.rect.centerx + return pos, self.rect.top + + +class Alien(pygame.sprite.Sprite): + """An alien space ship. That slowly moves down the screen.""" + + speed = 13 + animcycle = 12 + images = [] + + def __init__(self): + pygame.sprite.Sprite.__init__(self, self.containers) + self.image = self.images[0] + self.rect = self.image.get_rect() + self.facing = random.choice((-1, 1)) * Alien.speed + self.frame = 0 + if self.facing < 0: + self.rect.right = SCREENRECT.right + + def update(self): + self.rect.move_ip(self.facing, 0) + if not SCREENRECT.contains(self.rect): + self.facing = -self.facing + self.rect.top = self.rect.bottom + 1 + self.rect = self.rect.clamp(SCREENRECT) + self.frame = self.frame + 1 + self.image = self.images[self.frame // self.animcycle % 3] + + +class Explosion(pygame.sprite.Sprite): + """An explosion. Hopefully the Alien and not the player!""" + + defaultlife = 12 + animcycle = 3 + images = [] + + def __init__(self, actor): + pygame.sprite.Sprite.__init__(self, self.containers) + self.image = self.images[0] + self.rect = self.image.get_rect(center=actor.rect.center) + self.life = self.defaultlife + + def update(self): + """called every time around the game loop. + + Show the explosion surface for 'defaultlife'. + Every game tick(update), we decrease the 'life'. + + Also we animate the explosion. + """ + self.life = self.life - 1 + self.image = self.images[self.life // self.animcycle % 2] + if self.life <= 0: + self.kill() + + +class Shot(pygame.sprite.Sprite): + """a bullet the Player sprite fires.""" + + speed = -11 + images = [] + + def __init__(self, pos): + pygame.sprite.Sprite.__init__(self, self.containers) + self.image = self.images[0] + self.rect = self.image.get_rect(midbottom=pos) + + def update(self): + """called every time around the game loop. + + Every tick we move the shot upwards. + """ + self.rect.move_ip(0, self.speed) + if self.rect.top <= 0: + self.kill() + + +class Bomb(pygame.sprite.Sprite): + """A bomb the aliens drop.""" + + speed = 9 + images = [] + + def __init__(self, alien): + pygame.sprite.Sprite.__init__(self, self.containers) + self.image = self.images[0] + self.rect = self.image.get_rect(midbottom=alien.rect.move(0, 5).midbottom) + + def update(self): + """called every time around the game loop. + + Every frame we move the sprite 'rect' down. + When it reaches the bottom we: + + - make an explosion. + - remove the Bomb. + """ + self.rect.move_ip(0, self.speed) + if self.rect.bottom >= 470: + Explosion(self) + self.kill() + + +class Score(pygame.sprite.Sprite): + """to keep track of the score.""" + + def __init__(self): + pygame.sprite.Sprite.__init__(self) + self.font = pygame.Font(None, 20) + self.font.set_italic(1) + self.color = "white" + self.lastscore = -1 + self.update() + self.rect = self.image.get_rect().move(10, 450) + + def update(self): + """We only update the score in update() when it has changed.""" + if self.lastscore != SCORE: + self.lastscore = SCORE + msg = "Score: %d" % SCORE + self.image = self.font.render(msg, 0, self.color) + + +async def main(winstyle=0): + # Initialize pygame + pygame.mixer.pre_init(44100, 32, 2, 1024) + pygame.init() + if pygame.mixer and not pygame.mixer.get_init(): + print("Warning, no sound") + pygame.mixer = None + + fullscreen = False + # Set the display mode + winstyle = 0 # |FULLSCREEN + screen = pygame.display.set_mode(SCREENRECT.size, winstyle) + + # Load images, assign to sprite classes + # (do this before the classes are used, after screen setup) + img = load_image("player1.gif") + Player.images = [img, pygame.transform.flip(img, 1, 0)] + img = load_image("explosion1.gif") + Explosion.images = [img, pygame.transform.flip(img, 1, 1)] + Alien.images = [load_image(im) for im in ("alien1.gif", "alien2.gif", "alien3.gif")] + Bomb.images = [load_image("bomb.gif")] + Shot.images = [load_image("shot.gif")] + + # decorate the game window + icon = pygame.transform.scale(Alien.images[0], (32, 32)) + pygame.display.set_icon(icon) + pygame.display.set_caption("Pygame Aliens") + pygame.mouse.set_visible(0) + + # create the background, tile the bgd image + bgdtile = load_image("background.gif") + background = pygame.Surface(SCREENRECT.size) + for x in range(0, SCREENRECT.width, bgdtile.get_width()): + background.blit(bgdtile, (x, 0)) + screen.blit(background, (0, 0)) + pygame.display.flip() + + # load the sound effects + boom_sound = load_sound("boom.wav") + shoot_sound = load_sound("car_door.wav") + if pygame.mixer: + music = os.path.join(main_dir, "data", "house_lo.wav") + pygame.mixer.music.load(music) + pygame.mixer.music.play(-1) + + # Initialize Game Groups + aliens = pygame.sprite.Group() + shots = pygame.sprite.Group() + bombs = pygame.sprite.Group() + all = pygame.sprite.RenderUpdates() + lastalien = pygame.sprite.GroupSingle() + + # assign default groups to each sprite class + Player.containers = all + Alien.containers = aliens, all, lastalien + Shot.containers = shots, all + Bomb.containers = bombs, all + Explosion.containers = all + Score.containers = all + + # Create Some Starting Values + global score + alienreload = ALIEN_RELOAD + _clock = pygame.Clock() + + # initialize our starting sprites + global SCORE + player = Player() + Alien() # note, this 'lives' because it goes into a sprite group + if pygame.font: + all.add(Score()) + + # Run our main loop whilst the player is alive. + while player.alive(): + # get input + for event in pygame.event.get(): + if event.type == pygame.QUIT: + return + if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: + return + if event.type == pygame.KEYDOWN and event.key == pygame.K_f: + if not fullscreen: + print("Changing to FULLSCREEN") + screen_backup = screen.copy() + screen = pygame.display.set_mode( + SCREENRECT.size, winstyle | pygame.FULLSCREEN, bestdepth + ) + screen.blit(screen_backup, (0, 0)) + else: + print("Changing to windowed mode") + screen_backup = screen.copy() + screen = pygame.display.set_mode( + SCREENRECT.size, winstyle, bestdepth + ) + screen.blit(screen_backup, (0, 0)) + pygame.display.flip() + fullscreen = not fullscreen + + keystate = pygame.key.get_pressed() + + # clear/erase the last drawn sprites + all.clear(screen, background) + + # update all the sprites + all.update() + + # handle player input + direction = keystate[pygame.K_RIGHT] - keystate[pygame.K_LEFT] + player.move(direction) + firing = keystate[pygame.K_SPACE] + if not player.reloading and firing and len(shots) < MAX_SHOTS: + Shot(player.gunpos()) + if pygame.mixer: + shoot_sound.play() + player.reloading = firing + + # Create new alien + if alienreload: + alienreload = alienreload - 1 + elif not int(random.random() * ALIEN_ODDS): + Alien() + alienreload = ALIEN_RELOAD + + # Drop bombs + if lastalien and not int(random.random() * BOMB_ODDS): + Bomb(lastalien.sprite) + + # Detect collisions between aliens and players. + for alien in pygame.sprite.spritecollide(player, aliens, 1): + if pygame.mixer: + boom_sound.play() + Explosion(alien) + Explosion(player) + SCORE = SCORE + 1 + player.kill() + + # See if shots hit the aliens. + for alien in pygame.sprite.groupcollide(aliens, shots, 1, 1): + if pygame.mixer: + boom_sound.play() + Explosion(alien) + SCORE = SCORE + 1 + + # See if alien bombs hit the player. + for bomb in pygame.sprite.spritecollide(player, bombs, 1): + if pygame.mixer: + boom_sound.play() + Explosion(player) + Explosion(bomb) + player.kill() + + # draw the scene + dirty = all.draw(screen) + pygame.display.update(dirty) + + # cap the framerate at 40fps. Also called 40HZ or 40 times per second. + await asyncio.sleep(0.025) + + if pygame.mixer: + pygame.mixer.music.fadeout(1000) + + +main() diff --git a/examples/toga/freedom/src/freedom/__init__.py b/core/tests/manual/game/config.toml similarity index 100% rename from examples/toga/freedom/src/freedom/__init__.py rename to core/tests/manual/game/config.toml diff --git a/core/tests/manual/game/index.html b/core/tests/manual/game/index.html new file mode 100644 index 00000000000..17489f3881d --- /dev/null +++ b/core/tests/manual/game/index.html @@ -0,0 +1,19 @@ + + + + + + + + + + + +
+
pygame.examples.aliens
+
+ +
+
+ + diff --git a/core/tests/manual/html-decode.html b/core/tests/manual/html-decode.html new file mode 100644 index 00000000000..1db840c4696 --- /dev/null +++ b/core/tests/manual/html-decode.html @@ -0,0 +1,35 @@ + + + + + + + + + import js; js.console.log(1<2, 1>2) + import js; js.console.log("
")
+ + + import js + js.console.log("C", 1<2, 1>2) + js.console.log("D
") +
+ import js; js.console.log(1<2, 1>2) + import js; js.console.log("
")
+ + + import js + js.console.log("C", 1<2, 1>2) + js.console.log("D
") +
+ + + diff --git a/core/tests/manual/index.html b/core/tests/manual/index.html new file mode 100644 index 00000000000..f243947e5c3 --- /dev/null +++ b/core/tests/manual/index.html @@ -0,0 +1,19 @@ + + + + + + PyScript Next + + + + + + + + diff --git a/core/tests/manual/input.html b/core/tests/manual/input.html new file mode 100644 index 00000000000..58f23f848d0 --- /dev/null +++ b/core/tests/manual/input.html @@ -0,0 +1,21 @@ + + + + + + PyScript Next + + + + + + + print(input("what's your name? ")) + + + print(input("what's your name? ")) + + + diff --git a/core/tests/manual/interpreter.html b/core/tests/manual/interpreter.html new file mode 100644 index 00000000000..5405dca0650 --- /dev/null +++ b/core/tests/manual/interpreter.html @@ -0,0 +1,16 @@ + + + + Pyodide Worker Version + + + + + + + + + diff --git a/core/tests/manual/issue-2228/index.html b/core/tests/manual/issue-2228/index.html new file mode 100644 index 00000000000..04b28592aa8 --- /dev/null +++ b/core/tests/manual/issue-2228/index.html @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/core/tests/manual/issue-2246/index.html b/core/tests/manual/issue-2246/index.html new file mode 100644 index 00000000000..adb148331ca --- /dev/null +++ b/core/tests/manual/issue-2246/index.html @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/core/tests/manual/issue-2246/main.py b/core/tests/manual/issue-2246/main.py new file mode 100644 index 00000000000..3c7f04bcff8 --- /dev/null +++ b/core/tests/manual/issue-2246/main.py @@ -0,0 +1 @@ +print(input("What food would you like me to get from the shop? ")) diff --git a/core/tests/manual/issue-2302/assets/genuary25-18.m4a b/core/tests/manual/issue-2302/assets/genuary25-18.m4a new file mode 100644 index 00000000000..aa10617e4aa Binary files /dev/null and b/core/tests/manual/issue-2302/assets/genuary25-18.m4a differ diff --git a/core/tests/manual/issue-2302/glue/multipyjs.py b/core/tests/manual/issue-2302/glue/multipyjs.py new file mode 100644 index 00000000000..dd483f52255 --- /dev/null +++ b/core/tests/manual/issue-2302/glue/multipyjs.py @@ -0,0 +1,20 @@ +from pyscript import config + +MICROPYTHON = config["type"] == "mpy" + +if MICROPYTHON: + def new(obj, *args, **kwargs): + return obj.new(*args, kwargs) if kwargs else obj.new(*args) + def call(obj, *args, **kwargs): + return obj(*args, kwargs) if kwargs else obj(*args) +else: + def new(obj, *args, **kwargs): + return obj.new(*args, **kwargs) + def call(obj, *args, **kwargs): + return obj(*args, **kwargs) + +if not MICROPYTHON: + import pyodide_js + pyodide_js.setDebug(True) + +from pyscript.ffi import to_js, create_proxy diff --git a/core/tests/manual/issue-2302/glue/perlin-0.0.0-cp312-cp312-pyodide_2024_0_wasm32.whl b/core/tests/manual/issue-2302/glue/perlin-0.0.0-cp312-cp312-pyodide_2024_0_wasm32.whl new file mode 100644 index 00000000000..718ace2e725 Binary files /dev/null and b/core/tests/manual/issue-2302/glue/perlin-0.0.0-cp312-cp312-pyodide_2024_0_wasm32.whl differ diff --git a/core/tests/manual/issue-2302/index.html b/core/tests/manual/issue-2302/index.html new file mode 100644 index 00000000000..a2ec422b739 --- /dev/null +++ b/core/tests/manual/issue-2302/index.html @@ -0,0 +1,69 @@ + + + + Genuary + + + + + + + + + + + + + + + + +
+
+
+
+
+
+ + + diff --git a/core/tests/manual/issue-2302/libfft.py b/core/tests/manual/issue-2302/libfft.py new file mode 100644 index 00000000000..226842800c6 --- /dev/null +++ b/core/tests/manual/issue-2302/libfft.py @@ -0,0 +1,83 @@ +from dataclasses import dataclass, field +import sys + +@dataclass +class BeatSync: + fft_res: int = field() + + on_beat: bool = False + beat: int = -1 + since_last_beat: float = sys.maxsize + + _prev: int = 0 + _count: int = 0 + _bins: list[int] = field(default_factory=list) + _last_detection: float = -1.0 + _threshold: int = 50 + _diff: int = 40 + _cooldown: float = 0.2 + + _highest: int = 0 + + def __post_init__(self): + self._bins = [int(13/16*self.fft_res/2)+17, int(13/16*self.fft_res/2)+18] + + def reset(self): + self.beat = -1 + self._prev = 0 + self._count = 0 + self._last_detection = -1.0 + self.since_last_beat = sys.maxsize + # print('bs reset') + + def update(self, data, running_time): + self._count += 1 + self.since_last_beat = running_time - self._last_detection + d = sum(data[bin] for bin in self._bins) + if d < self._threshold: + self.on_beat = False + elif d - self._prev < self._diff: + self.on_beat = False + elif self.since_last_beat < self._cooldown: + self.on_beat = False + else: + self._last_detection = running_time + self.since_last_beat = 0 + self.on_beat = True + self.beat += 1 + self._prev = d + +@dataclass +class FreqIntensity: + freq: float = field() + fft_res: int = field() + + intensity: float = 0.0 + intensity_slew: float = 0.0 + scale_min: float = 0.0 + scale_max: float = 350 + max: float = 0.0 + _sample_rate: int = 48000 + _bin_indexes: list[int] = field(default_factory=list) + _harmonics: int = 8 + _slew_factor: float = 0.8 + + def __post_init__(self): + self._bin_indexes = [ + round((harmonic+1) * self.freq / self._sample_rate * self.fft_res / 2) + for harmonic in range(self._harmonics) + ] + print(self._bin_indexes) + + def update(self, data): + intensity = 0.0 + for bin in range(self._harmonics): + intensity += data[self._bin_indexes[bin]]/(bin+1) + self.intensity = intensity + self.intensity_slew = self._slew_factor * self.intensity_slew + (1 - self._slew_factor) * intensity + self.max = max(intensity, self.max) + + @property + def intensity_scaled(self): + raw = max(0, min(1.0, (self.intensity_slew - self.scale_min)/(self.scale_max - self.scale_min))) + return raw * raw diff --git a/core/tests/manual/issue-2302/libthree.py b/core/tests/manual/issue-2302/libthree.py new file mode 100644 index 00000000000..2c0c675d528 --- /dev/null +++ b/core/tests/manual/issue-2302/libthree.py @@ -0,0 +1,189 @@ +import asyncio +from dataclasses import dataclass, field +from typing import Callable + +from pyscript import document, window + +from pyscript.js_modules import three as THREE +from pyscript.js_modules.stats_gl import default as StatsGL +from pyscript.js_modules import lsgeo, line2, linemat + +from multipyjs import MICROPYTHON, new, call, to_js, create_proxy + +@dataclass +class SoundPlayer: + sound: THREE.Audio = field() + on_start: Callable[[], None] = field() + on_stop: Callable[[], None] = field(default=lambda: None) + + _start_time: float = -1.0 + + def play(self): + self.sound.stop() + self.on_start() + self._start_time = self.sound.context.currentTime + self.sound.play() + + def stop(self): + self.sound.stop() + self.on_stop() + self._start_time = -1.0 + + def toggle(self): + if self.sound.isPlaying: + self.stop() + else: + self.play() + + @property + def running_time(self): + if self.sound.isPlaying: + return self.sound.context.currentTime - self._start_time + elif self._start_time != -1.0: + self.stop() + return 0.0 + +def get_renderer(): + renderer = new(THREE.WebGLRenderer, antialias=True) + renderer.setSize(window.innerWidth, window.innerHeight) + renderer.setPixelRatio(window.devicePixelRatio) + renderer.setClearColor(0xF5F0DC) + pyterms = list(document.getElementsByTagName("py-terminal")) + if pyterms: + pyterm = pyterms[0] + pyterm.parentNode.removeChild(pyterm) + document.getElementById("pyterm").appendChild(pyterm) + + document.getElementById("threejs").appendChild(renderer.domElement) + + initial = {0: "115px", 1: "calc(100vh - 120px)"} + @create_proxy + def split_element_style(dimension, size, gutter_size, index): + if index in initial: + result = {dimension: initial.pop(index)} + else: + result = {dimension: f"calc({int(size)}vh - {gutter_size}px)"} + return to_js(result) + + call( + window.Split, + ["#pyterm", "#threejs"], + direction="vertical", + elementStyle=split_element_style, + minSize=0, + maxSize=to_js([120, 10000]), + ) + return renderer + +def get_ortho_camera(view_size): + aspect_ratio = window.innerWidth / window.innerHeight + camera = new( + THREE.OrthographicCamera, + -view_size * aspect_ratio, # Left + view_size * aspect_ratio, # Right + view_size, # Top + -view_size, # Bottom + -view_size, # Near plane + view_size, # Far plane + ) + camera.updateProjectionMatrix() + camera.position.set(0, 0, 0) + return camera + +def get_loading_manager(): + loading_mgr = new(THREE.LoadingManager) + ev = asyncio.Event() + + @create_proxy + def on_start(url, itemsLoaded, itemsTotal): + print(f'[{itemsLoaded}/{itemsTotal}] Started loading file: {url}') + loading_mgr.onStart = on_start + + @create_proxy + def on_progress(url, itemsLoaded, itemsTotal): + print(f'[{itemsLoaded}/{itemsTotal}] Loading file: {url}') + loading_mgr.onProgress = on_progress + + @create_proxy + def on_error(url): + print(f'There was a problem loading {url}') + loading_mgr.onError = on_error + + @create_proxy + def on_load(): + print('Loading assets complete!') + ev.set() + loading_mgr.onLoad = on_load + + return loading_mgr, ev + + +def get_perspective_camera(): + aspect_ratio = window.innerWidth / window.innerHeight + camera = new( + THREE.PerspectiveCamera, + 45, # fov + aspect_ratio, + 0.25, # near plane + 300, # far plane + ) + camera.position.set(0, 0, 30) + return camera + +def get_stats_gl(renderer): + stats = new(StatsGL, trackGPU=True, horizontal=False) + stats.init(renderer) + stats.dom.style.removeProperty("left") + stats.dom.style.right = "90px" + document.getElementById("stats").appendChild(stats.dom) + return stats + +def bg_from_v(*vertices): + geometry = new(THREE.BufferGeometry) + vertices_f32a = new(Float32Array, vertices) + attr = new(THREE.Float32BufferAttribute, vertices_f32a, 3) + return geometry.setAttribute('position', attr) + +def bg_from_p(*points): + buf = new(THREE.BufferGeometry) + buf.setFromPoints( + [new(THREE.Vector3, p[0], p[1], p[2]) for p in points] + ) + return buf + +def clear(): + # toggle stats and terminal? + stats_style = document.getElementById("stats-off").style + if stats_style.display == "none": + # turn stuff back on + stats_style.removeProperty("display") + document.getElementById("pyterm").style.height = "115px" + document.getElementById("threejs").style.height = "calc(100vh - 120px)" + for e in document.getElementsByClassName("gutter"): + e.style.removeProperty("display") + for e in document.getElementsByClassName("xterm-helper-textarea"): + e.focus() + break + return + + # no longer focus on xterm + document.activeElement.blur() + # hide stats + document.getElementById("stats-off").style.display = "none" + # hide pyterm and split gutter + document.getElementById("pyterm").style.height = "0vh" + document.getElementById("threejs").style.height = "100vh" + for e in document.getElementsByClassName("gutter"): + e.style.display = "none" + # hide ltk ad + for e in document.getElementsByClassName("ltk-built-with"): + e.style.display = "none" + # hide pyscript ad + for e in document.getElementsByTagName("div"): + style = e.getAttribute("style") + if style and style.startswith("z-index:999"): + e.style.display = "none" + for e in document.getElementsByTagName("svg"): + style = e.getAttribute("style") + if style and style.startswith("z-index:999"): + e.style.display = "none" diff --git a/core/tests/manual/issue-2302/main.py b/core/tests/manual/issue-2302/main.py new file mode 100644 index 00000000000..f2a6abf5db9 --- /dev/null +++ b/core/tests/manual/issue-2302/main.py @@ -0,0 +1,285 @@ +print("Starting up...") + +from array import array +import asyncio +import math +import time + +from pyscript import document, window, PyWorker + +from libthree import THREE, clear, SoundPlayer +from libthree import get_renderer, get_ortho_camera +from libthree import get_loading_manager, get_stats_gl +from libthree import lsgeo, line2, linemat, lsgeo +from libfft import BeatSync + +from multipyjs import MICROPYTHON, new, call, to_js, create_proxy + +from js import Float32Array + +scene = new(THREE.Scene) + +view_size = 1 +renderer = get_renderer() +camera = get_ortho_camera(view_size) +loading_mgr, loaded_event = get_loading_manager() + +t_loader = new(THREE.TextureLoader, loading_mgr) +t_loader.setPath('assets/') + +light = new(THREE.AmbientLight, 0xffffff, 1.0) +scene.add(light) + +fft_res = 2048 +audio_listener = new(THREE.AudioListener) +camera.add(audio_listener) +sound = new(THREE.Audio, audio_listener) +audio_loader = new(THREE.AudioLoader, loading_mgr) +analyser = new(THREE.AudioAnalyser, sound, fft_res) + +@create_proxy +def on_audio_load(buffer): + sound.setBuffer(buffer) + sound.setVolume(0.9) + sound.setLoop(False) + +audio_loader.load("assets/genuary25-18.m4a", on_audio_load) + +spheres = new(THREE.Group) +scene.add(spheres) + +line_basic_mat = new( + THREE.LineBasicMaterial, + color=0xffffff, +) + +zero_mat = new( + linemat.LineMaterial, + color=0x662503, + linewidth=3, +) + +other_mat = new( + linemat.LineMaterial, + color=0x662503, + linewidth=1.5, +) + +grid_mat = new( + linemat.LineMaterial, + color=0x662503, + linewidth=1, + dashed=True, + dashScale=1, + dashSize=0.5, + gapSize=1, + dashOffset=0, +) + +lines = [new(THREE.Group), new(THREE.Group)] +scene.add(lines[0]) +scene.add(lines[1]) + +def draw_lines(line_coords, mat_name, spy=False): + if spy: + line_coords_f32a = new(Float32Array, line_coords.length) + _it = line_coords.items + for i in range(line_coords.length): + line_coords_f32a[i] = _it[i] + else: + line_coords_f32a = new(Float32Array, line_coords) + if mat_name == 'zero': + mat = zero_mat + elif mat_name == 'grid': + mat = grid_mat + else: + mat = other_mat + + geo = new(THREE.BufferGeometry) + geo.setAttribute('position', new(THREE.BufferAttribute, line_coords_f32a, 3)) + seg = new(THREE.LineSegments, geo, line_basic_mat) + + lsg = new(lsgeo.LineSegmentsGeometry) + lsg.fromLineSegments(seg) + l1 = new(line2.Line2, lsg, mat) + l1.computeLineDistances() + l2 = new(line2.Line2, lsg, mat) + l2.computeLineDistances() + lines[0].add(l1) + lines[1].add(l2) + + seg.geometry.dispose() + del geo + del seg + +def drawing_done(): + maybe_with_spy = "with SPy" if USE_SPY else "with pure Python" + print(f"Time elapsed computing {maybe_with_spy}:", time.time() - start_ts) + drawing_event.set() + +grid_width = 0 +grid_height = 0 +scroll_offset = 0 +def scale_lines(grid_ws=None, grid_hs=None, offset=None): + global grid_width, grid_height, scroll_offset + + if grid_ws: + grid_width = grid_ws + else: + grid_ws = grid_width + + if grid_hs: + grid_height = grid_hs + else: + grid_hs = grid_height + + if offset: + scroll_offset = offset + else: + offset = scroll_offset + + scale = 2.04/grid_hs + lines[0].scale.set(scale, scale, scale) + lines[1].scale.set(scale, scale, scale) + lines[0].position.set((offset - grid_ws/2) * scale, -grid_hs/2 * scale, 0) + lines[1].position.set((offset + grid_ws/2) * scale, -grid_hs/2 * scale, 0) + +def append_p(lines, p1, p2): + lines.append(p1[0]) + lines.append(p1[1]) + lines.append(0) + lines.append(p2[0]) + lines.append(p2[1]) + lines.append(0) + +def initial_calc(): + grid_w = int(1920 * 4) + grid_h = 1080 * 2 + grid_scale = 10 + noise_factor = 500 + grid_hs = int(grid_h/grid_scale) + grid_ws = int(grid_w/grid_scale) + crossfade_range = int(grid_ws/12.5) + + def grid_lines(): + lines = array("d") + grid_goal = 24 + grid_size_i = int(round((grid_ws - crossfade_range) / grid_goal)) + grid_actual = (grid_ws - crossfade_range) / grid_size_i + for i in range(0, grid_size_i): + x = i * grid_actual + append_p(lines, (x, 0), (x, grid_hs)) + for y in range(0, grid_hs, grid_goal): + append_p(lines, (0, y), (grid_ws-crossfade_range, y)) + return lines + + import perlin + spy_perlin = perlin.lib + spy_perlin.init() + spy_perlin.seed(44) + scale_lines(grid_ws - crossfade_range, grid_hs) + print("Computing the height map") + spy_perlin.make_height_map(grid_ws, grid_hs) + spy_perlin.update_height_map(grid_ws, grid_hs, grid_scale / noise_factor, 0) + print("Cross-fading the height map") + spy_perlin.crossfade_height_map(grid_ws, grid_hs, crossfade_range) + print("Drawing grid") + draw_lines(grid_lines(), 'grid') + print("Marching squares") + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, 0), 'zero', spy=True) + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, 0.3), 'positive', spy=True) + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, -0.3), 'negative', spy=True) + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, 0.45), 'positive', spy=True) + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, -0.45), 'negative', spy=True) + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, 0.6), 'positive', spy=True) + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, -0.6), 'negative', spy=True) + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, -0.8), 'negative', spy=True) + draw_lines(spy_perlin.marching_squares(grid_ws, grid_hs, 0.8), 'positive', spy=True) + drawing_done() + +drawing_event = asyncio.Event() +start_ts = time.time() + +USE_SPY = True +if USE_SPY: + initial_calc() +else: + worker = PyWorker("./worker.py", type="pyodide", configURL="./pyscript.toml") + worker.sync.draw_lines = draw_lines + worker.sync.drawing_done = drawing_done + worker.sync.scale_lines = scale_lines + worker.sync.print = print + +@create_proxy +def on_tap(event): + clear() + player.toggle() +document.addEventListener("click", on_tap) + +@create_proxy +def on_key_down(event): + element = document.activeElement + _class = element.getAttribute("class") + in_xterm = element.tagName != "BODY" and _class and "xterm" in _class + + if event.code == "Backquote": + # Screenshot mode. + clear() + elif not in_xterm: + # Don't react to those bindings when typing code. + if event.code == "Space": + player.toggle() +document.addEventListener("keydown", on_key_down) + +@create_proxy +def on_window_resize(event): + aspect_ratio = window.innerWidth / window.innerHeight + if camera.type == "OrthographicCamera": + camera.left = -view_size * aspect_ratio + camera.right = view_size * aspect_ratio + camera.top = view_size + camera.bottom = -view_size + camera.updateProjectionMatrix() + elif camera.type == "PerspectiveCamera": + camera.aspect = window.innerWidth / window.innerHeight + camera.updateProjectionMatrix() + else: + raise ValueError("Unknown camera type") + renderer.setSize(window.innerWidth, window.innerHeight) + scale_lines() + +window.addEventListener("resize", on_window_resize) + +@create_proxy +def animate(now=0.0): + data = analyser.getFrequencyData()#.to_py() in Pyodide + audio_now = player.running_time + bs.update(data, audio_now) + + if grid_width: + offset = -((20 * audio_now) % grid_width) + scale_lines(offset=offset) + + renderer.render(scene, camera) + stats_gl.update() + +def reset(): + global scroll_offset + bs.reset() + scale_lines() + +def on_stop(): + global scroll_offset + bs.reset() + scale_lines() + +await loaded_event.wait() + +stats_gl = get_stats_gl(renderer) +player = SoundPlayer(sound=sound, on_start=reset, on_stop=on_stop) +bs = BeatSync(fft_res=fft_res) +renderer.setAnimationLoop(animate) +print("Waiting for the contours...") + +await drawing_event.wait() +print("Tap the map to start...") diff --git a/core/tests/manual/issue-2302/perlin_py.py b/core/tests/manual/issue-2302/perlin_py.py new file mode 100644 index 00000000000..8141e8f7545 --- /dev/null +++ b/core/tests/manual/issue-2302/perlin_py.py @@ -0,0 +1,110 @@ +# Translated from https://github.com/josephg/noisejs. +from libthree import THREE +from multipyjs import new + +class V3: + def __init__(self, x, y, z): + self.x = x + self.y = y + self.z = z + + def __repr__(self): + return f"V3({self.x}, {self.y}, {self.z})" + + def dot2(self, x, y): + return self.x * x + self.y * y + + def dot3(self, x, y, z): + return self.x * x + self.y * y + self.z * z + + def to_js(self, scale=1.0): + return new(THREE.Vector3, self.x * scale, self.y * scale, self.z * scale) + +PERM = [0] * 512 +V3_P = [0] * 512 # assigned V3s in seed() +P = [151, 160, 137, 91, 90, 15, + 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, + 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, + 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, + 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, + 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, + 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, + 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, + 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, + 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, + 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, + 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, + 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180] +V3_I = [V3(1, 1, 0), V3(-1, 1, 0), V3(1, -1, 0), V3(-1, -1, 0), + V3(1, 0, 1), V3(-1, 0, 1), V3(1, 0, -1), V3(-1, 0, -1), + V3(0, 1, 1), V3(0, -1, 1), V3(0, 1, -1), V3(0, -1, -1)] + +def seed(s): + if isinstance(s, float) and 0.0 < s < 1.0: + s *= 65536 + + s = int(s) + if s < 256: + s |= s << 8 + + for i in range(256): + if i & 1: + v = P[i] ^ (s & 255) + else: + v = P[i] ^ ((s >> 8) & 255) + + PERM[i] = PERM[i + 256] = v + V3_P[i] = V3_P[i + 256] = V3_I[v % 12] + +seed(0) + +def fade(t): + return t * t * t * (t * (t * 6 - 15) + 10) + +def lerp(a, b, t): + return (1 - t) * a + t * b + +def perlin3(x, y, z): + # grid cells + x_c = int(x) + y_c = int(y) + z_c = int(z) + # relative coords within the cell + x -= x_c + y -= y_c + z -= z_c + # wrap cells + x_c &= 255 + y_c &= 255 + z_c &= 255 + # noise contributions to corners + n000 = V3_P[x_c + PERM[y_c + PERM[z_c]]].dot3(x, y, z) + n001 = V3_P[x_c + PERM[y_c + PERM[z_c + 1]]].dot3(x, y, z - 1) + n010 = V3_P[x_c + PERM[y_c + 1 + PERM[z_c]]].dot3(x, y - 1, z) + n011 = V3_P[x_c + PERM[y_c + 1 + PERM[z_c + 1]]].dot3(x, y - 1, z - 1) + n100 = V3_P[x_c + 1 + PERM[y_c + PERM[z_c]]].dot3(x - 1, y, z) + n101 = V3_P[x_c + 1 + PERM[y_c + PERM[z_c + 1]]].dot3(x - 1, y, z - 1) + n110 = V3_P[x_c + 1 + PERM[y_c + 1 + PERM[z_c]]].dot3(x - 1, y - 1, z) + n111 = V3_P[x_c + 1 + PERM[y_c + 1 + PERM[z_c + 1]]].dot3(x - 1, y - 1, z - 1) + # fade curve + u = fade(x) + v = fade(y) + w = fade(z) + # interpolation + return lerp( + lerp(lerp(n000, n100, u), lerp(n001, n101, u), w), + lerp(lerp(n010, n110, u), lerp(n011, n111, u), w), + v, + ) + +def curl2(x, y, z): + # https://www.bit-101.com/2017/2021/07/curl-noise/ + delta = 0.01 + n1 = perlin3(x + delta, y, z) + n2 = perlin3(x - delta, y, z) + cy = -(n1 - n2) / (delta * 2) + n1 = perlin3(x, y + delta, z) + n2 = perlin3(x, y - delta, z) + cx = -(n1 - n2) / (delta * 2) + print(n1, n2) + return V3(cx, cy, 0) diff --git a/core/tests/manual/issue-2302/pyscript.toml b/core/tests/manual/issue-2302/pyscript.toml new file mode 100644 index 00000000000..36409b57f2f --- /dev/null +++ b/core/tests/manual/issue-2302/pyscript.toml @@ -0,0 +1,16 @@ +name = "Marching Squares with SPy Copy Copy" +packages = [ "cffi", "./glue/perlin-0.0.0-cp312-cp312-pyodide_2024_0_wasm32.whl",] + +[files] +"./libthree.py" = "" +"./libfft.py" = "" +"./perlin_py.py" = "" +"./worker.py" = "" +"./glue/multipyjs.py" = "./multipyjs.py" + +[js_modules.main] +"https://cdn.jsdelivr.net/npm/three@v0.173.0/build/three.module.js" = "three" +"https://cdn.jsdelivr.net/npm/three@v0.173.0/examples/jsm/lines/LineMaterial.js" = "linemat" +"https://cdn.jsdelivr.net/npm/three@v0.173.0/examples/jsm/lines/Line2.js" = "line2" +"https://cdn.jsdelivr.net/npm/three@v0.173.0/examples/jsm/lines/LineSegmentsGeometry.js" = "lsgeo" +"https://cdn.jsdelivr.net/npm/stats-gl@3.6.0/dist/main.js" = "stats_gl" diff --git a/core/tests/manual/issue-2302/worker.py b/core/tests/manual/issue-2302/worker.py new file mode 100644 index 00000000000..bc857738af8 --- /dev/null +++ b/core/tests/manual/issue-2302/worker.py @@ -0,0 +1,141 @@ +from array import array + +from pyscript import sync, window +from perlin_py import perlin3, seed + +grid_w = int(1920 * 4) +grid_h = 1080 * 2 +grid_scale = 10 +noise_factor = 500 +grid_hs = int(grid_h/grid_scale) +grid_ws = int(grid_w/grid_scale) +crossfade_range = int(grid_ws/12.5) +height_map = array("d", [0.0] * (grid_hs * grid_ws)) +edge_table = [ + (), # 0 + ((3, 2),), # 1 + ((2, 1),), # 2 + ((3, 1),), # 3 + ((0, 1),), # 4 + ((0, 3), (1, 2)), # 5 (ambiguous) + ((0, 2),), # 6 + ((0, 3),), # 7 + ((0, 3),), # 8 + ((0, 2),), # 9 + ((0, 1), (2, 3)), # 10 (ambiguous) + ((0, 1),), # 11 + ((3, 1),), # 12 + ((2, 1),), # 13 + ((3, 2),), # 14 + (), # 15 +] + +def update_height_map(z): + i = 0 + for y in range(0, grid_h, grid_scale): + for x in range(0, grid_w, grid_scale): + # 3 octaves of noise + n = perlin3(x/noise_factor, y/noise_factor, z) + n += 0.50 * perlin3(2*x/noise_factor, 2*y/noise_factor, z) + n += 0.25 * perlin3(4*x/noise_factor, 4*y/noise_factor, z) + height_map[i] = n + i += 1 + +def crossfade_height_map(): + for y in range(grid_hs): + for x in range(crossfade_range): + pos_i = y*grid_ws + x + neg_i = y*grid_ws + grid_ws - crossfade_range + x + weight = x/crossfade_range + old_pos = height_map[pos_i] + old_neg = height_map[neg_i] + height_map[neg_i] = height_map[pos_i] = weight * old_pos + (1.0 - weight) * old_neg + + +def _crossfade_height_map(): + for y in range(grid_hs): + for x in range(crossfade_range): + pos_i = y*grid_ws + x + neg_i = y*grid_ws + grid_ws - x - 1 + old_pos = height_map[pos_i] + old_neg = height_map[neg_i] + weight = 0.5 - x/crossfade_range/2 + height_map[pos_i] = (1.0 - weight) * old_pos + weight * old_neg + height_map[neg_i] = (1.0 - weight) * old_neg + weight * old_pos + +def interpolate(sq_threshold, v1, v2): + if v1 == v2: + return v1 + return (sq_threshold - v1) / (v2 - v1) + +stats = {'maxx': 0, 'maxy': 0, 'minx': 0, 'miny': 0} +def append_p(lines, p1, p2): + lines.append(p1[0]) + lines.append(p1[1]) + lines.append(0) + lines.append(p2[0]) + lines.append(p2[1]) + lines.append(0) + stats['maxy'] = max(p1[1], p2[1], stats['maxy']) + stats['miny'] = min(p1[1], p2[1], stats['miny']) + stats['maxx'] = max(p1[0], p2[0], stats['maxx']) + stats['minx'] = min(p1[0], p2[0], stats['minx']) + +def marching_squares(height_map, sq_threshold): + lines = array("d") + + for y in range(grid_hs-1): + for x in range(grid_ws-1): #cf + tl = height_map[y*grid_ws + x] + tr = height_map[y*grid_ws + x+1] + bl = height_map[(y+1)*grid_ws + x] + br = height_map[(y+1)*grid_ws + x+1] + + sq_idx = 0 + if tl > sq_threshold: + sq_idx |= 8 + if tr > sq_threshold: + sq_idx |= 4 + if br > sq_threshold: + sq_idx |= 2 + if bl > sq_threshold: + sq_idx |= 1 + + edge_points = [ + (x + interpolate(sq_threshold, tl, tr), y), + (x + 1, y + interpolate(sq_threshold, tr, br)), + (x + interpolate(sq_threshold, bl, br), y + 1), + (x, y + interpolate(sq_threshold, tl, bl)), + ] + + for a, b in edge_table[sq_idx]: + append_p(lines, edge_points[a], edge_points[b]) + + return lines + +def grid_lines(): + lines = array("d") + for x in range(0, grid_ws - crossfade_range, 26): + append_p(lines, (x, 0), (x, grid_hs)) + for y in range(0, grid_hs, 24): + append_p(lines, (0, y), (grid_ws-crossfade_range, y)) + return lines + +seed(44) +sync.scale_lines(grid_ws - crossfade_range, grid_hs) +sync.print("Computing the height map") +update_height_map(0) +sync.print("Cross-fading the height map") +crossfade_height_map() +sync.draw_lines(grid_lines(), 'grid') +sync.draw_lines(marching_squares(height_map, 0), 'zero') +sync.draw_lines(marching_squares(height_map, 0.3), 'positive') +sync.draw_lines(marching_squares(height_map, -0.3), 'negative') +sync.draw_lines(marching_squares(height_map, 0.45), 'positive') +sync.draw_lines(marching_squares(height_map, -0.45), 'negative') +sync.draw_lines(marching_squares(height_map, 0.6), 'positive') +sync.draw_lines(marching_squares(height_map, -0.6), 'negative') +sync.draw_lines(marching_squares(height_map, -0.8), 'negative') +sync.draw_lines(marching_squares(height_map, 0.8), 'positive') +print(stats) +sync.drawing_done() diff --git a/core/tests/manual/issue-2304/index.html b/core/tests/manual/issue-2304/index.html new file mode 100644 index 00000000000..fe1805db52f --- /dev/null +++ b/core/tests/manual/issue-2304/index.html @@ -0,0 +1,12 @@ + + + + + + + +
Status:
+ + + + diff --git a/core/tests/manual/issue-2304/main.py b/core/tests/manual/issue-2304/main.py new file mode 100644 index 00000000000..cf5eb6ae006 --- /dev/null +++ b/core/tests/manual/issue-2304/main.py @@ -0,0 +1,34 @@ +import sys +print("Starting test...") + +# Try NumPy +try: + import numpy as np + arr = np.array([1, 2, 3]) + print(f"NumPy works: {arr.mean()}") +except Exception as e: + print(f"NumPy error: {e}") + +# Try PyGame without NumPy first +try: + print("Testing PyGame...") + import pygame + screen = pygame.display.set_mode((200, 200)) + screen.fill((255, 0, 0)) # Fill with red + pygame.display.flip() + print("PyGame works!") +except Exception as e: + print(f"PyGame error: {e}") + +# Now try PyGame with NumPy +try: + print("Testing PyGame+NumPy...") + color_array = np.random.randint(0, 255, size=(50, 50, 3), dtype=np.uint8) + surface = pygame.surfarray.make_surface(color_array) + screen.blit(surface, (75, 75)) + pygame.display.flip() + print("PyGame+NumPy integration works!") +except Exception as e: + print(f"PyGame+NumPy integration error: {e}") + +print("Test completed") diff --git a/core/tests/manual/issue-2304/pyscript.toml b/core/tests/manual/issue-2304/pyscript.toml new file mode 100644 index 00000000000..28cd14bd37a --- /dev/null +++ b/core/tests/manual/issue-2304/pyscript.toml @@ -0,0 +1,2 @@ +name = "PyGame Numpy Minimal Example Copy" +packages = [ "numpy", ] diff --git a/core/tests/manual/issue-7015/config.toml b/core/tests/manual/issue-7015/config.toml new file mode 100644 index 00000000000..76507883737 --- /dev/null +++ b/core/tests/manual/issue-7015/config.toml @@ -0,0 +1,4 @@ +packages = [ + "https://cdn.holoviz.org/panel/wheels/bokeh-3.5.0-py3-none-any.whl", + "https://cdn.holoviz.org/panel/1.5.0-b.2/dist/wheels/panel-1.5.0b2-py3-none-any.whl" +] diff --git a/core/tests/manual/issue-7015/index.html b/core/tests/manual/issue-7015/index.html new file mode 100644 index 00000000000..6b7301a1d61 --- /dev/null +++ b/core/tests/manual/issue-7015/index.html @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + +
+ + diff --git a/core/tests/manual/issue-7015/main.py b/core/tests/manual/issue-7015/main.py new file mode 100644 index 00000000000..6e6927f0009 --- /dev/null +++ b/core/tests/manual/issue-7015/main.py @@ -0,0 +1,12 @@ +import panel as pn + +pn.extension(sizing_mode="stretch_width") + +slider = pn.widgets.FloatSlider(start=0, end=10, name="amplitude") + + +def callback(new): + return f"Amplitude is: {new}" + + +pn.Row(slider, pn.bind(callback, slider)).servable(target="simple_app") diff --git a/core/tests/manual/multi.html b/core/tests/manual/multi.html new file mode 100644 index 00000000000..e85ba5262cf --- /dev/null +++ b/core/tests/manual/multi.html @@ -0,0 +1,20 @@ + + + + + + + + + + + + diff --git a/core/tests/manual/multiple-editors.html b/core/tests/manual/multiple-editors.html new file mode 100644 index 00000000000..c2b3d257038 --- /dev/null +++ b/core/tests/manual/multiple-editors.html @@ -0,0 +1,31 @@ + + + + + + PyScript Test + + + + + + + + + + + + + diff --git a/core/tests/manual/no-error.html b/core/tests/manual/no-error.html new file mode 100644 index 00000000000..858f7a6689f --- /dev/null +++ b/core/tests/manual/no-error.html @@ -0,0 +1,23 @@ + + + + + + PyScript Next No Plugin + + + plugins = ['!error'] + + + print(4, 5, 6) + second() + + + print(4, 5, 6) + second() + + + diff --git a/core/tests/manual/no_sab/index.html b/core/tests/manual/no_sab/index.html new file mode 100644 index 00000000000..0cd7844589d --- /dev/null +++ b/core/tests/manual/no_sab/index.html @@ -0,0 +1,25 @@ + + + + + + + + + diff --git a/core/tests/manual/no_sab/worker.py b/core/tests/manual/no_sab/worker.py new file mode 100644 index 00000000000..ffdf6c02155 --- /dev/null +++ b/core/tests/manual/no_sab/worker.py @@ -0,0 +1,3 @@ +from pyscript import sync + +sync.get_class = lambda: "ok" diff --git a/core/tests/manual/piratical/index.html b/core/tests/manual/piratical/index.html new file mode 100644 index 00000000000..209cfb22e06 --- /dev/null +++ b/core/tests/manual/piratical/index.html @@ -0,0 +1,18 @@ + + + + + + Arrr - Piratical PyScript + + + + +

Arrr

+

Translate English into Pirate speak...

+ + +
+ + + diff --git a/core/tests/manual/piratical/piratical.py b/core/tests/manual/piratical/piratical.py new file mode 100644 index 00000000000..82bef2680f0 --- /dev/null +++ b/core/tests/manual/piratical/piratical.py @@ -0,0 +1,9 @@ +import arrr +from js import document + + +def translate_english(event): + input_text = document.querySelector("#english") + english = input_text.value + output_div = document.querySelector("#output") + output_div.innerText = arrr.translate(english) diff --git a/core/tests/manual/piratical/piratical.toml b/core/tests/manual/piratical/piratical.toml new file mode 100644 index 00000000000..cdebd8db7d4 --- /dev/null +++ b/core/tests/manual/piratical/piratical.toml @@ -0,0 +1 @@ +packages = ["arrr"] diff --git a/core/tests/manual/py-editor-failure.html b/core/tests/manual/py-editor-failure.html new file mode 100644 index 00000000000..6294d051f2a --- /dev/null +++ b/core/tests/manual/py-editor-failure.html @@ -0,0 +1,15 @@ + + + + + + PyEditor Failure + + + + + + + + + diff --git a/core/tests/manual/py-editor.html b/core/tests/manual/py-editor.html new file mode 100644 index 00000000000..000dda50e7b --- /dev/null +++ b/core/tests/manual/py-editor.html @@ -0,0 +1,33 @@ + + + + + + PyEditor + + + + + + + + + + diff --git a/core/tests/manual/py-editor/config.toml b/core/tests/manual/py-editor/config.toml new file mode 100644 index 00000000000..2c8a09a6454 --- /dev/null +++ b/core/tests/manual/py-editor/config.toml @@ -0,0 +1,2 @@ +[js_modules.worker] +"https://cdn.jsdelivr.net/npm/html-escaper/+esm" = "html_escaper" diff --git a/core/tests/manual/py-editor/index.html b/core/tests/manual/py-editor/index.html new file mode 100644 index 00000000000..b90f073ce47 --- /dev/null +++ b/core/tests/manual/py-editor/index.html @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + diff --git a/core/tests/manual/py-editor/issue-2056.html b/core/tests/manual/py-editor/issue-2056.html new file mode 100644 index 00000000000..3106c4fcda3 --- /dev/null +++ b/core/tests/manual/py-editor/issue-2056.html @@ -0,0 +1,17 @@ + + + + + + + + + + + + + diff --git a/core/tests/manual/py-editor/service-worker.html b/core/tests/manual/py-editor/service-worker.html new file mode 100644 index 00000000000..d42b333ec7a --- /dev/null +++ b/core/tests/manual/py-editor/service-worker.html @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/core/tests/manual/py-editor/sw.js b/core/tests/manual/py-editor/sw.js new file mode 100644 index 00000000000..1e1996cfbf0 --- /dev/null +++ b/core/tests/manual/py-editor/sw.js @@ -0,0 +1 @@ +const{isArray:e}=Array,t=new Map,s=e=>{e.stopImmediatePropagation(),e.preventDefault()};var n=Object.freeze({__proto__:null,activate:e=>e.waitUntil(clients.claim()),fetch:e=>{const{request:n}=e;"POST"===n.method&&n.url===`${location.href}?sabayon`&&(s(e),e.respondWith(n.json().then((async e=>{const{promise:s,resolve:o}=Promise.withResolvers(),a=e.join(",");t.set(a,o);for(const t of await clients.matchAll())t.postMessage(e);return s.then((e=>new Response(`[${e.join(",")}]`,n.headers)))}))))},install:()=>skipWaiting(),message:n=>{const{data:o}=n;if(e(o)&&4===o.length){const[e,a,i,r]=o,l=[e,a,i].join(",");t.has(l)&&(s(n),t.get(l)(r),t.delete(l))}}});for(const e in n)addEventListener(e,n[e]); diff --git a/core/tests/manual/py-editor/task1.py b/core/tests/manual/py-editor/task1.py new file mode 100644 index 00000000000..014e073d39a --- /dev/null +++ b/core/tests/manual/py-editor/task1.py @@ -0,0 +1,5 @@ +from pyscript import window + +window.console.log("OK") + +a = 1 diff --git a/core/tests/manual/py-terminals/index.html b/core/tests/manual/py-terminals/index.html new file mode 100644 index 00000000000..3d41ea8ba65 --- /dev/null +++ b/core/tests/manual/py-terminals/index.html @@ -0,0 +1,18 @@ + + + + + + Document + + + + + diff --git a/core/tests/manual/py-terminals/no-repl.html b/core/tests/manual/py-terminals/no-repl.html new file mode 100644 index 00000000000..ecd1d2f2f7c --- /dev/null +++ b/core/tests/manual/py-terminals/no-repl.html @@ -0,0 +1,20 @@ + + + + + + PyTerminal Prompt: NO REPL + + + + + + + + diff --git a/core/tests/manual/py-terminals/repl.html b/core/tests/manual/py-terminals/repl.html new file mode 100644 index 00000000000..e9b5f4766c0 --- /dev/null +++ b/core/tests/manual/py-terminals/repl.html @@ -0,0 +1,28 @@ + + + + + + PyTerminal Prompt: REPL + + + + + + + + diff --git a/core/tests/manual/py_modules.html b/core/tests/manual/py_modules.html new file mode 100644 index 00000000000..bb69b06c3ca --- /dev/null +++ b/core/tests/manual/py_modules.html @@ -0,0 +1,27 @@ + + + + + + + + + + + + diff --git a/core/tests/manual/service-worker/index.html b/core/tests/manual/service-worker/index.html new file mode 100644 index 00000000000..a07332b41f0 --- /dev/null +++ b/core/tests/manual/service-worker/index.html @@ -0,0 +1,16 @@ + + + + Service Worker + + + + + + + + + diff --git a/core/tests/manual/service-worker/mini-coi.js b/core/tests/manual/service-worker/mini-coi.js new file mode 100644 index 00000000000..b7a23bf2d1f --- /dev/null +++ b/core/tests/manual/service-worker/mini-coi.js @@ -0,0 +1,28 @@ +/*! coi-serviceworker v0.1.7 - Guido Zuidhof and contributors, licensed under MIT */ +/*! mini-coi - Andrea Giammarchi and contributors, licensed under MIT */ +(({ document: d, navigator: { serviceWorker: s } }) => { + if (d) { + const { currentScript: c } = d; + s.register(c.src, { scope: c.getAttribute('scope') || '.' }).then(r => { + r.addEventListener('updatefound', () => location.reload()); + if (r.active && !s.controller) location.reload(); + }); + } + else { + addEventListener('install', () => skipWaiting()); + addEventListener('activate', e => e.waitUntil(clients.claim())); + addEventListener('fetch', e => { + const { request: r } = e; + if (r.cache === 'only-if-cached' && r.mode !== 'same-origin') return; + e.respondWith(fetch(r).then(r => { + const { body, status, statusText } = r; + if (!status || status > 399) return r; + const h = new Headers(r.headers); + h.set('Cross-Origin-Opener-Policy', 'same-origin'); + h.set('Cross-Origin-Embedder-Policy', 'require-corp'); + h.set('Cross-Origin-Resource-Policy', 'cross-origin'); + return new Response(body, { status, statusText, headers: h }); + })); + }); + } +})(self); diff --git a/core/tests/manual/service-worker/sabayon.js b/core/tests/manual/service-worker/sabayon.js new file mode 100644 index 00000000000..1e1996cfbf0 --- /dev/null +++ b/core/tests/manual/service-worker/sabayon.js @@ -0,0 +1 @@ +const{isArray:e}=Array,t=new Map,s=e=>{e.stopImmediatePropagation(),e.preventDefault()};var n=Object.freeze({__proto__:null,activate:e=>e.waitUntil(clients.claim()),fetch:e=>{const{request:n}=e;"POST"===n.method&&n.url===`${location.href}?sabayon`&&(s(e),e.respondWith(n.json().then((async e=>{const{promise:s,resolve:o}=Promise.withResolvers(),a=e.join(",");t.set(a,o);for(const t of await clients.matchAll())t.postMessage(e);return s.then((e=>new Response(`[${e.join(",")}]`,n.headers)))}))))},install:()=>skipWaiting(),message:n=>{const{data:o}=n;if(e(o)&&4===o.length){const[e,a,i,r]=o,l=[e,a,i].join(",");t.has(l)&&(s(n),t.get(l)(r),t.delete(l))}}});for(const e in n)addEventListener(e,n[e]); diff --git a/core/tests/manual/shenanigans.py b/core/tests/manual/shenanigans.py new file mode 100644 index 00000000000..4fa59bcd37b --- /dev/null +++ b/core/tests/manual/shenanigans.py @@ -0,0 +1,3 @@ +import sys + +print(sys.shenanigans) diff --git a/core/tests/manual/split-config.html b/core/tests/manual/split-config.html new file mode 100644 index 00000000000..48bf8e71b80 --- /dev/null +++ b/core/tests/manual/split-config.html @@ -0,0 +1,20 @@ + + + + + + PyScript Config + + + + [[fetch]] + files = ["./a.py"] + + + + diff --git a/core/tests/manual/submit.html b/core/tests/manual/submit.html new file mode 100644 index 00000000000..65e68abd2a9 --- /dev/null +++ b/core/tests/manual/submit.html @@ -0,0 +1,15 @@ + + + + + + + + + + + + diff --git a/core/tests/manual/submit.py b/core/tests/manual/submit.py new file mode 100644 index 00000000000..e6136ee343d --- /dev/null +++ b/core/tests/manual/submit.py @@ -0,0 +1,6 @@ +from pyscript import document + + +def submit(event): + editor = document.querySelector("#editor") + editor.process(editor.code, True) diff --git a/core/tests/manual/target.html b/core/tests/manual/target.html new file mode 100644 index 00000000000..525d0e79f3d --- /dev/null +++ b/core/tests/manual/target.html @@ -0,0 +1,37 @@ + + + + + + @pyscript/core + + + + + + import pyscript + from pyscript import display + display("Hello", append=True) # Appears in a DIV that is a child of this py-script tag + pyscript.display("same", append=True) # Appears in another DIV that is a child of this py-script tag + + + # Appears in a DIV that is a child of this py-script tag, no need to re-import + display("World", append=True) + + + # Appears in a DIV that is a child of this py-script tag + # Re-importing has no effect in the essential behavior + from pyscript import display + display("A part", append=True) + + + # Use the 'target' element to specify the ID of an element in the DOM to write the content to + display("!", target="first", append=True) + + + # Appears in a DIV that is a child of this py-script tag, even with the code running in a worker + from pyscript import display + display("worker", append=True) + + + diff --git a/core/tests/manual/test_display_HTML.html b/core/tests/manual/test_display_HTML.html new file mode 100644 index 00000000000..5a0909f0a8f --- /dev/null +++ b/core/tests/manual/test_display_HTML.html @@ -0,0 +1,16 @@ + + + + + + PyScript Next: Display HTML + + + + + + from pyscript import display, HTML + display(HTML('

world

')) +
+ + diff --git a/core/tests/manual/test_when.html b/core/tests/manual/test_when.html new file mode 100644 index 00000000000..d322412e729 --- /dev/null +++ b/core/tests/manual/test_when.html @@ -0,0 +1,24 @@ + + + + + + PyScript Next: When Decorator + + + + +

Click for a hi!

+ + + from pyscript import window, when + @when("click", selector="#say-hi") + + def say_hi(event): + window.alert("Hi! 🤗") + + + + + + diff --git a/core/tests/manual/worker.html b/core/tests/manual/worker.html new file mode 100644 index 00000000000..5738444cc86 --- /dev/null +++ b/core/tests/manual/worker.html @@ -0,0 +1,39 @@ + + + + + + PyScript Next + + + + + + + + + + + + +
+ + diff --git a/core/tests/manual/worker.py b/core/tests/manual/worker.py new file mode 100644 index 00000000000..84fd294011c --- /dev/null +++ b/core/tests/manual/worker.py @@ -0,0 +1,13 @@ +import js + +js.document.body.append("document patch ") + +import a +from pyscript import RUNNING_IN_WORKER, display, sync + +display("Hello World", target="test", append=True) + +print(RUNNING_IN_WORKER) +print("sleeping") +sync.sleep(1) +print("awake") diff --git a/core/tests/py_tests.main.spec.js b/core/tests/py_tests.main.spec.js new file mode 100644 index 00000000000..02a897acede --- /dev/null +++ b/core/tests/py_tests.main.spec.js @@ -0,0 +1,21 @@ +import { test, expect } from '@playwright/test'; + +const timeout = 60 * 1000; + +test.setTimeout(timeout); + +test('Python unit tests - MicroPython on MAIN thread', async ({ page }) => { + await page.goto('http://localhost:8080/tests/python/index.html'); + const result = page.locator("#result"); // Payload for results will be here. + await result.waitFor({ timeout }); // wait for the result. + const data = JSON.parse(await result.textContent()); // get the result data. + await expect(data.fails).toMatchObject([]); // ensure no test failed. +}); + +test('Python unit tests - Pyodide on MAIN thread', async ({ page }) => { + await page.goto('http://localhost:8080/tests/python/index.html?type=py'); + const result = page.locator("#result"); // Payload for results will be here. + await result.waitFor({ timeout }); // wait for the result. + const data = JSON.parse(await result.textContent()); // get the result data. + await expect(data.fails).toMatchObject([]); // ensure no test failed. +}); diff --git a/core/tests/py_tests.worker.spec.js b/core/tests/py_tests.worker.spec.js new file mode 100644 index 00000000000..640aad75eb0 --- /dev/null +++ b/core/tests/py_tests.worker.spec.js @@ -0,0 +1,21 @@ +import { test, expect } from '@playwright/test'; + +const timeout = 120 * 1000; + +test.setTimeout(timeout); + +test('Python unit tests - MicroPython on WORKER', async ({ page }) => { + await page.goto('http://localhost:8080/tests/python/index.html?worker'); + const result = page.locator("#result"); // Payload for results will be here. + await result.waitFor({ timeout }); // wait for the result. + const data = JSON.parse(await result.textContent()); // get the result data. + await expect(data.fails).toMatchObject([]); // ensure no test failed. +}); + +test('Python unit tests - Pyodide on WORKER', async ({ page }) => { + await page.goto('http://localhost:8080/tests/python/index.html?type=py&worker'); + const result = page.locator("#result"); // Payload for results will be here. + await result.waitFor({ timeout }); // wait for the result. + const data = JSON.parse(await result.textContent()); // get the result data. + await expect(data.fails).toMatchObject([]); // ensure no test failed. +}); diff --git a/core/tests/python/example_js_module.js b/core/tests/python/example_js_module.js new file mode 100644 index 00000000000..540b4ddd770 --- /dev/null +++ b/core/tests/python/example_js_module.js @@ -0,0 +1,7 @@ +/* +A simple JavaScript module to test the integration with Python. +*/ + +export function hello() { + return "Hello from JavaScript!"; +} diff --git a/core/tests/python/example_js_worker_module.js b/core/tests/python/example_js_worker_module.js new file mode 100644 index 00000000000..c7696abd3b1 --- /dev/null +++ b/core/tests/python/example_js_worker_module.js @@ -0,0 +1,7 @@ +/* +A simple JavaScript module to test the integration with Python on a worker. +*/ + +export function hello() { + return "Hello from JavaScript in a web worker!"; +} diff --git a/core/tests/python/helper.js b/core/tests/python/helper.js new file mode 100644 index 00000000000..ae773d9a63e --- /dev/null +++ b/core/tests/python/helper.js @@ -0,0 +1,23 @@ +const qs = new URLSearchParams(location.search); + +const src = './main.py'; +let config = './settings_mpy.json'; + +// terminal=0 to NOT have a terminal +const terminal = qs.has('terminal') ? qs.get('terminal') : 1; +// worker=1 to have a worker +const worker = qs.has('worker'); + +const interpreter = qs.get('type') || 'mpy'; +if (interpreter === 'py') { + config = "./settings_py.json"; +} + +const script = document.createElement('script'); +script.type = interpreter; +if (src) script.src = src; +if (config) script.setAttribute('config', config); +script.toggleAttribute('terminal', terminal); +script.toggleAttribute('worker', worker); + +document.write(script.outerHTML); diff --git a/core/tests/python/index.html b/core/tests/python/index.html new file mode 100644 index 00000000000..f0ca795763a --- /dev/null +++ b/core/tests/python/index.html @@ -0,0 +1,76 @@ + + + + + + Pure Python PyScript tests + + + + + + + + + + + + +
+ +
+

Test Read and Write

+
Content test_rr_div
+

Content test_rr_h3

+ +
Content multi-elem-div
+

Content multi-elem-p

+

Content multi-elem-h2

+ +
+ + + + +
+ + + + + + + +
+ + + + + + +
+

+
+

+ +
+
+
+ + diff --git a/core/tests/python/main.py b/core/tests/python/main.py new file mode 100644 index 00000000000..483c8797761 --- /dev/null +++ b/core/tests/python/main.py @@ -0,0 +1,8 @@ +import json + +import upytest +from pyscript import web + +result = await upytest.run("./tests", random=True) +output = web.div(json.dumps(result), id="result") +web.page.append(output) diff --git a/core/tests/python/settings_mpy.json b/core/tests/python/settings_mpy.json new file mode 100644 index 00000000000..fb46cf3b3ff --- /dev/null +++ b/core/tests/python/settings_mpy.json @@ -0,0 +1,27 @@ +{ + "files": { + "https://raw.githubusercontent.com/ntoll/upytest/1.0.9/upytest.py": "", + "./tests/test_config.py": "tests/test_config.py", + "./tests/test_current_target.py": "tests/test_current_target.py", + "./tests/test_display.py": "tests/test_display.py", + "./tests/test_document.py": "tests/test_document.py", + "./tests/test_fetch.py": "tests/test_fetch.py", + "./tests/test_ffi.py": "tests/test_ffi.py", + "./tests/test_js_modules.py": "tests/test_js_modules.py", + "./tests/test_media.py": "tests/test_media.py", + "./tests/test_storage.py": "tests/test_storage.py", + "./tests/test_running_in_worker.py": "tests/test_running_in_worker.py", + "./tests/test_web.py": "tests/test_web.py", + "./tests/test_websocket.py": "tests/test_websocket.py", + "./tests/test_events.py": "tests/test_events.py", + "./tests/test_window.py": "tests/test_window.py" + }, + "js_modules": { + "main": { + "./example_js_module.js": "greeting" + }, + "worker": { + "./example_js_worker_module.js": "greeting_worker" + } + } +} diff --git a/core/tests/python/settings_py.json b/core/tests/python/settings_py.json new file mode 100644 index 00000000000..c9167d513d0 --- /dev/null +++ b/core/tests/python/settings_py.json @@ -0,0 +1,28 @@ +{ + "files": { + "https://raw.githubusercontent.com/ntoll/upytest/1.0.9/upytest.py": "", + "./tests/test_config.py": "tests/test_config.py", + "./tests/test_current_target.py": "tests/test_current_target.py", + "./tests/test_display.py": "tests/test_display.py", + "./tests/test_document.py": "tests/test_document.py", + "./tests/test_fetch.py": "tests/test_fetch.py", + "./tests/test_ffi.py": "tests/test_ffi.py", + "./tests/test_media.py": "tests/test_media.py", + "./tests/test_js_modules.py": "tests/test_js_modules.py", + "./tests/test_storage.py": "tests/test_storage.py", + "./tests/test_running_in_worker.py": "tests/test_running_in_worker.py", + "./tests/test_web.py": "tests/test_web.py", + "./tests/test_websocket.py": "tests/test_websocket.py", + "./tests/test_events.py": "tests/test_events.py", + "./tests/test_window.py": "tests/test_window.py" + }, + "js_modules": { + "main": { + "./example_js_module.js": "greeting" + }, + "worker": { + "./example_js_worker_module.js": "greeting_worker" + } + }, + "packages": ["Pillow" ] +} diff --git a/core/tests/python/tests/test_config.py b/core/tests/python/tests/test_config.py new file mode 100644 index 00000000000..976aefd5459 --- /dev/null +++ b/core/tests/python/tests/test_config.py @@ -0,0 +1,20 @@ +""" +Tests for the pyscript.config dictionary. +""" + +from pyscript import config, document, fetch +from upytest import is_micropython + + +async def test_config_reads_expected_settings_correctly(): + """ + The config dictionary should read expected settings for this test suite. + + Just grab the raw JSON for the settings and compare it to the config + dictionary. + """ + settings = "/settings_mpy.json" if is_micropython else "/settings_py.json" + url = document.location.href.rsplit("/", 1)[0] + settings + raw_config = await fetch(url).json() + for key, value in raw_config.items(): + assert config[key] == value, f"Expected {key} to be {value}, got {config[key]}" diff --git a/core/tests/python/tests/test_current_target.py b/core/tests/python/tests/test_current_target.py new file mode 100644 index 00000000000..cc4e24d2301 --- /dev/null +++ b/core/tests/python/tests/test_current_target.py @@ -0,0 +1,19 @@ +""" +Ensure the pyscript.current_target function returns the expected target +element's id. +""" + +from pyscript import RUNNING_IN_WORKER, current_target +from upytest import is_micropython + + +def test_current_target(): + """ + The current_target function should return the expected target element's id. + """ + expected = "py-0" + if is_micropython: + expected = "mpy-w0-target" if RUNNING_IN_WORKER else "mpy-0" + elif RUNNING_IN_WORKER: + expected = "py-w0-target" + assert current_target() == expected, f"Expected {expected} got {current_target()}" diff --git a/core/tests/python/tests/test_display.py b/core/tests/python/tests/test_display.py new file mode 100644 index 00000000000..d891bf7cca0 --- /dev/null +++ b/core/tests/python/tests/test_display.py @@ -0,0 +1,289 @@ +""" +Tests for the display function in PyScript. +""" + +import asyncio + +import upytest +from pyscript import HTML, RUNNING_IN_WORKER, display, py_import, web + + +async def get_display_container(): + """ + Get the element that contains the output of the display function. + """ + if RUNNING_IN_WORKER: + # Needed to ensure the DOM has time to catch up with the display calls + # made in the worker thread. + await asyncio.sleep(0.01) + py_display = web.page.find("script-py") + if len(py_display) == 1: + return py_display[0] + mpy_display = web.page.find("script-mpy") + if len(mpy_display) == 1: + return mpy_display[0] + return None + + +async def setup(): + """ + Setup function for the test_display.py module. Remove all references to the + display output in the DOM so we always start from a clean state. + """ + container = await get_display_container() + if container: + container.replaceChildren() + target_container = web.page.find("#test-element-container")[0] + target_container.innerHTML = "" + + +async def teardown(): + """ + Like setup. + """ + container = await get_display_container() + if container: + container.replaceChildren() + target_container = web.page.find("#test-element-container")[0] + target_container.innerHTML = "" + + +async def test_simple_display(): + """ + Test the display function with a simple string. + """ + display("Hello, world") + container = await get_display_container() + assert len(container.children) == 1, "Expected one child in the display container." + assert ( + container.children[0].tagName == "DIV" + ), "Expected a div element in the display container." + assert container.children[0].innerHTML == "Hello, world" + + +async def test_consecutive_display(): + """ + Display order should be preserved. + """ + display("hello 1") + display("hello 2") + container = await get_display_container() + assert ( + len(container.children) == 2 + ), "Expected two children in the display container." + assert container.children[0].innerHTML == "hello 1" + assert container.children[1].innerHTML == "hello 2" + + +def test_target_parameter(): + """ + The output from display is placed in the target element. + """ + display("hello world", target="test-element-container") + target = web.page.find("#test-element-container")[0] + assert target.innerText == "hello world" + + +def test_target_parameter_with_hash(): + """ + The target parameter can have a hash in front of it. + """ + display("hello world", target="#test-element-container") + target = web.page.find("#test-element-container")[0] + assert target.innerText == "hello world" + + +def test_non_existing_id_target_raises_value_error(): + """ + If the target parameter is set to a non-existing element, a ValueError should be raised. + """ + with upytest.raises(ValueError): + display("hello world", target="non-existing") + + +def test_empty_string_target_raises_value_error(): + """ + If the target parameter is an empty string, a ValueError should be raised. + """ + with upytest.raises(ValueError) as exc: + display("hello world", target="") + assert str(exc.exception) == "Cannot have an empty target" + + +def test_non_string_target_values_raise_typerror(): + """ + The target parameter must be a string. + """ + with upytest.raises(TypeError) as exc: + display("hello world", target=True) + assert str(exc.exception) == "target must be str or None, not bool" + + with upytest.raises(TypeError) as exc: + display("hello world", target=123) + assert str(exc.exception) == "target must be str or None, not int" + + +async def test_tag_target_attribute(): + """ + The order and arrangement of the display calls (including targets) should be preserved. + """ + display("item 1") + display("item 2", target="test-element-container") + display("item 3") + container = await get_display_container() + assert ( + len(container.children) == 2 + ), "Expected two children in the display container." + assert container.children[0].innerHTML == "item 1" + assert container.children[1].innerHTML == "item 3" + target = web.page.find("#test-element-container")[0] + assert target.innerText == "item 2" + + +async def test_multiple_display_calls_same_tag(): + """ + Multiple display calls in the same script tag should be displayed in order. + """ + display("item 1") + display("item 2") + container = await get_display_container() + assert ( + len(container.children) == 2 + ), "Expected two children in the display container." + assert container.children[0].innerHTML == "item 1" + assert container.children[1].innerHTML == "item 2" + + +async def test_append_true(): + """ + Explicit append flag as true should append to the expected container element. + """ + display("item 1", append=True) + display("item 2", append=True) + container = await get_display_container() + assert ( + len(container.children) == 2 + ), "Expected two children in the display container." + assert container.children[0].innerHTML == "item 1" + assert container.children[1].innerHTML == "item 2" + + +async def test_append_false(): + """ + Explicit append flag as false should replace the expected container element. + """ + display("item 1", append=False) + display("item 2", append=False) + container = await get_display_container() + assert container.innerText == "item 2" + + +async def test_display_multiple_values(): + """ + Display multiple values in the same call. + """ + display("hello", "world") + container = await get_display_container() + assert container.innerText == "hello\nworld", container.innerText + + +async def test_display_multiple_append_false(): + display("hello", "world", append=False) + container = await get_display_container() + assert container.innerText == "world" + + +def test_display_multiple_append_false_with_target(): + """ + TODO: this is a display.py issue to fix when append=False is used + do not use the first element, just clean up and then append + remove the # display comment once that's done + """ + + class Circle: + r = 0 + + def _repr_svg_(self): + return ( + f'' + f'' + ) + + circle = Circle() + circle.r += 5 + display(circle, circle, target="test-element-container", append=False) + target = web.page.find("#test-element-container")[0] + assert target.innerHTML == circle._repr_svg_() + + +async def test_display_list_dict_tuple(): + """ + Display a list, dictionary, and tuple with the expected __repr__. + + NOTE: MicroPython doesn't (yet) have ordered dicts. Hence the rather odd + check that the dictionary is displayed as a string. + """ + l = ["A", 1, "!"] + d = {"B": 2, "List": l} + t = ("C", 3, "!") + display(l, d, t) + container = await get_display_container() + l2, d2, t2 = container.innerText.split("\n") + assert l == eval(l2) + assert d == eval(d2) + assert t == eval(t2) + + +async def test_display_should_escape(): + display("

hello world

") + container = await get_display_container() + assert container[0].innerHTML == "<p>hello world</p>" + assert container.innerText == "

hello world

" + + +async def test_display_HTML(): + display(HTML("

hello world

")) + container = await get_display_container() + assert container[0].innerHTML == "

hello world

" + assert container.innerText == "hello world" + + +@upytest.skip( + "Pyodide main thread only", + skip_when=upytest.is_micropython or RUNNING_IN_WORKER, +) +async def test_image_display(): + """ + Check an image is displayed correctly. + """ + _mpl = await py_import("matplotlib") + import matplotlib.pyplot as plt + + xpoints = [3, 6, 9] + ypoints = [1, 2, 3] + plt.plot(xpoints, ypoints) + display(plt) + container = await get_display_container() + img = container.find("img")[0] + img_src = img.getAttribute("src").replace( + "data:image/png;charset=utf-8;base64,", "" + ) + assert len(img_src) > 0 + + +@upytest.skip( + "Pyodide main thread only", + skip_when=upytest.is_micropython or RUNNING_IN_WORKER, +) +async def test_image_renders_correctly(): + """ + This is just a sanity check to make sure that images are rendered + in a reasonable way. + """ + from PIL import Image + + img = Image.new("RGB", (4, 4), color=(0, 0, 0)) + display(img, target="test-element-container", append=False) + target = web.page.find("#test-element-container")[0] + img = target.find("img")[0] + assert img.src.startswith("data:image/png;charset=utf-8;base64") diff --git a/core/tests/python/tests/test_document.py b/core/tests/python/tests/test_document.py new file mode 100644 index 00000000000..24aa4176fe8 --- /dev/null +++ b/core/tests/python/tests/test_document.py @@ -0,0 +1,17 @@ +""" +Sanity check for the pyscript.document object. +""" + +from pyscript import document + + +def test_document(): + """ + The document object should be available and we can change its attributes + (in this case, the title). + """ + title = document.title + assert title + document.title = "A new title" + assert document.title == "A new title" + document.title = title diff --git a/core/tests/python/tests/test_events.py b/core/tests/python/tests/test_events.py new file mode 100644 index 00000000000..f9e37b99e59 --- /dev/null +++ b/core/tests/python/tests/test_events.py @@ -0,0 +1,360 @@ +""" +Tests for the when function and Event class. +""" + +import asyncio + +import upytest +from pyscript import RUNNING_IN_WORKER, web, Event, when + + +def get_container(): + return web.page.find("#test-element-container")[0] + + +def setup(): + container = get_container() + container.innerHTML = "" + + +def teardown(): + container = get_container() + container.innerHTML = "" + + +def test_event_add_listener(): + """ + Adding a listener to an event should add it to the list of listeners. It + should only be added once. + """ + event = Event() + listener = lambda x: x + event.add_listener(listener) + event.add_listener(listener) + assert len(event._listeners) == 1 # Only one item added. + assert listener in event._listeners # The item is the expected listener. + + +def test_event_remove_listener(): + """ + Removing a listener from an event should remove it from the list of + listeners. + """ + event = Event() + listener1 = lambda x: x + listener2 = lambda x: x + event.add_listener(listener1) + event.add_listener(listener2) + assert len(event._listeners) == 2 # Two listeners added. + assert listener1 in event._listeners # The first listener is in the list. + assert listener2 in event._listeners # The second listener is in the list. + event.remove_listener(listener1) + assert len(event._listeners) == 1 # Only one item remains. + assert listener2 in event._listeners # The second listener is in the list. + + +def test_event_remove_all_listeners(): + """ + Removing all listeners from an event should clear the list of listeners. + """ + event = Event() + listener1 = lambda x: x + listener2 = lambda x: x + event.add_listener(listener1) + event.add_listener(listener2) + assert len(event._listeners) == 2 # Two listeners added. + event.remove_listener() + assert len(event._listeners) == 0 # No listeners remain. + + +def test_event_trigger(): + """ + Triggering an event should call all of the listeners with the provided + arguments. + """ + event = Event() + counter = 0 + + def listener(x): + nonlocal counter + counter += 1 + assert x == "ok" + + event.add_listener(listener) + assert counter == 0 # The listener has not been triggered yet. + event.trigger("ok") + assert counter == 1 # The listener has been triggered with the expected result. + + +async def test_event_trigger_with_awaitable(): + """ + Triggering an event with an awaitable listener should call the listener + with the provided arguments. + """ + call_flag = asyncio.Event() + event = Event() + counter = 0 + + async def listener(x): + nonlocal counter + counter += 1 + assert x == "ok" + call_flag.set() + + event.add_listener(listener) + assert counter == 0 # The listener has not been triggered yet. + event.trigger("ok") + await call_flag.wait() + assert counter == 1 # The listener has been triggered with the expected result. + + +async def test_when_decorator_with_event(): + """ + When the decorated function takes a single parameter, + it should be passed the event object. + """ + btn = web.button("foo_button", id="foo_id") + container = get_container() + container.append(btn) + + called = False + call_flag = asyncio.Event() + + @when("click", selector="#foo_id") + def foo(evt): + nonlocal called + called = evt + call_flag.set() + + btn.click() + await call_flag.wait() + assert called.target.id == "foo_id" + + +async def test_when_decorator_without_event(): + """ + When the decorated function takes no parameters (not including 'self'), + it should be called without the event object. + """ + btn = web.button("foo_button", id="foo_id") + container = get_container() + container.append(btn) + + called = False + call_flag = asyncio.Event() + + @web.when("click", selector="#foo_id") + def foo(): + nonlocal called + called = True + call_flag.set() + + btn.click() + await call_flag.wait() + assert called is True + + +async def test_when_decorator_with_event_as_async_handler(): + """ + When the decorated function takes a single parameter, + it should be passed the event object. Async version. + """ + btn = web.button("foo_button", id="foo_id") + container = get_container() + container.append(btn) + + called = False + call_flag = asyncio.Event() + + @when("click", selector="#foo_id") + async def foo(evt): + nonlocal called + called = evt + call_flag.set() + + btn.click() + await call_flag.wait() + assert called.target.id == "foo_id" + + +async def test_when_decorator_without_event_as_async_handler(): + """ + When the decorated function takes no parameters (not including 'self'), + it should be called without the event object. Async version. + """ + btn = web.button("foo_button", id="foo_id") + container = get_container() + container.append(btn) + + called = False + call_flag = asyncio.Event() + + @web.when("click", selector="#foo_id") + async def foo(): + nonlocal called + called = True + call_flag.set() + + btn.click() + await call_flag.wait() + assert called is True + + +async def test_two_when_decorators(): + """ + When decorating a function twice, both should function + """ + btn = web.button("foo_button", id="foo_id") + container = get_container() + container.append(btn) + + called1 = False + called2 = False + call_flag1 = asyncio.Event() + call_flag2 = asyncio.Event() + + @when("click", selector="#foo_id") + def foo1(evt): + nonlocal called1 + called1 = True + call_flag1.set() + + @when("click", selector="#foo_id") + def foo2(evt): + nonlocal called2 + called2 = True + call_flag2.set() + + btn.click() + await call_flag1.wait() + await call_flag2.wait() + assert called1 + assert called2 + + +async def test_when_decorator_multiple_elements(): + """ + The @when decorator's selector should successfully select multiple + DOM elements + """ + btn1 = web.button( + "foo_button1", + id="foo_id1", + classes=[ + "foo_class", + ], + ) + btn2 = web.button( + "foo_button2", + id="foo_id2", + classes=[ + "foo_class", + ], + ) + container = get_container() + container.append(btn1) + container.append(btn2) + + counter = 0 + call_flag1 = asyncio.Event() + call_flag2 = asyncio.Event() + + @when("click", selector=".foo_class") + def foo(evt): + nonlocal counter + counter += 1 + if evt.target.id == "foo_id1": + call_flag1.set() + else: + call_flag2.set() + + assert counter == 0, counter + btn1.click() + await call_flag1.wait() + assert counter == 1, counter + btn2.click() + await call_flag2.wait() + assert counter == 2, counter + + +@upytest.skip( + "Only works in Pyodide on main thread", + skip_when=upytest.is_micropython or RUNNING_IN_WORKER, +) +def test_when_decorator_invalid_selector(): + """ + When the selector parameter of @when is invalid, it should raise an error. + """ + if upytest.is_micropython: + from jsffi import JsException + else: + from pyodide.ffi import JsException + + with upytest.raises(JsException) as e: + + @when("click", selector="#.bad") + def foo(evt): ... + + assert "'#.bad' is not a valid selector" in str(e.exception), str(e.exception) + + +def test_when_decorates_an_event(): + """ + When the @when decorator is used on a function to handle an Event instance, + the function should be called when the Event object is triggered. + """ + + whenable = Event() + counter = 0 + + # When as a decorator. + @when(whenable) + def handler(result): + """ + A function that should be called when the whenable object is triggered. + + The result generated by the whenable object should be passed to the + function. + """ + nonlocal counter + counter += 1 + assert result == "ok" + + # The function should not be called until the whenable object is triggered. + assert counter == 0 + # Trigger the whenable object. + whenable.trigger("ok") + # The function should have been called when the whenable object was + # triggered. + assert counter == 1 + + +def test_when_called_with_an_event_and_handler(): + """ + The when function should be able to be called with an Event object, + and a handler function. + """ + whenable = Event() + counter = 0 + + def handler(result): + """ + A function that should be called when the whenable object is triggered. + + The result generated by the whenable object should be passed to the + function. + """ + nonlocal counter + counter += 1 + assert result == "ok" + + # When as a function. + when(whenable, handler) + + # The function should not be called until the whenable object is triggered. + assert counter == 0 + # Trigger the whenable object. + whenable.trigger("ok") + # The function should have been called when the whenable object was + # triggered. + assert counter == 1 diff --git a/core/tests/python/tests/test_fetch.py b/core/tests/python/tests/test_fetch.py new file mode 100644 index 00000000000..0af2322a751 --- /dev/null +++ b/core/tests/python/tests/test_fetch.py @@ -0,0 +1,83 @@ +""" +Ensure the pyscript.test function behaves as expected. +""" + +from pyscript import fetch + + +async def test_fetch_json(): + """ + The fetch function should return the expected JSON response. + """ + response = await fetch("https://jsonplaceholder.typicode.com/todos/1") + assert response.ok + data = await response.json() + assert data["userId"] == 1 + assert data["id"] == 1 + assert data["title"] == "delectus aut autem" + assert data["completed"] is False + + +async def test_fetch_text(): + """ + The fetch function should return the expected text response. + """ + response = await fetch("https://jsonplaceholder.typicode.com/todos/1") + assert response.ok + text = await response.text() + assert "delectus aut autem" in text + assert "completed" in text + assert "false" in text + assert "1" in text + + +async def test_fetch_bytearray(): + """ + The fetch function should return the expected bytearray response. + """ + response = await fetch("https://jsonplaceholder.typicode.com/todos/1") + assert response.ok + data = await response.bytearray() + assert b"delectus aut autem" in data + assert b"completed" in data + assert b"false" in data + assert b"1" in data + + +async def test_fetch_array_buffer(): + """ + The fetch function should return the expected array buffer response. + """ + response = await fetch("https://jsonplaceholder.typicode.com/todos/1") + assert response.ok + data = await response.arrayBuffer() + bytes_ = bytes(data) + assert b"delectus aut autem" in bytes_ + assert b"completed" in bytes_ + assert b"false" in bytes_ + assert b"1" in bytes_ + + +async def test_fetch_ok(): + """ + The fetch function should return a response with ok set to True for an + existing URL. + """ + response = await fetch("https://jsonplaceholder.typicode.com/todos/1") + assert response.ok + assert response.status == 200 + data = await response.json() + assert data["userId"] == 1 + assert data["id"] == 1 + assert data["title"] == "delectus aut autem" + assert data["completed"] is False + + +async def test_fetch_not_ok(): + """ + The fetch function should return a response with ok set to False for a + non-existent URL. + """ + response = await fetch("https://jsonplaceholder.typicode.com/todos/1000") + assert not response.ok + assert response.status == 404 diff --git a/core/tests/python/tests/test_ffi.py b/core/tests/python/tests/test_ffi.py new file mode 100644 index 00000000000..4957598484e --- /dev/null +++ b/core/tests/python/tests/test_ffi.py @@ -0,0 +1,40 @@ +""" +Exercise (as much as is possible) the pyscript.ffi namespace. +""" + +import upytest +from pyscript import ffi + + +def test_create_proxy(): + """ + The create_proxy function should return a proxy object that is callable. + """ + + def func(): + return 42 + + proxy = ffi.create_proxy(func) + assert proxy() == 42 + if upytest.is_micropython: + from jsffi import JsProxy + else: + from pyodide.ffi import JsProxy + assert isinstance(proxy, JsProxy) + + +def test_to_js(): + """ + The to_js function should convert a Python object to a JavaScript object. + In this instance, a Python dict should be converted to a JavaScript object + represented by a JsProxy object. + """ + obj = {"a": 1, "b": 2} + js_obj = ffi.to_js(obj) + assert js_obj.a == 1 + assert js_obj.b == 2 + if upytest.is_micropython: + from jsffi import JsProxy + else: + from pyodide.ffi import JsProxy + assert isinstance(js_obj, JsProxy) diff --git a/core/tests/python/tests/test_js_modules.py b/core/tests/python/tests/test_js_modules.py new file mode 100644 index 00000000000..db474a9426a --- /dev/null +++ b/core/tests/python/tests/test_js_modules.py @@ -0,0 +1,52 @@ +""" +Ensure referenced JavaScript modules are available via the pyscript.js_modules +object. +""" + +import upytest +from pyscript import RUNNING_IN_WORKER + + +@upytest.skip("Main thread only.", skip_when=RUNNING_IN_WORKER) +def test_js_module_is_available_on_main(): + """ + The "hello" function in the example_js_module.js file is available via the + js_modules object while running in the main thread. See the settings.json + file for the configuration that makes this possible. + """ + from pyscript.js_modules import greeting + + assert greeting.hello() == "Hello from JavaScript!" + + +@upytest.skip("Worker only.", skip_when=not RUNNING_IN_WORKER) +def test_js_module_is_available_on_worker(): + """ + The "hello" function in the example_js_module.js file is available via the + js_modules object while running in a worker. See the settings.json file for + the configuration that makes this possible. + """ + from pyscript.js_modules import greeting + + assert greeting.hello() == "Hello from JavaScript!" + + +@upytest.skip("Worker only.", skip_when=not RUNNING_IN_WORKER) +def test_js_module_is_available_on_worker(): + """ + The "hello" function in the example_js_worker_module.js file is available + via the js_modules object while running in a worker. + """ + from pyscript.js_modules import greeting_worker + + assert greeting_worker.hello() == "Hello from JavaScript in a web worker!" + + +@upytest.skip("Main thread only.", skip_when=RUNNING_IN_WORKER) +def test_js_worker_module_is_not_available_on_main(): + """ + The "hello" function in the example_js_worker_module.js file is not + available via the js_modules object while running in the main thread. + """ + with upytest.raises(ImportError): + from pyscript.js_modules import greeting_worker diff --git a/core/tests/python/tests/test_media.py b/core/tests/python/tests/test_media.py new file mode 100644 index 00000000000..fd9658383cb --- /dev/null +++ b/core/tests/python/tests/test_media.py @@ -0,0 +1,87 @@ +"""" +Tests for the PyScript media module. +""" + +from pyscript import media +import upytest + +from pyscript import media + + +@upytest.skip( + "Uses Pyodide-specific to_js function in MicroPython", + skip_when=upytest.is_micropython, +) +async def test_device_enumeration(): + """Test enumerating media devices.""" + devices = await media.list_devices() + assert isinstance(devices, list), "list_devices should return a list" + + # If devices are found, verify they have the expected functionality + if devices: + device = devices[0] + + # Test real device properties exist (but don't assert on their values) + # Browser security might restrict actual values until permissions are granted + assert hasattr(device, "id"), "Device should have id property" + assert hasattr(device, "kind"), "Device should have kind property" + assert device.kind in [ + "videoinput", + "audioinput", + "audiooutput", + ], f"Device should have a valid kind, got: {device.kind}" + + # Verify dictionary access works with actual device + assert ( + device["id"] == device.id + ), "Dictionary access should match property access" + assert ( + device["kind"] == device.kind + ), "Dictionary access should match property access" + + +@upytest.skip("Waiting on a bug-fix in MicroPython, for this test to work.", skip_when=upytest.is_micropython) +async def test_video_stream_acquisition(): + """Test video stream.""" + try: + # Load a video stream + stream = await media.Device.load(video=True) + + # Verify we get a real stream with expected properties + assert hasattr(stream, "active"), "Stream should have active property" + + # Check for video tracks, but don't fail if permissions aren't granted + if stream._dom_element and hasattr(stream._dom_element, "getVideoTracks"): + tracks = stream._dom_element.getVideoTracks() + if tracks.length > 0: + assert True, "Video stream has video tracks" + except Exception as e: + # If the browser blocks access, the test should still pass + # This is because we're testing the API works, not that permissions are granted + assert ( + True + ), f"Stream acquisition attempted but may require permissions: {str(e)}" + + +@upytest.skip("Waiting on a bug-fix in MicroPython, for this test to work.", skip_when=upytest.is_micropython) +async def test_custom_video_constraints(): + """Test loading video with custom constraints.""" + try: + # Define custom constraints + constraints = {"width": 640, "height": 480} + + # Load stream with custom constraints + stream = await media.Device.load(video=constraints) + + # Basic stream property check + assert hasattr(stream, "active"), "Stream should have active property" + + # Check for tracks only if we have access + if stream._dom_element and hasattr(stream._dom_element, "getVideoTracks"): + tracks = stream._dom_element.getVideoTracks() + if tracks.length > 0 and hasattr(tracks[0], "getSettings"): + # Settings verification is optional - browsers may handle constraints differently + pass + except Exception as e: + # If the browser blocks access, test that the API structure works + assert True, f"Custom constraint test attempted: {str(e)}" diff --git a/core/tests/python/tests/test_running_in_worker.py b/core/tests/python/tests/test_running_in_worker.py new file mode 100644 index 00000000000..de7b6b89fbc --- /dev/null +++ b/core/tests/python/tests/test_running_in_worker.py @@ -0,0 +1,27 @@ +""" +Ensure the pyscript.RUNNING_IN_WORKER flag is set correctly (a sanity check). +""" + +import upytest +from pyscript import RUNNING_IN_WORKER, document + +# In the test suite, running in a worker is flagged by the presence of the +# "worker" query string. We do this to avoid using RUNNING_IN_WORKER to skip +# tests that check RUNNING_IN_WORKER. +in_worker = "worker" in document.location.search.lower() + + +@upytest.skip("Main thread only.", skip_when=in_worker) +def test_running_in_main(): + """ + The flag should be False. + """ + assert RUNNING_IN_WORKER is False + + +@upytest.skip("Worker only.", skip_when=not in_worker) +def test_running_in_worker(): + """ + The flag should be True. + """ + assert RUNNING_IN_WORKER is True diff --git a/core/tests/python/tests/test_storage.py b/core/tests/python/tests/test_storage.py new file mode 100644 index 00000000000..674a82b3977 --- /dev/null +++ b/core/tests/python/tests/test_storage.py @@ -0,0 +1,88 @@ +""" +Ensure the pyscript.storage object behaves as a Python dict. +""" + +from pyscript import Storage, storage + +test_store = None + + +async def setup(): + global test_store + if test_store is None: + test_store = await storage("test_store") + test_store.clear() + await test_store.sync() + + +async def teardown(): + if test_store: + test_store.clear() + await test_store.sync() + + +async def test_storage_as_dict(): + """ + The storage object should behave as a Python dict. + """ + # Assign + test_store["a"] = 1 + # Retrieve + assert test_store["a"] == 1 + assert "a" in test_store + assert len(test_store) == 1 + # Iterate + for k, v in test_store.items(): + assert k == "a" + assert v == 1 + # Remove + del test_store["a"] + assert "a" not in test_store + assert len(test_store) == 0 + + +async def test_storage_types(): + """ + The storage object should support different types of values. + """ + test_store["boolean"] = False + test_store["integer"] = 42 + test_store["float"] = 3.14 + test_store["string"] = "hello" + test_store["none"] = None + test_store["list"] = [1, 2, 3] + test_store["dict"] = {"a": 1, "b": 2} + test_store["tuple"] = (1, 2, 3) + test_store["bytearray"] = bytearray(b"hello") + test_store["memoryview"] = memoryview(b"hello") + await test_store.sync() + assert test_store["boolean"] is False + assert isinstance(test_store["boolean"], bool) + assert test_store["integer"] == 42 + assert isinstance(test_store["integer"], int) + assert test_store["float"] == 3.14 + assert isinstance(test_store["float"], float) + assert test_store["string"] == "hello" + assert isinstance(test_store["string"], str) + assert test_store["none"] is None + assert test_store["list"] == [1, 2, 3] + assert isinstance(test_store["list"], list) + assert test_store["dict"] == {"a": 1, "b": 2} + assert isinstance(test_store["dict"], dict) + assert test_store["tuple"] == (1, 2, 3) + assert isinstance(test_store["tuple"], tuple) + assert test_store["bytearray"] == bytearray(b"hello") + assert isinstance(test_store["bytearray"], bytearray) + assert test_store["memoryview"] == memoryview(b"hello") + assert isinstance(test_store["memoryview"], memoryview) + + +async def test_storage_clear(): + """ + The clear method should remove all items from the storage object. + """ + test_store["a"] = 1 + test_store["b"] = 2 + assert len(test_store) == 2 + test_store.clear() + assert len(test_store) == 0 diff --git a/core/tests/python/tests/test_util.py b/core/tests/python/tests/test_util.py new file mode 100644 index 00000000000..ebf15c6b6de --- /dev/null +++ b/core/tests/python/tests/test_util.py @@ -0,0 +1,48 @@ +import upytest +import js +from pyscript import util + + +def test_as_bytearray(): + """ + Test the as_bytearray function correctly converts a JavaScript ArrayBuffer + to a Python bytearray. + """ + msg = b"Hello, world!" + buffer = js.ArrayBuffer.new(len(msg)) + ui8a = js.Uint8Array.new(buffer) + for b in msg: + ui8a[i] = b + ba = util.as_bytearray(buffer) + assert isinstance(ba, bytearray) + assert ba == msg + + +def test_not_supported(): + """ + Test the NotSupported class raises an exception when trying to access + attributes or call the object. + """ + ns = util.NotSupported("test", "This is not supported.") + with upytest.raises(AttributeError) as e: + ns.test + assert str(e.exception) == "This is not supported.", str(e.exception) + with upytest.raises(AttributeError) as e: + ns.test = 1 + assert str(e.exception) == "This is not supported.", str(e.exception) + with upytest.raises(TypeError) as e: + ns() + assert str(e.exception) == "This is not supported.", str(e.exception) + + +def test_is_awaitable(): + """ + Test the is_awaitable function correctly identifies an asynchronous + function. + """ + + async def async_func(): + yield + + assert util.is_awaitable(async_func) + assert not util.is_awaitable(lambda: None) diff --git a/core/tests/python/tests/test_web.py b/core/tests/python/tests/test_web.py new file mode 100644 index 00000000000..19bc8ab44bb --- /dev/null +++ b/core/tests/python/tests/test_web.py @@ -0,0 +1,1187 @@ +""" +Tests for the pyscript.web module. +""" + +import asyncio + +import upytest +from pyscript import RUNNING_IN_WORKER, document, web, when + + +def setup(): + container = web.page.find("#test-element-container")[0] + container.innerHTML = "" + + +def teardown(): + container = web.page.find("#test-element-container")[0] + container.innerHTML = "" + + +def test_getitem_by_id(): + """ + An element with an id in the DOM can be retrieved by id. + """ + result = web.page.find("#div-no-classes") + # There is a single result. + assert len(result) == 1 + # The result is a div. + assert result[0].get_tag_name() == "div" + + +def test_getitem_by_class(): + ids = [ + "test_class_selector", + "test_selector_w_children", + "test_selector_w_children_child_1", + ] + expected_class = "a-test-class" + result = web.page.find(f".{expected_class}") + + # EXPECT to find exact number of elements with the class in the page (== 3) + assert len(result) == 3 + + # EXPECT that all element ids are in the expected list + assert [el.id for el in result] == ids + + +def test_read_n_write_collection_elements(): + elements = web.page.find(".multi-elems") + + for element in elements: + assert element.innerHTML == f"Content {element.id.replace('#', '')}" + + new_content = "New Content" + elements.innerHTML = new_content + for element in elements: + assert element.innerHTML == new_content + + +class TestElement: + + def test_query(self): + # GIVEN an existing element on the page, with at least 1 child element + id_ = "test_selector_w_children" + parent_div = web.page.find(f"#{id_}")[0] + + # EXPECT it to be able to query for the first child element + div = parent_div.find("div")[0] + + # EXPECT the new element to be associated with the parent + assert ( + div.parent.id == parent_div.id + ), f"The parent of the new element should be the parent div, but got {div.parent} instead of {parent_div}" + # EXPECT the new element to be an Element + assert isinstance(div, web.Element), "The new element should be an Element" + # EXPECT the div attributes to be == to how they are configured in the page + assert ( + div.innerHTML == "Child 1" + ), f"The innerHTML of the div should be 'Child 1', but got {div.innerHTML}" + assert ( + div.id == "test_selector_w_children_child_1" + ), f"The id of the div should be 'test_selector_w_children_child_1', but got {div.id}" + + def test_equality(self): + # GIVEN 2 different Elements pointing to the same underlying element + id_ = "test_id_selector" + selector = f"#{id_}" + div = web.page.find(selector)[0] + div2 = web.page.find(selector)[0] + + # EXPECT them to be equal + assert div.id == div2.id + # EXPECT them to be different objects + assert div is not div2 + + # EXPECT their value to always be equal + assert div.innerHTML == div2.innerHTML + div.innerHTML = "some value" + + assert div.innerHTML == div2.innerHTML == "some value" + + def test_append_element(self): + id_ = "element-append-tests" + div = web.page.find(f"#{id_}")[0] + len_children_before = len(div.children) + new_el = web.p("new element") + div.append(new_el) + assert len(div.children) == len_children_before + 1 + assert div.children[-1].id == new_el.id + + def test_append_dom_element_element(self): + id_ = "element-append-tests" + div = web.page.find(f"#{id_}")[0] + len_children_before = len(div.children) + new_el = web.p("new element") + div.append(new_el._dom_element) + assert len(div.children) == len_children_before + 1 + assert div.children[-1].id == new_el.id + + def test_append_collection(self): + id_ = "element-append-tests" + div = web.page.find(f"#{id_}")[0] + len_children_before = len(div.children) + collection = web.page.find(".collection") + div.append(collection) + assert len(div.children) == len_children_before + len(collection) + + for i in range(len(collection)): + assert div.children[-1 - i].id == collection[-1 - i].id + + def test_read_classes(self): + id_ = "test_class_selector" + expected_class = "a-test-class" + div = web.page.find(f"#{id_}")[0] + assert div.classes == [expected_class] + + def test_add_remove_class(self): + id_ = "div-no-classes" + classname = "tester-class" + div = web.page.find(f"#{id_}")[0] + assert not div.classes + div.classes.add(classname) + same_div = web.page.find(f"#{id_}")[0] + assert div.classes == [classname] == same_div.classes + div.classes.remove(classname) + assert div.classes == [] == same_div.classes + + async def test_when_decorator(self): + called = False + + just_a_button = web.page.find("#a-test-button")[0] + call_flag = asyncio.Event() + + @when("click", just_a_button) + def on_click(event): + nonlocal called + called = True + call_flag.set() + + # Now let's simulate a click on the button (using the low level JS API) + # so we don't risk dom getting in the way + assert not called + just_a_button._dom_element.click() + await call_flag.wait() + assert called + + async def test_when_decorator_on_event(self): + called = False + + another_button = web.page.find("#another-test-button")[0] + call_flag = asyncio.Event() + + assert another_button.on_click is not None + assert isinstance(another_button.on_click, web.Event) + + @when(another_button.on_click) + def on_click(event): + nonlocal called + called = True + call_flag.set() + + # Now let's simulate a click on the button (using the low level JS API) + # so we don't risk dom getting in the way + assert not called + another_button._dom_element.click() + await call_flag.wait() + assert called + + async def test_on_event_with_default_handler(self): + called = False + call_flag = asyncio.Event() + + def handler(event): + nonlocal called + called = True + call_flag.set() + + b = web.button("Click me", on_click=handler) + + # Now let's simulate a click on the button (using the low level JS API) + # so we don't risk dom getting in the way + assert not called + b._dom_element.click() + await call_flag.wait() + assert called + + def test_on_event_must_be_actual_event(self): + """ + Any on_FOO event must relate to an actual FOO event on the element. + """ + b = web.button("Click me") + # Non-existent event causes a ValueError + with upytest.raises(ValueError): + b.on_chicken + # Buttons have an underlying "click" event so this will work. + assert b.on_click + + def test_inner_html_attribute(self): + # GIVEN an existing element on the page with a known empty text content + div = web.page.find("#element_attribute_tests")[0] + + # WHEN we set the html attribute + div.innerHTML = "New Content" + + # EXPECT the element html and underlying JS Element innerHTML property + # to match what we expect and what + assert div.innerHTML == div._dom_element.innerHTML == "New Content" + assert div.textContent == div._dom_element.textContent == "New Content" + + def test_text_attribute(self): + # GIVEN an existing element on the page with a known empty text content + div = web.page.find("#element_attribute_tests")[0] + + # WHEN we set the html attribute + div.textContent = "New Content" + + # EXPECT the element html and underlying JS Element innerHTML property + # to match what we expect and what + assert ( + div.innerHTML + == div._dom_element.innerHTML + == "<b>New Content</b>" + ) + assert div.textContent == div._dom_element.textContent == "New Content" + + +class TestCollection: + + def test_iter_eq_children(self): + elements = web.page.find(".multi-elems") + assert list(elements) == list(elements.elements) + assert len(elements) == 3 + + def test_slices(self): + elements = web.page.find(".multi-elems") + assert elements[0] + _slice = elements[:2] + assert len(_slice) == 2 + for i, el in enumerate(_slice): + assert el == elements[i] + assert elements[:] == elements + + def test_style_rule(self): + selector = ".multi-elems" + elements = web.page.find(selector) + for el in elements: + assert el.style["background-color"] != "red" + + elements.style["background-color"] = "red" + + for i, el in enumerate(web.page.find(selector)): + assert elements[i].style["background-color"] == "red" + assert el.style["background-color"] == "red" + + elements.style.remove("background-color") + + for i, el in enumerate(web.page.find(selector)): + assert el.style["background-color"] != "red" + assert elements[i].style["background-color"] != "red" + + @upytest.skip( + "Flakey in Pyodide on Worker", + skip_when=RUNNING_IN_WORKER and not upytest.is_micropython, + ) + async def test_when_decorator(self): + called = False + call_flag = asyncio.Event() + + buttons_collection = web.page["button"] + + @when("click", buttons_collection) + def on_click(event): + nonlocal called + called = True + call_flag.set() + + # Now let's simulate a click on the button (using the low level JS API) + # so we don't risk dom getting in the way + assert not called + for button in buttons_collection: + button._dom_element.click() + await call_flag.wait() + assert called + called = False + call_flag.clear() + + async def test_when_decorator_on_event(self): + call_counter = 0 + call_flag = asyncio.Event() + + buttons_collection = web.page.find("button") + number_of_clicks = len(buttons_collection) + + @when(buttons_collection.on_click) + def on_click(event): + nonlocal call_counter + call_counter += 1 + if call_counter == number_of_clicks: + call_flag.set() + + # Now let's simulate a click on the button (using the low level JS API) + # so we don't risk dom getting in the way + assert call_counter == 0 + for button in buttons_collection: + button._dom_element.click() + await call_flag.wait() + assert call_counter == number_of_clicks + + +class TestCreation: + + def test_create_document_element(self): + # TODO: This test should probably be removed since it's testing the elements + # module. + new_el = web.div("new element") + new_el.id = "new_el_id" + assert isinstance(new_el, web.Element) + assert new_el._dom_element.tagName == "DIV" + # EXPECT the new element to be associated with the document + assert new_el.parent is None + web.page.body.append(new_el) + + assert web.page.find("#new_el_id")[0].parent.tagName == web.page.body.tagName + + def test_create_element_child(self): + selector = "#element-creation-test" + parent_div = web.page.find(selector)[0] + + # Creating an element from another element automatically creates that element + # as a child of the original element + new_el = web.p( + "a div", + classes=["code-description"], + innerHTML="Ciao PyScripters!", + id="test-new-el", + ) + parent_div.append(new_el) + + assert isinstance(new_el, web.Element) + assert new_el._dom_element.tagName == "P" + + # EXPECT the new element to be associated with the document + assert new_el.parent.id == parent_div.id + assert web.page.find(selector)[0].children[0].id == new_el.id + + +class TestInput: + + input_ids = [ + "test_rr_input_text", + "test_rr_input_button", + "test_rr_input_email", + "test_rr_input_password", + ] + + def test_value(self): + for id_ in self.input_ids: + expected_type = id_.split("_")[-1] + result = web.page.find(f"#{id_}") + input_el = result[0] + assert input_el._dom_element.type == expected_type + assert ( + input_el.value == f"Content {id_}" == input_el._dom_element.value + ), f"Expected '{input_el.value}' to be 'Content {id_}' to be '{input_el._dom_element.value}'" + + # Check that we can set the value + new_value = f"New Value {expected_type}" + input_el.value = new_value + assert input_el.value == new_value + + # Check that we can set the value back to the original using + # the collection + new_value = f"Content {id_}" + result.value = new_value + assert input_el.value == new_value + + def test_set_value_collection(self): + for id_ in self.input_ids: + input_el = web.page.find(f"#{id_}") + + assert input_el.value[0] == f"Content {id_}" == input_el[0].value + + new_value = f"New Value {id_}" + input_el.value = new_value + assert ( + input_el.value[0] == new_value == input_el[0].value + ), f"Expected '{input_el.value}' to be 'Content {id_}' to be '{input_el._dom_element.value}'" + + new_value = f"Content {id_}" + input_el.value = new_value + + # TODO: We only attach attributes to the classes that have them now which means we + # would have to have some other way to help users if using attributes that aren't + # actually on the class. Maybe a job for __setattr__? + # + # def test_element_without_value(self): + # result = web.page.find(f"#tests-terminal"][0] + # with upytest.raises(AttributeError): + # result.value = "some value" + # + # def test_element_without_value_via_collection(self): + # result = web.page.find(f"#tests-terminal"] + # with upytest.raises(AttributeError): + # result.value = "some value" + + +class TestSelect: + + def test_select_options_iter(self): + select = web.page.find("#test_select_element_w_options")[0] + + for i, option in enumerate(select.options, 1): + assert option.value == f"{i}" + assert option.innerHTML == f"Option {i}" + + def test_select_options_len(self): + select = web.page.find("#test_select_element_w_options")[0] + assert len(select.options) == 2 + + def test_select_options_clear(self): + select = web.page.find("#test_select_element_to_clear")[0] + assert len(select.options) == 3 + + select.options.clear() + + assert len(select.options) == 0 + + def test_select_element_add(self): + # GIVEN the existing select element with no options + select = web.page.find("#test_select_element")[0] + + # EXPECT the select element to have no options + assert len(select.options) == 0 + + # WHEN we add an option + select.options.add(value="1", html="Option 1") + + # EXPECT the select element to have 1 option matching the attributes + # we passed in + assert len(select.options) == 1 + assert select.options[0].value == "1" + assert select.options[0].innerHTML == "Option 1" + + # WHEN we add another option (blank this time) + select.options.add("") + + # EXPECT the select element to have 2 options + assert len(select.options) == 2 + + # EXPECT the last option to have an empty value and html + assert select.options[1].value == "" + assert select.options[1].innerHTML == "" + + # WHEN we add another option (this time adding it in between the other 2 + # options by using an integer index) + select.options.add(value="2", html="Option 2", before=1) + + # EXPECT the select element to have 3 options + assert len(select.options) == 3 + + # EXPECT the middle option to have the value and html we passed in + assert select.options[0].value == "1" + assert select.options[0].innerHTML == "Option 1" + assert select.options[1].value == "2" + assert select.options[1].innerHTML == "Option 2" + assert select.options[2].value == "" + assert select.options[2].innerHTML == "" + + # WHEN we add another option (this time adding it in between the other 2 + # options but using the option itself) + select.options.add( + value="3", html="Option 3", before=select.options[2], selected=True + ) + + # EXPECT the select element to have 3 options + assert len(select.options) == 4 + + # EXPECT the middle option to have the value and html we passed in + assert select.options[0].value == "1" + assert select.options[0].innerHTML == "Option 1" + assert select.options[0].selected == select.options[0]._dom_element.selected + assert select.options[0].selected is False + assert select.options[1].value == "2" + assert select.options[1].innerHTML == "Option 2" + assert select.options[2].value == "3" + assert select.options[2].innerHTML == "Option 3" + assert select.options[2].selected == select.options[2]._dom_element.selected + assert select.options[2].selected is True + assert select.options[3].value == "" + assert select.options[3].innerHTML == "" + + # WHEN we add another option (this time adding it in between the other 2 + # options but using the JS element of the option itself) + select.options.add( + value="2a", html="Option 2a", before=select.options[2]._dom_element + ) + + # EXPECT the select element to have 3 options + assert len(select.options) == 5 + + # EXPECT the middle option to have the value and html we passed in + assert select.options[0].value == "1" + assert select.options[0].innerHTML == "Option 1" + assert select.options[1].value == "2" + assert select.options[1].innerHTML == "Option 2" + assert select.options[2].value == "2a" + assert select.options[2].innerHTML == "Option 2a" + assert select.options[3].value == "3" + assert select.options[3].innerHTML == "Option 3" + assert select.options[4].value == "" + assert select.options[4].innerHTML == "" + + def test_select_options_remove(self): + # GIVEN the existing select element with 3 options + select = web.page.find("#test_select_element_to_remove")[0] + + # EXPECT the select element to have 3 options + assert len(select.options) == 4 + # EXPECT the options to have the values originally set + assert select.options[0].value == "1" + assert select.options[1].value == "2" + assert select.options[2].value == "3" + assert select.options[3].value == "4" + + # WHEN we remove the second option (index starts at 0) + select.options.remove(1) + + # EXPECT the select element to have 2 options + assert len(select.options) == 3 + # EXPECT the options to have the values originally set but the second + assert select.options[0].value == "1" + assert select.options[1].value == "3" + assert select.options[2].value == "4" + + def test_select_get_selected_option(self): + # GIVEN the existing select element with one selected option + select = web.page.find("#test_select_element_w_options")[0] + + # WHEN we get the selected option + selected_option = select.options.selected + + # EXPECT the selected option to be correct + assert selected_option.value == "2" + assert selected_option.innerHTML == "Option 2" + assert selected_option.selected == selected_option._dom_element.selected + assert selected_option.selected is True + + +class TestElements: + """ + This class tests all elements in the pyweb.ui.elements module. It creates + an element of each type, both executing in the main thread and in a worker. + It runs each test for each interpreter defined in `INTERPRETERS` + + Each individual element test looks for the element properties, sets a value + on each the supported properties and checks if the element was created correctly + and all it's properties were set correctly. + """ + + def __init__(self): + # This module's setup function ensures self.container is empty. + self.container = web.page.find("#test-element-container")[0] + + def _create_el_and_basic_asserts( + self, + el_type, + el_text=None, + properties=None, + additional_selector_rules=None, + ): + """ + Create an element with all its properties set then check if the + element was created correctly and all its properties were set correctly. + """ + if not properties: + properties = {} + + def parse_value(v): + if isinstance(v, bool): + return str(v) + + return f"{v}" + + args = [] + kwargs = {} + if el_text: + args.append(el_text) + + if properties: + kwargs = {k: parse_value(v) for k, v in properties.items()} + + # Let's make sure the target div to contain the element is empty. + container = web.page["#test-element-container"][0] + container.innerHTML = "" + assert container.innerHTML == "", container.innerHTML + + # Let's create the element + try: + klass = getattr(web, el_type) + el = klass(*args, **kwargs) + container.append(el) + except Exception as e: + msg = f"Failed to create element {el_type}: {e}" + raise AssertionError(msg) + + # Let's keep the tag in 2 variables, one for the selector and another to + # check the return tag from the selector + locator_type = el_tag = el_type[:-1] if el_type.endswith("_") else el_type + if additional_selector_rules: + locator_type += f"{additional_selector_rules}" + + el = container.find(locator_type)[0] + el.tagName == el_tag.upper() + if el_text: + assert ( + el.innerHTML == el_text + ), f"In {el.tagName}, expected {el_text} but got {el.innerHTML}" + assert el.textContent == el_text + + if properties: + for k, v in properties.items(): + assert v == getattr(el, k), f"{k} should be {v} but is {getattr(el, k)}" + return el + + def test_a(self): + a = self._create_el_and_basic_asserts("a", "click me") + assert a.textContent == "click me" + + def test_abbr(self): + abbr = self._create_el_and_basic_asserts("abbr", "some text") + assert abbr.textContent == "some text" + + def test_address(self): + address = self._create_el_and_basic_asserts("address", "some text") + assert address.textContent == "some text" + + def test_area(self): + properties = { + "shape": "poly", + "coords": "129,0,260,95,129,138", + "href": "https://developer.mozilla.org/docs/Web/HTTP", + "target": "_blank", + "alt": "HTTP", + } + # TODO: Check why click times out + self._create_el_and_basic_asserts("area", properties=properties) + + def test_article(self): + self._create_el_and_basic_asserts("article", "some text") + + def test_aside(self): + self._create_el_and_basic_asserts("aside", "some text") + + def test_audio(self): + self._create_el_and_basic_asserts( + "audio", + properties={ + "src": "http://localhost:8080/somefile.ogg", + "controls": True, + }, + ) + + def test_b(self): + self._create_el_and_basic_asserts("b", "some text") + + def test_blockquote(self): + self._create_el_and_basic_asserts("blockquote", "some text") + + def test_br(self): + self._create_el_and_basic_asserts("br") + + def test_element_button(self): + button = self._create_el_and_basic_asserts("button", "click me") + assert button.innerHTML == "click me" + + def test_element_button_attributes(self): + button = self._create_el_and_basic_asserts("button", "click me", None) + assert button.innerHTML == "click me" + + def test_canvas(self): + properties = { + "height": 100, + "width": 120, + } + # TODO: Check why click times out + self._create_el_and_basic_asserts( + "canvas", "alt text for canvas", properties=properties + ) + + def test_caption(self): + self._create_el_and_basic_asserts("caption", "some text") + + def test_cite(self): + self._create_el_and_basic_asserts("cite", "some text") + + def test_code(self): + self._create_el_and_basic_asserts("code", "import pyweb") + + def test_data(self): + self._create_el_and_basic_asserts( + "data", "some text", properties={"value": "123"} + ) + + def test_datalist(self): + self._create_el_and_basic_asserts("datalist", "some items") + + def test_dd(self): + self._create_el_and_basic_asserts("dd", "some text") + + def test_del_(self): + self._create_el_and_basic_asserts( + "del_", "some text", properties={"cite": "http://example.com/"} + ) + + def test_details(self): + self._create_el_and_basic_asserts( + "details", "some text", properties={"open": True} + ) + + def test_dialog(self): + self._create_el_and_basic_asserts( + "dialog", "some text", properties={"open": True} + ) + + def test_div(self): + div = self._create_el_and_basic_asserts("div", "click me") + assert div.innerHTML == "click me" + + def test_dl(self): + self._create_el_and_basic_asserts("dl", "some text") + + def test_dt(self): + self._create_el_and_basic_asserts("dt", "some text") + + def test_em(self): + self._create_el_and_basic_asserts("em", "some text") + + def test_embed(self): + # NOTE: Types actually matter and embed expects a string for height and width + # while other elements expect an int + + # TODO: It's important that we add typing soon to help with the user experience + properties = { + "src": "http://localhost:8080/somefile.ogg", + "type": "video/ogg", + "width": "250", + "height": "200", + } + self._create_el_and_basic_asserts("embed", properties=properties) + + def test_fieldset(self): + self._create_el_and_basic_asserts( + "fieldset", "some text", properties={"name": "some name"} + ) + + def test_figcaption(self): + self._create_el_and_basic_asserts("figcaption", "some text") + + def test_figure(self): + self._create_el_and_basic_asserts("figure", "some text") + + def test_footer(self): + self._create_el_and_basic_asserts("footer", "some text") + + def test_form(self): + properties = { + "action": "https://example.com/submit", + "method": "post", + "name": "some name", + "autocomplete": "on", + "rel": "external", + } + self._create_el_and_basic_asserts("form", "some text", properties=properties) + + def test_h1(self): + self._create_el_and_basic_asserts("h1", "some text") + + def test_h2(self): + self._create_el_and_basic_asserts("h2", "some text") + + def test_h3(self): + self._create_el_and_basic_asserts("h3", "some text") + + def test_h4(self): + self._create_el_and_basic_asserts("h4", "some text") + + def test_h5(self): + self._create_el_and_basic_asserts("h5", "some text") + + def test_h6(self): + self._create_el_and_basic_asserts("h6", "some text") + + def test_header(self): + self._create_el_and_basic_asserts("header", "some text") + + def test_hgroup(self): + self._create_el_and_basic_asserts("hgroup", "some text") + + def test_hr(self): + self._create_el_and_basic_asserts("hr") + + def test_i(self): + self._create_el_and_basic_asserts("i", "some text") + + def test_iframe(self): + # TODO: same comment about defining the right types + properties = { + "src": "http://localhost:8080/somefile.html", + "width": "250", + "height": "200", + } + self._create_el_and_basic_asserts("iframe", properties=properties) + + @upytest.skip( + "Flakey in worker.", + skip_when=RUNNING_IN_WORKER, + ) + async def test_img(self): + """ + This test, thanks to downloading an image from the internet, is flakey + when run in a worker. It's skipped when running in a worker. + """ + properties = { + "src": "https://picsum.photos/600/400", + "alt": "some image", + "width": 250, + "height": 200, + } + self._create_el_and_basic_asserts("img", properties=properties) + + def test_input(self): + # TODO: we need multiple input tests + properties = { + "type": "text", + "value": "some value", + "name": "some name", + "autofocus": True, + "pattern": "[A-Za-z]{3}", + "placeholder": "some placeholder", + "required": True, + "size": 20, + } + self._create_el_and_basic_asserts("input_", properties=properties) + + def test_ins(self): + self._create_el_and_basic_asserts( + "ins", "some text", properties={"cite": "http://example.com/"} + ) + + def test_kbd(self): + self._create_el_and_basic_asserts("kbd", "some text") + + def test_label(self): + self._create_el_and_basic_asserts("label", "some text") + + def test_legend(self): + self._create_el_and_basic_asserts("legend", "some text") + + def test_li(self): + self._create_el_and_basic_asserts("li", "some text") + + def test_link(self): + properties = { + "href": "http://localhost:8080/somefile.css", + "rel": "stylesheet", + "type": "text/css", + } + self._create_el_and_basic_asserts( + "link", + properties=properties, + additional_selector_rules="[href='http://localhost:8080/somefile.css']", + ) + + def test_main(self): + self._create_el_and_basic_asserts("main", "some text") + + def test_map(self): + self._create_el_and_basic_asserts( + "map_", "some text", properties={"name": "somemap"} + ) + + def test_mark(self): + self._create_el_and_basic_asserts("mark", "some text") + + def test_menu(self): + self._create_el_and_basic_asserts("menu", "some text") + + def test_meter(self): + properties = { + "value": 50, + "min": 0, + "max": 100, + "low": 30, + "high": 80, + "optimum": 50, + } + self._create_el_and_basic_asserts("meter", "some text", properties=properties) + + def test_nav(self): + self._create_el_and_basic_asserts("nav", "some text") + + def test_object(self): + properties = { + "data": "http://localhost:8080/somefile.swf", + "type": "application/x-shockwave-flash", + "width": "250", + "height": "200", + } + self._create_el_and_basic_asserts( + "object_", + properties=properties, + ) + + def test_ol(self): + self._create_el_and_basic_asserts("ol", "some text") + + def test_optgroup(self): + self._create_el_and_basic_asserts( + "optgroup", "some text", properties={"label": "some label"} + ) + + def test_option(self): + self._create_el_and_basic_asserts( + "option", "some text", properties={"value": "some value"} + ) + + def test_output(self): + self._create_el_and_basic_asserts("output", "some text") + + def test_p(self): + self._create_el_and_basic_asserts("p", "some text") + + def test_picture(self): + self._create_el_and_basic_asserts("picture", "some text") + + def test_pre(self): + self._create_el_and_basic_asserts("pre", "some text") + + def test_progress(self): + properties = { + "value": 50.0, + "max": 100.0, + } + self._create_el_and_basic_asserts( + "progress", "some text", properties=properties + ) + + def test_q(self): + self._create_el_and_basic_asserts( + "q", "some text", properties={"cite": "http://example.com/"} + ) + + def test_s(self): + self._create_el_and_basic_asserts("s", "some text") + + # def test_script(self): + # self._create_el_and_basic_asserts("script", "some text") + + def test_section(self): + self._create_el_and_basic_asserts("section", "some text") + + def test_select(self): + self._create_el_and_basic_asserts("select", "some text") + + def test_small(self): + self._create_el_and_basic_asserts("small", "some text") + + def test_source(self): + properties = { + "src": "http://localhost:8080/somefile.ogg", + "type": "audio/ogg", + } + self._create_el_and_basic_asserts( + "source", + properties=properties, + ) + + def test_span(self): + self._create_el_and_basic_asserts("span", "some text") + + def test_strong(self): + self._create_el_and_basic_asserts("strong", "some text") + + def test_style(self): + self._create_el_and_basic_asserts( + "style", + "body {background-color: red;}", + ) + + def test_sub(self): + self._create_el_and_basic_asserts("sub", "some text") + + def test_summary(self): + self._create_el_and_basic_asserts("summary", "some text") + + def test_sup(self): + self._create_el_and_basic_asserts("sup", "some text") + + def test_table(self): + self._create_el_and_basic_asserts("table", "some text") + + def test_tbody(self): + self._create_el_and_basic_asserts("tbody", "some text") + + def test_td(self): + self._create_el_and_basic_asserts("td", "some text") + + def test_template(self): + # We are not checking the content of template since it's sort of + # special element + self._create_el_and_basic_asserts("template") + + def test_textarea(self): + self._create_el_and_basic_asserts("textarea", "some text") + + def test_tfoot(self): + self._create_el_and_basic_asserts("tfoot", "some text") + + def test_th(self): + self._create_el_and_basic_asserts("th", "some text") + + def test_thead(self): + self._create_el_and_basic_asserts("thead", "some text") + + def test_time(self): + self._create_el_and_basic_asserts("time", "some text") + + def test_title(self): + self._create_el_and_basic_asserts("title", "some text") + + def test_tr(self): + self._create_el_and_basic_asserts("tr", "some text") + + def test_track(self): + properties = { + "src": "http://localhost:8080/somefile.vtt", + "kind": "subtitles", + "srclang": "en", + "label": "English", + } + self._create_el_and_basic_asserts( + "track", + properties=properties, + ) + + def test_u(self): + self._create_el_and_basic_asserts("u", "some text") + + def test_ul(self): + self._create_el_and_basic_asserts("ul", "some text") + + def test_var(self): + self._create_el_and_basic_asserts("var", "some text") + + def test_video(self): + properties = { + "src": "http://localhost:8080/somefile.ogg", + "controls": True, + "width": 250, + "height": 200, + } + self._create_el_and_basic_asserts("video", properties=properties) + + def test_append_py_element(self): + div_text_content = "Luke, I am your father" + p_text_content = "noooooooooo!" + # Let's create the element + el = web.div(div_text_content) + child = web.p(p_text_content) + el.append(child) + self.container.append(el) + # Check the expected content exists. + result = self.container.find("div") + assert len(result) == 1 + el = result[0] + tag = el.tagName + assert tag == "DIV", tag + assert el.textContent == f"{div_text_content}{p_text_content}" + assert len(el.children) == 1, "There should be only 1 child" + assert el.children[0].tagName == "P" + assert ( + el.children[0].parentNode.textContent + == f"{div_text_content}{p_text_content}" + ) + assert el.children[0].textContent == p_text_content + + def test_append_proxy_element(self): + div_text_content = "Luke, I am your father" + p_text_content = "noooooooooo!" + # Let's create the element + el = web.div(div_text_content) + child = document.createElement("P") + child.textContent = p_text_content + el.append(child) + self.container.append(el) + # Check the expected content exists. + result = self.container.find("div") + assert len(result) == 1 + el = result[0] + tag = el.tagName + assert tag == "DIV", tag + assert el.textContent == f"{div_text_content}{p_text_content}", el.textContent + assert len(el.children) == 1, "There should be only 1 child" + assert el.children[0].tagName == "P" + assert ( + el.children[0].parentNode.textContent + == f"{div_text_content}{p_text_content}" + ) + assert el.children[0].textContent == p_text_content + + def test_append_py_elementcollection(self): + div_text_content = "Luke, I am your father" + p_text_content = "noooooooooo!" + p2_text_content = "not me!" + # Let's create the elements + el = web.div(div_text_content) + child1 = web.p(p_text_content) + child2 = web.p(p2_text_content, id="child2") + collection = web.ElementCollection([child1, child2]) + el.append(collection) + self.container.append(el) + # Check the expected content exists. + result = self.container.find("div") + assert len(result) == 1 + el = result[0] + tag = el.tagName + assert tag == "DIV", tag + parent_full_content = f"{div_text_content}{p_text_content}{p2_text_content}" + assert el.textContent == parent_full_content + assert len(el.children) == 2, "There should be only 2 children" + assert el.children[0].tagName == "P" + assert el.children[0].parentNode.textContent == parent_full_content + assert el.children[0].textContent == p_text_content + assert el.children[1].tagName == "P" + assert el.children[1].id == "child2" + assert el.children[1].parentNode.textContent == parent_full_content + assert el.children[1].textContent == p2_text_content + + def test_append_js_element_nodelist(self): + div_text_content = "Luke, I am your father" + p_text_content = "noooooooooo!" + p2_text_content = "not me!" + # Let's create the elements + el = web.div(div_text_content) + child1 = web.p(p_text_content) + child2 = web.p(p2_text_content, id="child2") + self.container.append(child1) + self.container.append(child2) + nodes = self.container._dom_element.querySelectorAll("p") + el.append(nodes) + self.container.append(el) + # Check the expected content exists. + result = self.container.find("div") + assert len(result) == 1 + el = result[0] + tag = el.tagName + assert tag == "DIV", tag + parent_full_content = f"{div_text_content}{p_text_content}{p2_text_content}" + assert el.textContent == parent_full_content, el.innerHTML + assert len(el.children) == 2, "There should be only 2 children" + assert el.children[0].tagName == "P" + assert el.children[0].parentNode.textContent == parent_full_content + assert el.children[0].textContent == p_text_content + assert el.children[1].tagName == "P" + assert el.children[1].id == "child2" + assert el.children[1].parentNode.textContent == parent_full_content + assert el.children[1].textContent == p2_text_content diff --git a/core/tests/python/tests/test_websocket.py b/core/tests/python/tests/test_websocket.py new file mode 100644 index 00000000000..8561eab1b1a --- /dev/null +++ b/core/tests/python/tests/test_websocket.py @@ -0,0 +1,102 @@ +""" +Exercise the pyscript.Websocket class. +""" + +import asyncio +import upytest + +from pyscript import WebSocket + + +@upytest.skip("Websocket tests are disabled.") +async def test_websocket_with_attributes(): + """ + Event handlers assigned via object attributes. + + The Websocket class should be able to connect to a websocket server and + send and receive messages. + + Use of echo.websocket.org means: + + 1) When connecting it responds with a "Request served by" message. + 2) When sending a message it echos it back. + """ + connected_flag = False + closed_flag = False + messages = [] + ready_to_test = asyncio.Event() + + def on_open(event): + nonlocal connected_flag + connected_flag = True + ws.send("Hello, world!") # A message to echo. + + def on_message(event): + messages.append(event.data) + if len(messages) == 2: # We're done. + ws.close() + + def on_close(event): + nonlocal closed_flag + closed_flag = True + ready_to_test.set() # Finished! + + ws = WebSocket(url="wss://echo.websocket.org") + ws.onopen = on_open + ws.onmessage = on_message + ws.onclose = on_close + # Wait for everything to be finished. + await ready_to_test.wait() + assert connected_flag is True + assert len(messages) == 2 + assert "request served by" in messages[0].lower() + assert messages[1] == "Hello, world!" + assert closed_flag is True + + +@upytest.skip("Websocket tests are disabled.") +async def test_websocket_with_init(): + """ + Event handlers assigned via __init__ arguments. + + The Websocket class should be able to connect to a websocket server and + send and receive messages. + + Use of echo.websocket.org means: + + 1) When connecting it responds with a "Request served by" message. + 2) When sending a message it echos it back. + """ + connected_flag = False + closed_flag = False + messages = [] + ready_to_test = asyncio.Event() + + def on_open(event): + nonlocal connected_flag + connected_flag = True + ws.send("Hello, world!") # A message to echo. + + def on_message(event): + messages.append(event.data) + if len(messages) == 2: # We're done. + ws.close() + + def on_close(event): + nonlocal closed_flag + closed_flag = True + ready_to_test.set() # Finished! + + ws = WebSocket( + url="wss://echo.websocket.org", + onopen=on_open, + onmessage=on_message, + onclose=on_close, + ) + # Wait for everything to be finished. + await ready_to_test.wait() + assert connected_flag is True + assert len(messages) == 2 + assert "request served by" in messages[0].lower() + assert messages[1] == "Hello, world!" + assert closed_flag is True diff --git a/core/tests/python/tests/test_window.py b/core/tests/python/tests/test_window.py new file mode 100644 index 00000000000..6600c36fb31 --- /dev/null +++ b/core/tests/python/tests/test_window.py @@ -0,0 +1,25 @@ +""" +Ensure the pyscript.window object refers to the main thread's window object. +""" + +import upytest +from pyscript import RUNNING_IN_WORKER, window + + +@upytest.skip("Main thread only.", skip_when=RUNNING_IN_WORKER) +def test_window_in_main_thread(): + """ + The window object should refer to the main thread's window object. + """ + # The window will have a document. + assert window.document + + +@upytest.skip("Worker only.", skip_when=not RUNNING_IN_WORKER) +def test_window_in_worker(): + """ + The window object should refer to the worker's self object, even though + this code is running in a web worker. + """ + # The window will have a document. + assert window.document diff --git a/core/tsconfig.json b/core/tsconfig.json new file mode 100644 index 00000000000..f9fc9e68508 --- /dev/null +++ b/core/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "module": "NodeNext", + "target": "esnext", + "moduleResolution": "nodenext", + "allowJs": true, + "declaration": true, + "emitDeclarationOnly": true, + "declarationDir": "types" + }, + "include": ["src/core.js"] +} diff --git a/core/types/3rd-party/codemirror.d.ts b/core/types/3rd-party/codemirror.d.ts new file mode 100644 index 00000000000..2a1a953a9a0 --- /dev/null +++ b/core/types/3rd-party/codemirror.d.ts @@ -0,0 +1 @@ +export * from "codemirror"; diff --git a/core/types/3rd-party/codemirror_commands.d.ts b/core/types/3rd-party/codemirror_commands.d.ts new file mode 100644 index 00000000000..1862cebc7bb --- /dev/null +++ b/core/types/3rd-party/codemirror_commands.d.ts @@ -0,0 +1 @@ +export * from "@codemirror/commands"; diff --git a/core/types/3rd-party/codemirror_lang-python.d.ts b/core/types/3rd-party/codemirror_lang-python.d.ts new file mode 100644 index 00000000000..76b718d3b66 --- /dev/null +++ b/core/types/3rd-party/codemirror_lang-python.d.ts @@ -0,0 +1 @@ +export * from "@codemirror/lang-python"; diff --git a/core/types/3rd-party/codemirror_language.d.ts b/core/types/3rd-party/codemirror_language.d.ts new file mode 100644 index 00000000000..632a9f72919 --- /dev/null +++ b/core/types/3rd-party/codemirror_language.d.ts @@ -0,0 +1 @@ +export * from "@codemirror/language"; diff --git a/core/types/3rd-party/codemirror_state.d.ts b/core/types/3rd-party/codemirror_state.d.ts new file mode 100644 index 00000000000..9dd5c97d8a1 --- /dev/null +++ b/core/types/3rd-party/codemirror_state.d.ts @@ -0,0 +1 @@ +export * from "@codemirror/state"; diff --git a/core/types/3rd-party/codemirror_view.d.ts b/core/types/3rd-party/codemirror_view.d.ts new file mode 100644 index 00000000000..3669d051e72 --- /dev/null +++ b/core/types/3rd-party/codemirror_view.d.ts @@ -0,0 +1 @@ +export * from "@codemirror/view"; diff --git a/core/types/3rd-party/toml.d.ts b/core/types/3rd-party/toml.d.ts new file mode 100644 index 00000000000..14f8437c8b8 --- /dev/null +++ b/core/types/3rd-party/toml.d.ts @@ -0,0 +1,12 @@ +/*! (c) Jak Wings - MIT */ declare class e extends SyntaxError { + constructor(r: any, { offset: t, line: e, column: n }: { + offset: any; + line: any; + column: any; + }); + offset: any; + line: any; + column: any; +} +declare function n(n: any): any; +export { e as SyntaxError, n as parse }; diff --git a/core/types/3rd-party/xterm-readline.d.ts b/core/types/3rd-party/xterm-readline.d.ts new file mode 100644 index 00000000000..6bb8c3bfe4b --- /dev/null +++ b/core/types/3rd-party/xterm-readline.d.ts @@ -0,0 +1,138 @@ +declare var v: any; +declare var k: boolean; +declare namespace i { + export let __esModule: boolean; + export { Readline }; +} +declare class Readline { + highlighter: { + highlight(t: any, e: any): any; + highlightPrompt(t: any): any; + highlightChar(t: any, e: any): boolean; + }; + history: { + entries: any[]; + cursor: number; + maxEntries: any; + saveToLocalStorage(): void; + restoreFromLocalStorage(): void; + append(t: any): void; + resetCursor(): void; + next(): any; + prev(): any; + }; + disposables: any[]; + watermark: number; + highWatermark: number; + lowWatermark: number; + highWater: boolean; + state: { + line: { + buf: string; + pos: number; + buffer(): string; + pos_buffer(): string; + length(): number; + char_length(): number; + update(t: any, e: any): void; + insert(t: any): boolean; + moveBack(t: any): boolean; + moveForward(t: any): boolean; + moveHome(): boolean; + moveEnd(): boolean; + startOfLine(): number; + endOfLine(): number; + moveLineUp(t: any): boolean; + moveLineDown(t: any): boolean; + set_pos(t: any): void; + prevPos(t: any): number; + nextPos(t: any): number; + backspace(t: any): boolean; + delete(t: any): boolean; + deleteEndOfLine(): boolean; + }; + highlighting: boolean; + prompt: any; + tty: any; + highlighter: any; + history: any; + promptSize: any; + layout: c; + buffer(): string; + shouldHighlight(): boolean; + clearScreen(): void; + editInsert(t: any): void; + update(t: any): void; + editBackspace(t: any): void; + editDelete(t: any): void; + editDeleteEndOfLine(): void; + refresh(): void; + moveCursorBack(t: any): void; + moveCursorForward(t: any): void; + moveCursorUp(t: any): void; + moveCursorDown(t: any): void; + moveCursorHome(): void; + moveCursorEnd(): void; + moveCursorToEnd(): void; + previousHistory(): void; + nextHistory(): void; + moveCursor(): void; + }; + checkHandler: () => boolean; + ctrlCHandler: () => void; + pauseHandler: (t: any) => void; + activate(t: any): void; + term: any; + dispose(): void; + appendHistory(t: any): void; + setHighlighter(t: any): void; + setCheckHandler(t: any): void; + setCtrlCHandler(t: any): void; + setPauseHandler(t: any): void; + writeReady(): boolean; + write(t: any): void; + print(t: any): void; + println(t: any): void; + output(): this; + tty(): { + tabWidth: any; + col: any; + row: any; + out: any; + write(t: any): any; + print(t: any): any; + println(t: any): any; + clearScreen(): void; + calculatePosition(t: any, e: any): any; + computeLayout(t: any, e: any): { + promptSize: any; + cursor: any; + end: any; + }; + refreshLine(t: any, e: any, s: any, i: any, r: any): void; + clearOldRows(t: any): void; + moveCursor(t: any, e: any): void; + }; + read(t: any): Promise; + activeRead: { + prompt: any; + resolve: (value: any) => void; + reject: (reason?: any) => void; + }; + handleKeyEvent(t: any): boolean; + readData(t: any): void; + readPaste(t: any): void; + readKey(t: any): void; +} +declare class c { + constructor(t: any); + promptSize: any; + cursor: u; + end: u; +} +declare class u { + constructor(t: any, e: any); + row: any; + col: any; +} +export { v as Readline, k as __esModule, i as default }; diff --git a/core/types/3rd-party/xterm.d.ts b/core/types/3rd-party/xterm.d.ts new file mode 100644 index 00000000000..697d9adc5f5 --- /dev/null +++ b/core/types/3rd-party/xterm.d.ts @@ -0,0 +1,4 @@ +declare var D: any; +declare var R: any; +declare var L: {}; +export { D as Terminal, R as __esModule, L as default }; diff --git a/core/types/3rd-party/xterm_addon-fit.d.ts b/core/types/3rd-party/xterm_addon-fit.d.ts new file mode 100644 index 00000000000..6959e9739c0 --- /dev/null +++ b/core/types/3rd-party/xterm_addon-fit.d.ts @@ -0,0 +1,4 @@ +declare var i: any; +declare var o: any; +declare var s: {}; +export { i as FitAddon, o as __esModule, s as default }; diff --git a/core/types/3rd-party/xterm_addon-web-links.d.ts b/core/types/3rd-party/xterm_addon-web-links.d.ts new file mode 100644 index 00000000000..5d1e051502b --- /dev/null +++ b/core/types/3rd-party/xterm_addon-web-links.d.ts @@ -0,0 +1,4 @@ +declare var r: any; +declare var n: any; +declare var t: {}; +export { r as WebLinksAddon, n as __esModule, t as default }; diff --git a/core/types/all-done.d.ts b/core/types/all-done.d.ts new file mode 100644 index 00000000000..cb0ff5c3b54 --- /dev/null +++ b/core/types/all-done.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/core/types/config.d.ts b/core/types/config.d.ts new file mode 100644 index 00000000000..bb809895a68 --- /dev/null +++ b/core/types/config.d.ts @@ -0,0 +1,7 @@ +export function configDetails(config: string, type: string | null): { + json: boolean; + toml: boolean; + text: string; +}; +export const configs: Map; +export function relative_url(url: any, base?: string): string; diff --git a/core/types/core.d.ts b/core/types/core.d.ts new file mode 100644 index 00000000000..2f075d559fd --- /dev/null +++ b/core/types/core.d.ts @@ -0,0 +1,67 @@ +export function donkey(options: any): Promise<{ + process: (code: any) => Promise; + execute: (code: any) => Promise; + evaluate: (code: any) => Promise; + clear: () => Promise; + reset: () => Promise; + kill: () => void; +}>; +export function offline_interpreter(config: any): string; +import codemirror from "./plugins/codemirror.js"; +import { stdlib } from "./stdlib.js"; +import { optional } from "./stdlib.js"; +import { inputFailure } from "./hooks.js"; +import TYPES from "./types.js"; +import { relative_url } from "./config.js"; +/** + * A `Worker` facade able to bootstrap on the worker thread only a PyScript module. + * @param {string} file the python file to run ina worker. + * @param {{config?: string | object, async?: boolean}} [options] optional configuration for the worker. + * @returns {Promise} + */ +declare function exportedPyWorker(file: string, options?: { + config?: string | object; + async?: boolean; +}): Promise; +/** + * A `Worker` facade able to bootstrap on the worker thread only a PyScript module. + * @param {string} file the python file to run ina worker. + * @param {{config?: string | object, async?: boolean}} [options] optional configuration for the worker. + * @returns {Promise} + */ +declare function exportedMPWorker(file: string, options?: { + config?: string | object; + async?: boolean; +}): Promise; +declare const exportedHooks: { + main: { + onWorker: Set; + onReady: Set; + onBeforeRun: Set; + onBeforeRunAsync: Set; + onAfterRun: Set; + onAfterRunAsync: Set; + codeBeforeRun: Set; + codeBeforeRunAsync: Set; + codeAfterRun: Set; + codeAfterRunAsync: Set; + }; + worker: { + onReady: Set; + onBeforeRun: Set; + onBeforeRunAsync: Set; + onAfterRun: Set; + onAfterRunAsync: Set; + codeBeforeRun: Set; + codeBeforeRunAsync: Set; + codeAfterRun: Set; + codeAfterRunAsync: Set; + }; +}; +declare const exportedConfig: {}; +declare const exportedWhenDefined: any; +export { codemirror, stdlib, optional, inputFailure, TYPES, relative_url, exportedPyWorker as PyWorker, exportedMPWorker as MPWorker, exportedHooks as hooks, exportedConfig as config, exportedWhenDefined as whenDefined }; diff --git a/core/types/exceptions.d.ts b/core/types/exceptions.d.ts new file mode 100644 index 00000000000..fc2db6340b5 --- /dev/null +++ b/core/types/exceptions.d.ts @@ -0,0 +1,56 @@ +/** + * Internal function for creating alert banners on the page + * @param {string} message The message to be displayed to the user + * @param {string} level The alert level of the message. Can be any string; 'error' or 'warning' cause matching messages to be emitted to the console + * @param {string} [messageType="text"] If set to "html", the message content will be assigned to the banner's innerHTML directly, instead of its textContent + * @param {any} [logMessage=true] An additional flag for whether the message should be sent to the console log. + */ +export function _createAlertBanner(message: string, level: string, messageType?: string, logMessage?: any): void; +export namespace ErrorCode { + let GENERIC: string; + let CONFLICTING_CODE: string; + let BAD_CONFIG: string; + let MICROPIP_INSTALL_ERROR: string; + let BAD_PLUGIN_FILE_EXTENSION: string; + let NO_DEFAULT_EXPORT: string; + let TOP_LEVEL_AWAIT: string; + let FETCH_ERROR: string; + let FETCH_NAME_ERROR: string; + let FETCH_UNAUTHORIZED_ERROR: string; + let FETCH_FORBIDDEN_ERROR: string; + let FETCH_NOT_FOUND_ERROR: string; + let FETCH_SERVER_ERROR: string; + let FETCH_UNAVAILABLE_ERROR: string; +} +/** + * Keys of the ErrorCode object + * @typedef {keyof ErrorCode} ErrorCodes + * */ +export class UserError extends Error { + /** + * @param {ErrorCodes} errorCode + * @param {string} message + * @param {string} messageType + * */ + constructor(errorCode: ErrorCodes, message?: string, messageType?: string); + errorCode: "GENERIC" | "CONFLICTING_CODE" | "BAD_CONFIG" | "MICROPIP_INSTALL_ERROR" | "BAD_PLUGIN_FILE_EXTENSION" | "NO_DEFAULT_EXPORT" | "TOP_LEVEL_AWAIT" | "FETCH_ERROR" | "FETCH_NAME_ERROR" | "FETCH_UNAUTHORIZED_ERROR" | "FETCH_FORBIDDEN_ERROR" | "FETCH_NOT_FOUND_ERROR" | "FETCH_SERVER_ERROR" | "FETCH_UNAVAILABLE_ERROR"; + messageType: string; +} +export class FetchError extends UserError { + /** + * @param {ErrorCodes} errorCode + * @param {string} message + * */ + constructor(errorCode: ErrorCodes, message: string); +} +export class InstallError extends UserError { + /** + * @param {ErrorCodes} errorCode + * @param {string} message + * */ + constructor(errorCode: ErrorCodes, message: string); +} +/** + * Keys of the ErrorCode object + */ +export type ErrorCodes = "GENERIC" | "CONFLICTING_CODE" | "BAD_CONFIG" | "MICROPIP_INSTALL_ERROR" | "BAD_PLUGIN_FILE_EXTENSION" | "NO_DEFAULT_EXPORT" | "TOP_LEVEL_AWAIT" | "FETCH_ERROR" | "FETCH_NAME_ERROR" | "FETCH_UNAUTHORIZED_ERROR" | "FETCH_FORBIDDEN_ERROR" | "FETCH_NOT_FOUND_ERROR" | "FETCH_SERVER_ERROR" | "FETCH_UNAVAILABLE_ERROR"; diff --git a/core/types/fetch.d.ts b/core/types/fetch.d.ts new file mode 100644 index 00000000000..fc3849ddeee --- /dev/null +++ b/core/types/fetch.d.ts @@ -0,0 +1,11 @@ +/** + * This is a fetch wrapper that handles any non 200 responses and throws a + * FetchError with the right ErrorCode. This is useful because our FetchError + * will automatically create an alert banner. + * + * @param {string} url - URL to fetch + * @param {Request} [options] - options to pass to fetch + * @returns {Promise} + */ +export function robustFetch(url: string, options?: Request): Promise; +export function getText(response: Response): Promise; diff --git a/core/types/fs.d.ts b/core/types/fs.d.ts new file mode 100644 index 00000000000..3283c5d4009 --- /dev/null +++ b/core/types/fs.d.ts @@ -0,0 +1,8 @@ +export const NAMESPACE: "@pyscript.fs"; +export const ERROR: "storage permissions not granted"; +export const idb: any; +export function getFileSystemDirectoryHandle(options: { + id?: string; + mode?: "read" | "readwrite"; + hint?: "desktop" | "documents" | "downloads" | "music" | "pictures" | "videos"; +}): Promise; diff --git a/core/types/hooks.d.ts b/core/types/hooks.d.ts new file mode 100644 index 00000000000..cb52f57a64e --- /dev/null +++ b/core/types/hooks.d.ts @@ -0,0 +1,39 @@ +export function main(name: any): any; +export function worker(name: any): any; +export function codeFor(branch: any, type: any): {}; +export function createFunction(self: any, name: any): any; +export const inputFailure: "\n import builtins\n def input(prompt=\"\"):\n raise Exception(\"\\n \".join([\n \"input() doesn't work when PyScript runs in the main thread.\",\n \"Consider using the worker attribute: https://pyscript.github.io/docs/2023.11.2/user-guide/workers/\"\n ]))\n\n builtins.input = input\n del builtins\n del input\n"; +export namespace hooks { + namespace main { + let onWorker: Set; + let onReady: Set; + let onBeforeRun: Set; + let onBeforeRunAsync: Set; + let onAfterRun: Set; + let onAfterRunAsync: Set; + let codeBeforeRun: Set; + let codeBeforeRunAsync: Set; + let codeAfterRun: Set; + let codeAfterRunAsync: Set; + } + namespace worker { + let onReady_1: Set; + export { onReady_1 as onReady }; + let onBeforeRun_1: Set; + export { onBeforeRun_1 as onBeforeRun }; + let onBeforeRunAsync_1: Set; + export { onBeforeRunAsync_1 as onBeforeRunAsync }; + let onAfterRun_1: Set; + export { onAfterRun_1 as onAfterRun }; + let onAfterRunAsync_1: Set; + export { onAfterRunAsync_1 as onAfterRunAsync }; + let codeBeforeRun_1: Set; + export { codeBeforeRun_1 as codeBeforeRun }; + let codeBeforeRunAsync_1: Set; + export { codeBeforeRunAsync_1 as codeBeforeRunAsync }; + let codeAfterRun_1: Set; + export { codeAfterRun_1 as codeAfterRun }; + let codeAfterRunAsync_1: Set; + export { codeAfterRunAsync_1 as codeAfterRunAsync }; + } +} diff --git a/core/types/plugins-helper.d.ts b/core/types/plugins-helper.d.ts new file mode 100644 index 00000000000..7af7edde243 --- /dev/null +++ b/core/types/plugins-helper.d.ts @@ -0,0 +1,2 @@ +declare function _default(main: any, wrap: any, element: any, hook: any): Promise; +export default _default; diff --git a/core/types/plugins.d.ts b/core/types/plugins.d.ts new file mode 100644 index 00000000000..00dd48e665a --- /dev/null +++ b/core/types/plugins.d.ts @@ -0,0 +1,10 @@ +declare const _default: { + codemirror: () => Promise; + "deprecations-manager": () => Promise; + donkey: () => Promise; + error: () => Promise; + "py-editor": () => Promise; + "py-game": () => Promise; + "py-terminal": () => Promise; +}; +export default _default; diff --git a/core/types/plugins/codemirror.d.ts b/core/types/plugins/codemirror.d.ts new file mode 100644 index 00000000000..93424d77d2c --- /dev/null +++ b/core/types/plugins/codemirror.d.ts @@ -0,0 +1,9 @@ +declare namespace _default { + const core: Promise; + const state: Promise; + const python: Promise; + const language: Promise; + const view: Promise; + const commands: Promise; +} +export default _default; diff --git a/core/types/plugins/deprecations-manager.d.ts b/core/types/plugins/deprecations-manager.d.ts new file mode 100644 index 00000000000..cb0ff5c3b54 --- /dev/null +++ b/core/types/plugins/deprecations-manager.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/core/types/plugins/donkey.d.ts b/core/types/plugins/donkey.d.ts new file mode 100644 index 00000000000..f328f997dd4 --- /dev/null +++ b/core/types/plugins/donkey.d.ts @@ -0,0 +1,9 @@ +declare function _default(options?: {}): Promise<{ + process: (code: any) => Promise; + execute: (code: any) => Promise; + evaluate: (code: any) => Promise; + clear: () => Promise; + reset: () => Promise; + kill: () => void; +}>; +export default _default; diff --git a/core/types/plugins/error.d.ts b/core/types/plugins/error.d.ts new file mode 100644 index 00000000000..40bdfd0dc2d --- /dev/null +++ b/core/types/plugins/error.d.ts @@ -0,0 +1,6 @@ +export function notOnDOM(): void; +/** + * Add a banner to the top of the page, notifying the user of an error + * @param {string} message + */ +export function notify(message: string): void; diff --git a/core/types/plugins/py-editor.d.ts b/core/types/plugins/py-editor.d.ts new file mode 100644 index 00000000000..35a35db464a --- /dev/null +++ b/core/types/plugins/py-editor.d.ts @@ -0,0 +1,2 @@ +declare const _default: Promise; +export default _default; diff --git a/core/types/plugins/py-game.d.ts b/core/types/plugins/py-game.d.ts new file mode 100644 index 00000000000..cb0ff5c3b54 --- /dev/null +++ b/core/types/plugins/py-game.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/core/types/plugins/py-terminal.d.ts b/core/types/plugins/py-terminal.d.ts new file mode 100644 index 00000000000..cb0ff5c3b54 --- /dev/null +++ b/core/types/plugins/py-terminal.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/core/types/plugins/py-terminal/mpy.d.ts b/core/types/plugins/py-terminal/mpy.d.ts new file mode 100644 index 00000000000..a45471b4e48 --- /dev/null +++ b/core/types/plugins/py-terminal/mpy.d.ts @@ -0,0 +1,2 @@ +declare function _default(element: any): Promise; +export default _default; diff --git a/core/types/plugins/py-terminal/py.d.ts b/core/types/plugins/py-terminal/py.d.ts new file mode 100644 index 00000000000..a45471b4e48 --- /dev/null +++ b/core/types/plugins/py-terminal/py.d.ts @@ -0,0 +1,2 @@ +declare function _default(element: any): Promise; +export default _default; diff --git a/core/types/stdlib.d.ts b/core/types/stdlib.d.ts new file mode 100644 index 00000000000..c42c11acfd6 --- /dev/null +++ b/core/types/stdlib.d.ts @@ -0,0 +1,2 @@ +export const stdlib: string; +export const optional: string; diff --git a/core/types/stdlib/pyscript.d.ts b/core/types/stdlib/pyscript.d.ts new file mode 100644 index 00000000000..8c6c476d5a8 --- /dev/null +++ b/core/types/stdlib/pyscript.d.ts @@ -0,0 +1,19 @@ +declare namespace _default { + let pyscript: { + "__init__.py": string; + "display.py": string; + "events.py": string; + "fetch.py": string; + "ffi.py": string; + "flatted.py": string; + "fs.py": string; + "magic_js.py": string; + "media.py": string; + "storage.py": string; + "util.py": string; + "web.py": string; + "websocket.py": string; + "workers.py": string; + }; +} +export default _default; diff --git a/core/types/sync.d.ts b/core/types/sync.d.ts new file mode 100644 index 00000000000..484122d3782 --- /dev/null +++ b/core/types/sync.d.ts @@ -0,0 +1,20 @@ +declare namespace _default { + function is_pyterminal(): boolean; + /** + * 'Sleep' for the given number of seconds. Used to implement Python's time.sleep in Worker threads. + * @param {number} seconds The number of seconds to sleep. + */ + function sleep(seconds: number): Promise; + /** + * Ask a user action via dialog and returns the directory handler once granted. + * @param {string} uid + * @param {{id?:string, mode?:"read"|"readwrite", hint?:"desktop"|"documents"|"downloads"|"music"|"pictures"|"videos"}} options + * @returns {boolean} + */ + function storeFSHandler(uid: string, options?: { + id?: string; + mode?: "read" | "readwrite"; + hint?: "desktop" | "documents" | "downloads" | "music" | "pictures" | "videos"; + }): boolean; +} +export default _default; diff --git a/core/types/types.d.ts b/core/types/types.d.ts new file mode 100644 index 00000000000..1190776e65a --- /dev/null +++ b/core/types/types.d.ts @@ -0,0 +1,2 @@ +declare const _default: Map; +export default _default; diff --git a/core/types/zero-redirect.d.ts b/core/types/zero-redirect.d.ts new file mode 100644 index 00000000000..cb0ff5c3b54 --- /dev/null +++ b/core/types/zero-redirect.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index cc455c578ce..00000000000 --- a/docs/Makefile +++ /dev/null @@ -1,45 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= sphinx-build -SOURCEDIR = . -BUILDDIR = _build -CONDA_ENV ?= _env - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -env := $(CONDA_ENV) -conda_run := conda run -p $(env) - -setup: - @if [ -z "$${CONDA_SHLVL:+x}" ]; then echo "Conda is not installed." && exit 1; fi - $(CONDA_EXE) env $(shell [ -d $(env) ] && echo update || echo create) -p $(env) --file environment.yml - -clean: - rm -rf $(BUILDDIR) - -clean-all: clean - rm -rf $(env) *.egg-info - -shell: - @export CONDA_ENV_PROMPT='<{name}>' - @echo 'conda activate $(env)' - -htmlserve: - python -m http.server -d "$(BUILDDIR)/html/" - -livehtml: - sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - - -.PHONY: help Makefile setup clean clean-all shell - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 62c08416fe4..00000000000 --- a/docs/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# PyScript documentation - -Welcome to the PyScript documentation directory, where you can find -and contribute to discussions around PyScript and related topics. - -## Getting started - -Before you start contributing to the documentation, it's worthwhile to -take a look at the general contributing guidelines for the PyScript project. You can find these guidelines here -[Contributing Guidelines](https://github.com/pyscript/pyscript/blob/main/CONTRIBUTING.md) - -### Setup - -The `docs` directory in the pyscript repository contains a -[Sphinx](https://www.sphinx-doc.org/) documentation project. Sphinx is a system -that takes plaintext files containing documentation written in Markdown, along with -and static files like templates and themes, to build the static end result. diff --git a/docs/_static/examples/what-is-pyscript.html b/docs/_static/examples/what-is-pyscript.html deleted file mode 100644 index d8b96dfd951..00000000000 --- a/docs/_static/examples/what-is-pyscript.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - numpy - - matplotlib - - - - -

Let's plot random numbers

-
-
-

❰py❱

-
-
- -import matplotlib.pyplot as plt -import numpy as np - -x = np.random.randn(1000) -y = np.random.randn(1000) - -fig, ax = plt.subplots() -ax.scatter(x, y) -pyscript.write('plot', fig) - - - diff --git a/docs/_static/fonts/Hack-Bold.woff b/docs/_static/fonts/Hack-Bold.woff deleted file mode 100644 index 35feb8f859d..00000000000 Binary files a/docs/_static/fonts/Hack-Bold.woff and /dev/null differ diff --git a/docs/_static/fonts/Hack-BoldItalic.woff b/docs/_static/fonts/Hack-BoldItalic.woff deleted file mode 100644 index 30e7b66c3c1..00000000000 Binary files a/docs/_static/fonts/Hack-BoldItalic.woff and /dev/null differ diff --git a/docs/_static/fonts/Hack-Italic.woff b/docs/_static/fonts/Hack-Italic.woff deleted file mode 100644 index 037a0b3ef62..00000000000 Binary files a/docs/_static/fonts/Hack-Italic.woff and /dev/null differ diff --git a/docs/_static/fonts/Hack-Regular.woff b/docs/_static/fonts/Hack-Regular.woff deleted file mode 100644 index 05ea5cf97a7..00000000000 Binary files a/docs/_static/fonts/Hack-Regular.woff and /dev/null differ diff --git a/docs/_static/images/avatar.jpg b/docs/_static/images/avatar.jpg deleted file mode 100644 index 538af057f49..00000000000 Binary files a/docs/_static/images/avatar.jpg and /dev/null differ diff --git a/docs/_static/redirect.html b/docs/_static/redirect.html deleted file mode 100644 index 3c3a36bcaae..00000000000 --- a/docs/_static/redirect.html +++ /dev/null @@ -1 +0,0 @@ - diff --git a/docs/concepts/governance/maintainers.md b/docs/concepts/governance/maintainers.md deleted file mode 120000 index eebb18385a0..00000000000 --- a/docs/concepts/governance/maintainers.md +++ /dev/null @@ -1 +0,0 @@ -../../../MAINTAINERS.md \ No newline at end of file diff --git a/docs/concepts/governance/policy.md b/docs/concepts/governance/policy.md deleted file mode 120000 index 460729773a8..00000000000 --- a/docs/concepts/governance/policy.md +++ /dev/null @@ -1 +0,0 @@ -../../../GOVERNANCE.md \ No newline at end of file diff --git a/docs/concepts/index.md b/docs/concepts/index.md deleted file mode 100644 index 8bd09c78ea9..00000000000 --- a/docs/concepts/index.md +++ /dev/null @@ -1,12 +0,0 @@ -# Concepts - -This section contains various topics that are higher-level and useful to know. - -```{toctree} ---- -maxdepth: 2 -glob: ---- -what-is-pyscript -governance/* -``` diff --git a/docs/concepts/what-is-pyscript.md b/docs/concepts/what-is-pyscript.md deleted file mode 100644 index a0e0032cbba..00000000000 --- a/docs/concepts/what-is-pyscript.md +++ /dev/null @@ -1,34 +0,0 @@ -# What is PyScript? - -The PyScript library provides HTML tags for embedding and executing Python code in your browser. PyScript is built using [Pyodide](https://pyodide.org/en/stable/), the WebAssembly port of CPython, which is compiled using [Emscripten](https://emscripten.org/). - -PyScript turns the browser into a code deployment tool that anyone can learn to use. - -## Example - -In this example, we are using the `` HTML tag to generate a Matplotlib figure and display it as an image. -Click **Preview** to see the rendered HTML. - -To try it in your browser, copy the code below into an online HTML editor like W3School's [Tryit Editor](https://www.w3schools.com/html/tryit.asp?filename=tryhtml_default_default), which allows you to modify, run, and even save your code. Watch the video below to see it in action! - -```{youtube} ZtC7TCt_LhU -``` - -::::{tab-set} -:::{tab-item} HTML Source - -```{literalinclude} ../_static/examples/what-is-pyscript.html ---- -linenos: -``` - -::: - -:::{tab-item} Preview - -```{raw} html - -``` - -::: -:::: diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index e15b3ebf5a1..00000000000 --- a/docs/conf.py +++ /dev/null @@ -1,103 +0,0 @@ -# Configuration file for the Sphinx documentation builder. -# -# This file only contains a selection of the most common options. For a full -# list see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html - -# -- Path setup -------------------------------------------------------------- - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -import os - -# import sys -# sys.path.insert(0, os.path.abspath('.')) - - -# -- Project information ----------------------------------------------------- - -project = "PyScript" -copyright = "(c) 2022, Anaconda, Inc." -author = "Anaconda, Inc." -language = "en" - -# -- General configuration --------------------------------------------------- - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "myst_parser", - "sphinx_copybutton", - "sphinx_design", - "sphinx_togglebutton", - "sphinx_sitemap", - "sphinxemoji.sphinxemoji", - "sphinxcontrib.youtube", -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This pattern also affects html_static_path and html_extra_path. -exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "_env", "README.md"] - - -# -- Options for HTML output ------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = "pydata_sphinx_theme" - -html_logo = "_static/images/avatar.jpg" - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] -# html_css_files = ["styles/custom.css"] - -html_baseurl = os.environ.get("SPHINX_HTML_BASE_URL", "http://127.0.0.1:8000/") -sitemap_locales = [None] -sitemap_url_scheme = "{link}" - -html_extra_path = ["robots.txt"] - -html_theme_options = { - "github_url": "https://github.com/pyscript/pyscript", - "twitter_url": "https://twitter.com/pyscript_dev", - "icon_links_label": "Quick Links", - # "google_analytics_id": "G-XXXXXXXXXX", - "use_edit_page_button": True, - "show_nav_level": 2, - "external_links": [ - # {"name": "GitHub repo", "url": "https://github.com/pyscript/pyscript"}, - ], -} - -html_context = { - "default_mode": "dark", - "pygment_light_style": "tango", - "pygment_dark_style": "native", - "github_user": "pyscript", - "github_repo": "pyscript", - "github_version": "main", - "doc_path": "docs", -} - - -myst_enable_extensions = [ - "dollarmath", - "amsmath", - "deflist", - "html_admonition", - "html_image", - "colon_fence", - "smartquotes", - "replacements", -] diff --git a/docs/environment.yml b/docs/environment.yml deleted file mode 100644 index e60a1be2123..00000000000 --- a/docs/environment.yml +++ /dev/null @@ -1,18 +0,0 @@ -channels: -- conda-forge -- defaults -dependencies: -- python=3.9 -- pip=20.2.2 -- Sphinx=4.5.0 -- myst-parser=0.17.2 -- pydata-sphinx-theme -- sphinx-copybutton -- sphinx-design -- sphinx-togglebutton - -- pip: - - sphinxemoji - - sphinx-sitemap - - sphinx-autobuild - - sphinxcontrib-youtube diff --git a/docs/howtos/index.md b/docs/howtos/index.md deleted file mode 100644 index 5c4261fe83b..00000000000 --- a/docs/howtos/index.md +++ /dev/null @@ -1,18 +0,0 @@ -# How-to guides - -Welcome to the how-to documentation section for PyScript. If you've already -gained some experience with PyScript before and just need practical guides -to get your ideas realized, you can learn step by step how to use PyScript here. - -```{note} -Please head over to the [tutorials](../tutorials/index.md) section if you're only getting started. -``` - -```{toctree} ---- -maxdepth: 2 -glob: -caption: 'Contents:' ---- -* -``` diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index 4d2a62fc518..00000000000 --- a/docs/index.md +++ /dev/null @@ -1,54 +0,0 @@ -# PyScript - -```{warning} -Please note, this documentation is just a placeholder and **should not be used -in reference material**. Thank you! -``` - -Welcome to the PyScript documentation! - -PyScript provides a way for you to run Python code directly in your browser, giving -anyone the ability to program without infrastructure barriers. Add an interactive -Python REPL directly to your website, share an interactive dashboard with a colleague -as an HTML file, or create a client-side Python-powered web application. This documentation -will show you how. - -::::{grid} 2 -:gutter: 3 - -:::{grid-item-card} [Tutorials](tutorials/index.md) - -Just getting started with PyScript? - -Check out our [getting started guide](tutorials/getting-started.md)! -::: -:::{grid-item-card} [How-to guides](howtos/index.md) - -**Coming soon!** - -::: -:::{grid-item-card} [Concepts](concepts/index.md) - -[What is PyScript?](concepts/what-is-pyscript.md) - -::: -:::{grid-item-card} [Reference](reference/index.md) - -**Coming soon!** - -:::{toctree} -:maxdepth: 1 - -::: -:::: - -```{toctree} ---- -maxdepth: 1 -hidden: ---- -tutorials/index -howtos/index -concepts/index -reference/index -``` diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 32bb24529f9..00000000000 --- a/docs/make.bat +++ /dev/null @@ -1,35 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=. -set BUILDDIR=_build - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.https://www.sphinx-doc.org/ - exit /b 1 -) - -if "%1" == "" goto help - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% - -:end -popd diff --git a/docs/reference/index.md b/docs/reference/index.md deleted file mode 100644 index f798f587bb3..00000000000 --- a/docs/reference/index.md +++ /dev/null @@ -1,4 +0,0 @@ -# Reference - -This reference section will have manually documented or fully -automated code documentation. **Coming soon!** diff --git a/docs/robots.txt b/docs/robots.txt deleted file mode 100644 index 4fccf0cccd8..00000000000 --- a/docs/robots.txt +++ /dev/null @@ -1,5 +0,0 @@ -User-agent: * -Disallow: /review/ - -Sitemap: https://docs.pyscript.net/sitemap.xml -Host: docs.pyscript.net diff --git a/docs/tutorials/deployment.md b/docs/tutorials/deployment.md deleted file mode 100644 index 5ed82887d31..00000000000 --- a/docs/tutorials/deployment.md +++ /dev/null @@ -1,3 +0,0 @@ -# Deployment - -**Coming soon!** diff --git a/docs/tutorials/getting-started.md b/docs/tutorials/getting-started.md deleted file mode 100644 index 82644052c81..00000000000 --- a/docs/tutorials/getting-started.md +++ /dev/null @@ -1,254 +0,0 @@ -# Getting started with PyScript - -This page will guide you through getting started with PyScript. - -## Development setup - -PyScript does not require any development environment other -than a web browser. We recommend using [Chrome](https://www.google.com/chrome/). - -If you're using [VSCode](https://code.visualstudio.com/), the -[Live Server extension](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) -can be used to reload the page as you edit the HTML file. - -## Installation - -There is no installation required. In this document, we'll use -the PyScript assets served on https://pyscript.net. - -If you want to download the source and build it yourself, follow -the instructions in the README.md file. - -## Your first PyScript HTML file - -Here's a "Hello, world!" example using PyScript. - -Using your favorite editor, create a new file called `hello.html` in -the same directory as your PyScript, JavaScript, and CSS files with the -following content, and open the file in your web browser. You can typically -open an HTML by double-clicking it in your file explorer. - -```html - - - - - - print('Hello, World!') - -``` - -Notice the use of the `` tag in the HTML body. This -is where you'll write your Python code. In the following sections, we'll -introduce the eight tags provided by PyScript. - -## The py-script tag - -The `` tag lets you execute multi-line Python scripts and -print back onto the page. For example, we can compute π. - -```html - - - - - - - - print("Let's compute π:") - def compute_pi(n): - pi = 2 - for i in range(1,n): - pi *= 4 * i ** 2 / (4 * i ** 2 - 1) - return pi - - pi = compute_pi(100000) - s = f"π is approximately {pi:.3f}" - print(s) - - - -``` - -### Writing into labeled elements - -In the example above, we had a single `` tag printing -one or more lines onto the page in order. Within the ``, you -have access to the `pyscript` module, which provides a `.write()` method -to send strings into labeled elements on the page. - -For example, we'll add some style elements and provide placeholders for -the `` tag to write to. - -```html - - - - - - - - -

Today is

-
-
- - import datetime as dt - pyscript.write('today', dt.date.today().strftime('%A %B %d, %Y')) - - def compute_pi(n): - pi = 2 - for i in range(1,n): - pi *= 4 * i ** 2 / (4 * i ** 2 - 1) - return pi - - pi = compute_pi(100000) - pyscript.write('pi', f'π is approximately {pi:.3f}') - - - -``` - -## The py-env tag - -In addition to the [Python Standard Library](https://docs.python.org/3/library/) and -the `pyscript` module, many 3rd-party OSS packages will work out-of-the-box with PyScript. - -In order to use them, you will need to declare the dependencies using the `` tag in the -HTML head. You can also link to `.whl` files directly on disk like in our [toga example](https://github.com/pyscript/pyscript/blob/main/examples/toga/freedom.html). - -``` - -- './static/wheels/travertino-0.1.3-py3-none-any.whl' - -``` - -If your `.whl` is not a pure Python wheel, then open a PR or issue with [pyodide](https://github.com/pyodide/pyodide) to get it added [here](https://github.com/pyodide/pyodide/tree/main/packages). -If there's enough popular demand, the pyodide team will likely work on supporting your package. Regardless, things will likely move faster if you make the PR and consult with the team to get unblocked. - -For example, NumPy and Matplotlib are available. Notice here we're using `` -as a shortcut, which takes the expression on the last line of the script and runs `pyscript.write('plot', fig)`. - -```html - - - - - - - numpy - - matplotlib - - - - -

Let's plot random numbers

-
- - import matplotlib.pyplot as plt - import numpy as np - - x = np.random.randn(1000) - y = np.random.randn(1000) - - fig, ax = plt.subplots() - ax.scatter(x, y) - fig - - - -``` - -### Local modules - -In addition to packages, you can declare local Python modules that will -be imported in the `` tag. For example, we can place the random -number generation steps in a function in the file `data.py`. - -```python -# data.py -import numpy as np - - -def make_x_and_y(n): - x = np.random.randn(n) - y = np.random.randn(n) - return x, y -``` - -In the HTML tag ``, paths to local modules are provided in the -`paths:` key. - -```html - - - - - - - numpy - - matplotlib - - paths: - - ./data.py - - - - -

Let's plot random numbers

-
- - import matplotlib.pyplot as plt - from data import make_x_and_y - - x, y = make_x_and_y(n=1000) - - fig, ax = plt.subplots() - ax.scatter(x, y) - fig - - - -``` -## The py-repl tag - -The `` tag creates a REPL component that is rendered to the page as a code editor, allowing you to write executable code inline. - -## The py-config tag - -Use the `` tag to set and configure general metadata about your PyScript application in YAML format. If you are unfamiliar with YAML, consider reading [Red Hat's YAML for beginners](https://www.redhat.com/sysadmin/yaml-beginners) guide for more information. - -The `` tag can be used as follows: - -``` - - - autoclose_loader: false - - runtimes: - - - src: "https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js" - name: pyodide-0.20 - lang: python - -``` - -The following optional values are supported by ``: - - * autoclose_loader (boolean): If false, PyScript will not close the loading splash screen when the startup operations finish. - * name (string): Name of the user application. This field can be any string and is to be used by the application author for their own customization purposes. - * version (string): Version of the user application. This field can be any string and is to be used by the application author for their own customization purposes. It is not related to the PyScript version. - * runtimes (List of Runtimes): List of runtime configurations. Each Runtime expects the following fields: - * src (string, Required): URL to the runtime source. - * name (string): Name of the runtime. This field can be any string and is to be used by the application author for their own customization purposes. - * lang (string): Programming language supported by the runtime. This field can be used by the application author to provide clarification. It currently has no implications on how PyScript behaves. - -## Visual component tags - -The following tags can be used to add visual attributes to your HTML page. - -| Tag | Description | -| --- | ----------- | -| `` | Adds an input box that can be used to prompt users to enter input values. | -| `` | Creates a container object that can be used to host one or more visual components that define how elements of `` should align and show on the page. | -| `` | Adds a button to which authors can add labels and event handlers for actions on the button, such as `on_focus` or `on_click`. | -| `` | Adds a static text title component that styles the text inside the tag as a page title. | - -```{note} -All the elements above are experimental and not implemented at their full functionality. Use them with the understanding that the APIs or full support might change or be removed until the visual components are more mature. -``` diff --git a/docs/tutorials/index.md b/docs/tutorials/index.md deleted file mode 100644 index d19d033c751..00000000000 --- a/docs/tutorials/index.md +++ /dev/null @@ -1,12 +0,0 @@ -# Tutorials - -This is the tutorials section for beginners. - -```{toctree} ---- -maxdepth: 2 ---- -getting-started -deployment -setup -``` diff --git a/docs/tutorials/setup.md b/docs/tutorials/setup.md deleted file mode 100644 index dab30d7f638..00000000000 --- a/docs/tutorials/setup.md +++ /dev/null @@ -1,3 +0,0 @@ -# Setup - -**Coming soon!** diff --git a/examples/altair.html b/examples/altair.html deleted file mode 100644 index 753a88b993a..00000000000 --- a/examples/altair.html +++ /dev/null @@ -1,60 +0,0 @@ - - - Altair - - - - - - - altair - - pandas - - vega_datasets - - - -
- -import altair as alt -from vega_datasets import data - -source = data.movies.url - -pts = alt.selection(type="single", encodings=['x']) - -rect = alt.Chart(data.movies.url).mark_rect().encode( - alt.X('IMDB_Rating:Q', bin=True), - alt.Y('Rotten_Tomatoes_Rating:Q', bin=True), - alt.Color('count()', - scale=alt.Scale(scheme='greenblue'), - legend=alt.Legend(title='Total Records') - ) -) - -circ = rect.mark_point().encode( - alt.ColorValue('grey'), - alt.Size('count()', - legend=alt.Legend(title='Records in Selection') - ) -).transform_filter( - pts -) - -bar = alt.Chart(source).mark_bar().encode( - x='Major_Genre:N', - y='count()', - color=alt.condition(pts, alt.ColorValue("steelblue"), alt.ColorValue("grey")) -).properties( - width=550, - height=200 -).add_selection(pts) - -alt.vconcat( - rect + circ, - bar -).resolve_legend( - color="independent", - size="independent" -) - - - diff --git a/examples/antigravity.html b/examples/antigravity.html deleted file mode 100644 index f3292570ecf..00000000000 --- a/examples/antigravity.html +++ /dev/null @@ -1,20 +0,0 @@ - - - Antigravity - - - - - - -- paths: - - ./antigravity.py - - - Based on xkcd: antigravity https://xkcd.com/353/. - -import antigravity -antigravity.fly() - - - diff --git a/examples/antigravity.py b/examples/antigravity.py deleted file mode 100644 index 67fd5b453c5..00000000000 --- a/examples/antigravity.py +++ /dev/null @@ -1,45 +0,0 @@ -import random -import sys - -from js import DOMParser, document, setInterval -from pyodide import create_proxy -from pyodide.http import open_url - - -class Antigravity: - - url = "./antigravity.svg" - - def __init__(self, target=None, interval=10, append=True, fly=False): - target = target or sys.stdout._out - self.target = ( - document.getElementById(target) if isinstance(target, str) else target - ) - doc = DOMParser.new().parseFromString( - open_url(self.url).read(), "image/svg+xml" - ) - self.node = doc.documentElement - if append: - self.target.append(self.node) - else: - self.target.replaceChildren(self.node) - self.xoffset, self.yoffset = 0, 0 - self.interval = interval - if fly: - self.fly() - - def fly(self): - setInterval(create_proxy(self.move), self.interval) - - def move(self): - char = self.node.getElementsByTagName("g")[1] - char.setAttribute("transform", f"translate({self.xoffset}, {-self.yoffset})") - self.xoffset += random.normalvariate(0, 1) / 20 - if self.yoffset < 50: - self.yoffset += 0.1 - else: - self.yoffset += random.normalvariate(0, 1) / 20 - - -_auto = Antigravity(append=True) -fly = _auto.fly diff --git a/examples/antigravity.svg b/examples/antigravity.svg deleted file mode 100644 index 092a9e7af79..00000000000 --- a/examples/antigravity.svg +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/examples/bokeh.html b/examples/bokeh.html deleted file mode 100644 index 226ef8bdd26..00000000000 --- a/examples/bokeh.html +++ /dev/null @@ -1,48 +0,0 @@ - - Bokeh Example - - - - - - - - - - - - - - - - -- bokeh -- numpy - -

Bokeh Example

-
- - -import json -import pyodide - -from js import Bokeh, console, JSON - -from bokeh.embed import json_item -from bokeh.plotting import figure -from bokeh.resources import CDN - -# create a new plot with default tools, using figure -p = figure(plot_width=400, plot_height=400) - -# add a circle renderer with x and y coordinates, size, color, and alpha -p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=15, line_color="navy", fill_color="orange", fill_alpha=0.5) -p_json = json.dumps(json_item(p, "myplot")) - -Bokeh.embed.embed_item(JSON.parse(p_json)) - - - - diff --git a/examples/bokeh_interactive.html b/examples/bokeh_interactive.html deleted file mode 100644 index 61fbc9df611..00000000000 --- a/examples/bokeh_interactive.html +++ /dev/null @@ -1,98 +0,0 @@ - - Bokeh Example - - - - - - - - - - - - - - - - -- bokeh -- numpy - -

Bokeh Example

-
- - -import asyncio -import json -import pyodide - -from js import Bokeh, console, JSON - -from bokeh import __version__ -from bokeh.document import Document -from bokeh.embed.util import OutputDocumentFor, standalone_docs_json_and_render_items -from bokeh.models import Slider, Div -from bokeh.layouts import Row -from bokeh.protocol.messages.patch_doc import process_document_events - -# create a new plot with default tools, using figure -p = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude") -div = Div(text=f'Amplitude is: {p.value}') - -def callback(attr, old, new): - div.text = f'Amplitude is: {new}' - -p.on_change('value', callback) - -row = Row(children=[p, div]) - -def doc_json(model, target): - with OutputDocumentFor([model]) as doc: - doc.title = "" - docs_json, _ = standalone_docs_json_and_render_items( - [model], suppress_callback_warning=True - ) - - doc_json = list(docs_json.values())[0] - root_id = doc_json['roots']['root_ids'][0] - - return doc, json.dumps(dict( - target_id = target, - root_id = root_id, - doc = doc_json, - version = __version__, - )) - -def _link_docs(pydoc, jsdoc): - def jssync(event): - if getattr(event, 'setter_id', None) is not None: - return - events = [event] - json_patch = jsdoc.create_json_patch_string(pyodide.to_js(events)) - pydoc.apply_json_patch(json.loads(json_patch)) - - jsdoc.on_change(pyodide.create_proxy(jssync), pyodide.to_js(False)) - - def pysync(event): - json_patch, buffers = process_document_events([event], use_buffers=True) - buffer_map = {} - for (ref, buffer) in buffers: - buffer_map[ref['id']] = buffer - jsdoc.apply_json_patch(JSON.parse(json_patch), pyodide.to_js(buffer_map), setter_id='js') - - pydoc.on_change(pysync) - -async def show(plot, target): - pydoc, model_json = doc_json(plot, target) - views = await Bokeh.embed.embed_item(JSON.parse(model_json)) - jsdoc = views[0].model.document - _link_docs(pydoc, jsdoc) - -await show(row, 'myplot') - - - - diff --git a/examples/d3.html b/examples/d3.html deleted file mode 100644 index b429c3d55f9..00000000000 --- a/examples/d3.html +++ /dev/null @@ -1,169 +0,0 @@ - - - d3: JavaScript & PyScript visualizations side-by-side - - - - - - - - - - - Based on Learn D3: Shapes tutorial. - -
-
-
JavaScript version
-
-
-
-
-
-
PyScript version
-
-
-
-
-
- - - - - - -from pyodide import create_proxy, to_js -import d3 - -fruits = [ - dict(name="🍊", count=21), - dict(name="🍇", count=13), - dict(name="🍏", count=8), - dict(name="🍌", count=5), - dict(name="🍐", count=3), - dict(name="🍋", count=2), - dict(name="🍎", count=1), - dict(name="🍉", count=1), -] - -fn = create_proxy(lambda d, *_: d["count"]) -data = d3.pie().value(fn)(to_js(fruits)) - -arc = (d3.arc() - .innerRadius(210) - .outerRadius(310) - .padRadius(300) - .padAngle(2 / 300) - .cornerRadius(8)) - -py = d3.select("#py") -py.select(".loading").remove() - -svg = (py - .append("svg") - .attr("viewBox", "-320 -320 640 640") - .attr("width", "400") - .attr("height", "400")) - -for d in data: - d_py = d.to_py() - - (svg.append("path") - .style("fill", "steelblue") - .attr("d", arc(d))) - - text = (svg.append("text") - .style("fill", "white") - .attr("transform", f"translate({arc.centroid(d).join(',')})") - .attr("text-anchor", "middle")) - - (text.append("tspan") - .style("font-size", "24") - .attr("x", "0") - .text(d_py["data"]["name"])) - - (text.append("tspan") - .style("font-size", "18") - .attr("x", "0") - .attr("dy", "1.3em") - .text(d_py["value"])) - - - - diff --git a/examples/favicon.png b/examples/favicon.png deleted file mode 100644 index 0e2c5cc2f6e..00000000000 Binary files a/examples/favicon.png and /dev/null differ diff --git a/examples/folium.html b/examples/folium.html deleted file mode 100644 index 84772785018..00000000000 --- a/examples/folium.html +++ /dev/null @@ -1,49 +0,0 @@ - - - Folium - - - - - - - folium - - pandas - - - -
- -import folium -import json -import pandas as pd - -from pyodide.http import open_url - -url = ( - "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data" -) -state_geo = f"{url}/us-states.json" -state_unemployment = f"{url}/US_Unemployment_Oct2012.csv" -state_data = pd.read_csv(open_url(state_unemployment)) -geo_json = json.loads(open_url(state_geo).read()) - -m = folium.Map(location=[48, -102], zoom_start=3) - -folium.Choropleth( - geo_data=geo_json, - name="choropleth", - data=state_data, - columns=["State", "Unemployment"], - key_on="feature.id", - fill_color="YlGn", - fill_opacity=0.7, - line_opacity=0.2, - legend_name="Unemployment Rate (%)", -).add_to(m) - -folium.LayerControl().add_to(m) - -m - - - diff --git a/examples/fractals.py b/examples/fractals.py deleted file mode 100644 index 61965e1d6db..00000000000 --- a/examples/fractals.py +++ /dev/null @@ -1,139 +0,0 @@ -import numpy as np -from numpy.polynomial import Polynomial - - -def mandelbrot( - width: int, - height: int, - *, - x: float = -0.5, - y: float = 0, - zoom: int = 1, - max_iterations: int = 100 -) -> np.array: - """ - https://www.learnpythonwithrune.org/numpy-compute-mandelbrot-set-by-vectorization - """ - # To make navigation easier we calculate these values - x_width, y_height = 1.5, 1.5 * height / width - x_from, x_to = x - x_width / zoom, x + x_width / zoom - y_from, y_to = y - y_height / zoom, y + y_height / zoom - - # Here the actual algorithm starts - x = np.linspace(x_from, x_to, width).reshape((1, width)) - y = np.linspace(y_from, y_to, height).reshape((height, 1)) - c = x + 1j * y - - # Initialize z to all zero - z = np.zeros(c.shape, dtype=np.complex128) - - # To keep track in which iteration the point diverged - div_time = np.zeros(z.shape, dtype=int) - - # To keep track on which points did not converge so far - m = np.full(c.shape, True, dtype=bool) - for i in range(max_iterations): - z[m] = z[m] ** 2 + c[m] - diverged = np.greater( - np.abs(z), 2, out=np.full(c.shape, False), where=m - ) # Find diverging - div_time[diverged] = i # set the value of the diverged iteration number - m[np.abs(z) > 2] = False # to remember which have diverged - - return div_time - - -def julia( - width: int, - height: int, - *, - c: complex = -0.4 + 0.6j, - x: float = 0, - y: float = 0, - zoom: int = 1, - max_iterations: int = 100 -) -> np.array: - """ - https://www.learnpythonwithrune.org/numpy-calculate-the-julia-set-with-vectorization - """ - # To make navigation easier we calculate these values - x_width, y_height = 1.5, 1.5 * height / width - x_from, x_to = x - x_width / zoom, x + x_width / zoom - y_from, y_to = y - y_height / zoom, y + y_height / zoom - - # Here the actual algorithm starts - x = np.linspace(x_from, x_to, width).reshape((1, width)) - y = np.linspace(y_from, y_to, height).reshape((height, 1)) - z = x + 1j * y - - # Initialize z to all zero - c = np.full(z.shape, c) - - # To keep track in which iteration the point diverged - div_time = np.zeros(z.shape, dtype=int) - - # To keep track on which points did not converge so far - m = np.full(c.shape, True, dtype=bool) - for i in range(max_iterations): - z[m] = z[m] ** 2 + c[m] - m[np.abs(z) > 2] = False - div_time[m] = i - - return div_time - - -Range = tuple[float, float] - - -def newton( - width: int, - height: int, - *, - p: Polynomial, - a: complex, - xr: Range = (-2.5, 1), - yr: Range = (-1, 1), - max_iterations: int = 100 -) -> tuple[np.array, np.array]: - """ """ - # To make navigation easier we calculate these values - x_from, x_to = xr - y_from, y_to = yr - - # Here the actual algorithm starts - x = np.linspace(x_from, x_to, width).reshape((1, width)) - y = np.linspace(y_from, y_to, height).reshape((height, 1)) - z = x + 1j * y - - # Compute the derivative - dp = p.deriv() - - # Compute roots - roots = p.roots() - epsilon = 1e-5 - - # Set the initial conditions - a = np.full(z.shape, a) - - # To keep track in which iteration the point diverged - div_time = np.zeros(z.shape, dtype=int) - - # To keep track on which points did not converge so far - m = np.full(a.shape, True, dtype=bool) - - # To keep track which root each point converged to - r = np.full(a.shape, 0, dtype=int) - - for i in range(max_iterations): - z[m] = z[m] - a[m] * p(z[m]) / dp(z[m]) - - for j, root in enumerate(roots): - converged = (np.abs(z.real - root.real) < epsilon) & ( - np.abs(z.imag - root.imag) < epsilon - ) - m[converged] = False - r[converged] = j + 1 - - div_time[m] = i - - return div_time, r diff --git a/examples/handtrack/lib/handtrack.min.js b/examples/handtrack/lib/handtrack.min.js deleted file mode 100644 index 4130ea6ddaf..00000000000 --- a/examples/handtrack/lib/handtrack.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! For license information please see handtrack.min.js.LICENSE.txt */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.handTrack=t():e.handTrack=t()}(self,(function(){return(()=>{var e={377:(e,t,n)=>{var s=n(832),a=n(652),r=n(801),i=n(30),o=n(618),l=n(49),u=n(971);u.alea=s,u.xor128=a,u.xorwow=r,u.xorshift7=i,u.xor4096=o,u.tychei=l,e.exports=u},832:function(e,t,n){var s;!function(e,a,r){function i(e){var t,n=this,s=(t=4022871197,function(e){e=e.toString();for(var n=0;n>>0,t=(s*=t)>>>0,t+=4294967296*(s-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=s(" "),n.s1=s(" "),n.s2=s(" "),n.s0-=s(e),n.s0<0&&(n.s0+=1),n.s1-=s(e),n.s1<0&&(n.s1+=1),n.s2-=s(e),n.s2<0&&(n.s2+=1),s=null}function o(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function l(e,t){var n=new i(e),s=t&&t.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+11102230246251565e-32*(2097152*a()|0)},a.quick=a,s&&("object"==typeof s&&o(s,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,a))||(a.exports=s):this.alea=l}(0,e=n.nmd(e),n.amdD)},49:function(e,t,n){var s;!function(e,a,r){function i(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,s=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-s|0,s=s<<24^s>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-s|0,t.d=s<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var s=0;s>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,s&&("object"==typeof s&&o(s,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,a))||(a.exports=s):this.tychei=l}(0,e=n.nmd(e),n.amdD)},652:function(e,t,n){var s;!function(e,a,r){function i(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var s=0;s>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,s&&("object"==typeof s&&o(s,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,a))||(a.exports=s):this.xor128=l}(0,e=n.nmd(e),n.amdD)},618:function(e,t,n){var s;!function(e,a,r){function i(e){var t=this;t.next=function(){var e,n,s=t.w,a=t.X,r=t.i;return t.w=s=s+1640531527|0,n=a[r+34&127],e=a[r=r+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[r]=n^e,t.i=r,n+(s^s>>>16)|0},function(e,t){var n,s,a,r,i,o=[],l=128;for(t===(0|t)?(s=t,t=null):(t+="\0",s=0,l=Math.max(l,t.length)),a=0,r=-32;r>>15,s^=s<<4,s^=s>>>13,r>=0&&(i=i+1640531527|0,a=0==(n=o[127&r]^=s+i)?a+1:0);for(a>=128&&(o[127&(t&&t.length||0)]=-1),a=127,r=512;r>0;--r)s=o[a+34&127],n=o[a=a+1&127],s^=s<<13,n^=n<<17,s^=s>>>15,n^=n>>>12,o[a]=s^n;e.w=i,e.X=o,e.i=a}(t,e)}function o(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function l(e,t){null==e&&(e=+new Date);var n=new i(e),s=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,s&&(s.X&&o(s,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,a))||(a.exports=s):this.xor4096=l}(0,e=n.nmd(e),n.amdD)},30:function(e,t,n){var s;!function(e,a,r){function i(e){var t=this;t.next=function(){var e,n,s=t.x,a=t.i;return e=s[a],n=(e^=e>>>7)^e<<24,n^=(e=s[a+1&7])^e>>>10,n^=(e=s[a+3&7])^e>>>3,n^=(e=s[a+4&7])^e<<7,e=s[a+7&7],n^=(e^=e<<13)^e<<9,s[a]=n,t.i=a+1&7,n},function(e,t){var n,s=[];if(t===(0|t))s[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function o(e,t){return t.x=e.x.slice(),t.i=e.i,t}function l(e,t){null==e&&(e=+new Date);var n=new i(e),s=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,s&&(s.x&&o(s,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,a))||(a.exports=s):this.xorshift7=l}(0,e=n.nmd(e),n.amdD)},801:function(e,t,n){var s;!function(e,a,r){function i(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var s=0;s>>4),t.next()}function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function l(e,t){var n=new i(e),s=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,s&&("object"==typeof s&&o(s,n),a.state=function(){return o(n,{})}),a}a&&a.exports?a.exports=l:n.amdD&&n.amdO?void 0===(s=function(){return l}.call(t,n,t,a))||(a.exports=s):this.xorwow=l}(0,e=n.nmd(e),n.amdD)},971:(e,t,n)=>{var s;!function(a,r){var i,o=this,l=256,u=r.pow(l,6),c=r.pow(2,52),h=2*c,p=255;function d(e,t,n){var s=[],p=y(g((t=1==t?{entropy:!0}:t||{}).entropy?[e,b(a)]:null==e?function(){try{var e;return i&&(e=i.randomBytes)?e=e(l):(e=new Uint8Array(l),(o.crypto||o.msCrypto).getRandomValues(e)),b(e)}catch(e){var t=o.navigator,n=t&&t.plugins;return[+new Date,o,n,o.screen,b(a)]}}():e,3),s),d=new f(s),x=function(){for(var e=d.g(6),t=u,n=0;e=h;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|d.g(4)},x.quick=function(){return d.g(4)/4294967296},x.double=x,y(b(d.S),a),(t.pass||n||function(e,t,n,s){return s&&(s.S&&m(s,d),e.state=function(){return m(d,{})}),n?(r.random=e,t):e})(x,p,"global"in t?t.global:this==r,t.state)}function f(e){var t,n=e.length,s=this,a=0,r=s.i=s.j=0,i=s.S=[];for(n||(e=[n++]);a{},628:()=>{},601:()=>{},792:()=>{},42:()=>{}},t={};function n(s){var a=t[s];if(void 0!==a)return a.exports;var r=t[s]={id:s,loaded:!1,exports:{}};return e[s].call(r.exports,r,r.exports,n),r.loaded=!0,r.exports}n.amdD=function(){throw new Error("define cannot be used indirect")},n.amdO={},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var s={};return(()=>{"use strict";n.r(s),n.d(s,{ObjectDetection:()=>_D,colorMap:()=>ED,load:()=>RD,startVideo:()=>FD,stopVideo:()=>DD,version:()=>CD});var e={};n.r(e),n.d(e,{assertParamsValid:()=>rr,computeFlatOffset:()=>br,computeOutShape:()=>or,getNormalizedAxes:()=>hr,isSliceContinous:()=>yr,maskToAxes:()=>ir,parseSliceParams:()=>xr,sliceInfo:()=>wr,startForAxis:()=>mr,startIndicesWithElidedDims:()=>pr,stopForAxis:()=>gr,stopIndicesWithElidedDims:()=>dr,stridesForAxis:()=>fr,stridesWithElidedDims:()=>lr});var t={};n.r(t),n.d(t,{collectGatherOpShapeInfo:()=>zu,computeOutShape:()=>Lu,segOpComputeOptimalWindowSize:()=>Mu});var a={};n.r(a),n.d(a,{ERF_A1:()=>wu,ERF_A2:()=>ku,ERF_A3:()=>vu,ERF_A4:()=>Nu,ERF_A5:()=>Iu,ERF_P:()=>xu,PARALLELIZE_THRESHOLD:()=>ru,SELU_SCALE:()=>bu,SELU_SCALEALPHA:()=>yu,applyActivation:()=>el,assertAndGetBroadcastShape:()=>vi,assertAxesAreInnerMostDims:()=>Ji,assertParamsConsistent:()=>su,assignToTypedArray:()=>Fu,axesAreInnerMostDims:()=>Ki,calculateShapes:()=>gu,combineLocations:()=>qi,complexWithEvenIndex:()=>Eu,complexWithOddIndex:()=>Au,computeConv2DInfo:()=>Vr,computeConv3DInfo:()=>Ur,computeDefaultPad:()=>Gr,computeDilation2DInfo:()=>Br,computeOptimalWindowSize:()=>iu,computeOutAndReduceShapes:()=>Xi,computeOutShape:()=>au,computePool2DInfo:()=>Pr,computePool3DInfo:()=>Wr,convertConv2DDataFormat:()=>Jr,eitherStridesOrDilationsAreOne:()=>Yr,expandShapeToKeepDim:()=>Yi,exponent:()=>_u,exponents:()=>Du,fromStringArrayToUint8:()=>Pu,fromUint8ToStringArray:()=>Bu,getAxesPermutation:()=>Zi,getBroadcastDims:()=>wi,getComplexWithIndex:()=>Ru,getFusedBiasGradient:()=>Qo,getFusedDyActivation:()=>Zo,getImageCenter:()=>ou,getInnerMostAxes:()=>eo,getPermuted:()=>uu,getReductionAxes:()=>ki,getReshaped:()=>lu,getReshapedPermuted:()=>cu,getSliceBeginCoords:()=>hu,getSliceSize:()=>pu,getUndoAxesPermutation:()=>Qi,log:()=>Cu,mergeRealAndImagArrays:()=>Su,prepareAndValidate:()=>du,prepareSplitSize:()=>Ou,segment_util:()=>t,shouldFuse:()=>tl,slice_util:()=>e,splitRealAndImagArrays:()=>Tu,tupleValuesAreOne:()=>Xr,upcastType:()=>Vs,validateInput:()=>mu,validateUpdateShape:()=>fu,warn:()=>$u});var r={};n.r(r),n.d(r,{json:()=>Jy});var i={};n.r(i),n.d(i,{json:()=>Zy});var o={};n.r(o),n.d(o,{json:()=>Qy});var l={};n.r(l),n.d(l,{json:()=>eb});var u={};n.r(u),n.d(u,{json:()=>tb});var c={};n.r(c),n.d(c,{json:()=>nb});var h={};n.r(h),n.d(h,{json:()=>sb});var p={};n.r(p),n.d(p,{json:()=>ab});var d={};n.r(d),n.d(d,{json:()=>rb});var f={};n.r(f),n.d(f,{json:()=>ib});var m={};n.r(m),n.d(m,{json:()=>ob});var g={};n.r(g),n.d(g,{json:()=>lb});var y={};n.r(y),n.d(y,{json:()=>ub});var b={};n.r(b),n.d(b,{json:()=>cb});var x={};n.r(x),n.d(x,{json:()=>hb});var w={};n.r(w),n.d(w,{json:()=>pb});var k={};n.r(k),n.d(k,{json:()=>db});var v={};n.r(v),n.d(v,{addImpl:()=>pw,bincountImpl:()=>ak,bincountReduceImpl:()=>rk,ceilImpl:()=>lk,concatImpl:()=>fk,expImpl:()=>ev,expm1Impl:()=>rv,floorImpl:()=>Cv,gatherV2Impl:()=>Ov,greaterImpl:()=>Lv,lessImpl:()=>Yv,linSpaceImpl:()=>nN,logImpl:()=>aN,maxImpl:()=>xN,maximumImpl:()=>vN,minimumImpl:()=>_N,multiplyImpl:()=>lv,negImpl:()=>GN,notEqualImpl:()=>ZN,prodImpl:()=>hI,rangeImpl:()=>dI,rsqrtImpl:()=>$I,simpleAbsImpl:()=>kw,sliceImpl:()=>ek,squaredDifferenceImpl:()=>ZI,stridedSliceImpl:()=>s$,subImpl:()=>mv,tileImpl:()=>l$,topKImpl:()=>u$,transposeImpl:()=>Tw,uniqueImpl:()=>f$});class N{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class I{refCount(e){return $("refCount")}incRef(e){return $("incRef")}timerAvailable(){return!0}time(e){return $("time")}read(e){return $("read")}readSync(e){return $("readSync")}numDataIds(){return $("numDataIds")}disposeData(e,t){return $("disposeData")}write(e,t,n){return $("write")}move(e,t,n,s,a){return $("move")}memory(){return $("memory")}floatPrecision(){return $("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return $("dispose")}}function $(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function C(e){let t=e.length,n=0,s=0;for(;t>0;)s=Math.random()*t|0,t--,n=e[t],e[t]=e[s],e[s]=n}function S(e,t,n){return Math.max(e,Math.min(t,n))}function T(e){return e%2==0?e:e+1}function E(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function A(e,t,n=""){E(_(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function R(e){E(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function F(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||H(e)&&!n)for(let s=0;s0),n){return new Promise(((s,a)=>{let r=0;const i=()=>{if(e())return void s();r++;const o=t(r);null!=n&&r>=n?a():setTimeout(i,o)};i()}))}function B(e,t){let n=1,s=-1;for(let t=0;t=0)n*=e[t];else if(-1===e[t]){if(-1!==s)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${t}`);s=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===s){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[s]=t/n,a}function P(e,t){const n=t.length;return E((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),E(e.every((e=>O(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function W(e,t){const n=[],s=[],a=null!=t&&Array.isArray(t)&&0===t.length,r=null==t||a?null:P(t,e).sort();let i=0;for(let t=0;tt)&&1===e[t]&&(n.push(e[t]),s.push(t)),r[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),s.push(t))}return{newShape:n,keptDims:s}}function V(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function U(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function G(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function H(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function j(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function K(e){return"string"==typeof e||e instanceof String}function q(e){return"number"==typeof e}function X(e){return Array.isArray(e)?X(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":q(e)?"float32":K(e)?"string":"boolean"==typeof e?"bool":"float32"}function Y(e){return!!(e&&e.constructor&&e.call&&e.apply)}function J(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function Q(e,t,n){const s=new Array;if(1===t.length){const a=t[0];for(let t=0;te*t));for(let t=0;te*t));if(0===n)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return Q(0,e,t)}function te(e,t){const n=ne(e,t);for(let e=0;ee*t),1);if(null==t||"float32"===t)return ee(e,new Float32Array(n));if("int32"===t)return ee(e,new Int32Array(n));if("bool"===t)return ee(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function ae(e){e.forEach((t=>{E(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function re(e,t,n){if(0===t)return 0;if(1===t)return e[0];let s=e[e.length-1];for(let t=0;t(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}(this.global.location.search);"tfjsflags"in e&&e.tfjsflags.split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}function ue(){return he}let ce,he=null;function pe(){if(null==ce){let e;if("undefined"!=typeof window)e=window;else if(void 0!==n.g)e=n.g;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}ce=e}return ce}function de(e,t){const n=function(){const e=pe();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const fe="Abs",me="Acos",ge="Acosh",ye="Add",be="AddN",xe="All",we="Any",ke="ArgMax",ve="ArgMin",Ne="Asin",Ie="Asinh",$e="Atan",Ce="Atanh",Se="Atan2",Te="AvgPool",Ee="AvgPoolGrad",Ae="AvgPool3D",Re="AvgPool3DGrad",Fe="BatchMatMul",De="BatchToSpaceND",_e="Bincount",Oe="Cast",Me="Ceil",Le="ClipByValue",ze="Complex",Be="ComplexAbs",Pe="Concat",We="Conv2D",Ve="Conv2DBackpropFilter",Ue="Conv2DBackpropInput",Ge="Conv3D",He="Conv3DBackpropFilterV2",je="Conv3DBackpropInputV2",Ke="Cos",qe="Cosh",Xe="Cumsum",Ye="CropAndResize",Je="DenseBincount",Ze="DepthToSpace",Qe="DepthwiseConv2dNative",et="DepthwiseConv2dNativeBackpropFilter",tt="DepthwiseConv2dNativeBackpropInput",nt="Diag",st="Dilation2D",at="Dilation2DBackpropInput",rt="Dilation2DBackpropFilter",it="RealDiv",ot="Elu",lt="EluGrad",ut="Erf",ct="Equal",ht="Exp",pt="ExpandDims",dt="Expm1",ft="FFT",mt="Fill",gt="FlipLeftRight",yt="Floor",bt="FloorDiv",xt="FusedBatchNorm",wt="GatherV2",kt="GatherNd",vt="Greater",Nt="GreaterEqual",It="Identity",$t="IFFT",Ct="Imag",St="IsFinite",Tt="IsInf",Et="IsNan",At="LeakyRelu",Rt="Less",Ft="LessEqual",Dt="LinSpace",_t="Log",Ot="Log1p",Mt="LogicalAnd",Lt="LogicalNot",zt="LogicalOr",Bt="LRN",Pt="LRNGrad",Wt="Max",Vt="Maximum",Ut="MaxPool",Gt="MaxPoolGrad",Ht="MaxPool3D",jt="MaxPool3DGrad",Kt="MaxPoolWithArgmax",qt="Mean",Xt="Min",Yt="Minimum",Jt="MirrorPad",Zt="Mod",Qt="Multinomial",en="Multiply",tn="Neg",nn="NotEqual",sn="NonMaxSuppressionV3",an="NonMaxSuppressionV4",rn="NonMaxSuppressionV5",on="OnesLike",ln="OneHot",un="Pack",cn="PadV2",hn="Pow",pn="Prelu",dn="Prod",fn="Range",mn="Real",gn="Reciprocal",yn="Relu",bn="Reshape",xn="ResizeNearestNeighbor",wn="ResizeNearestNeighborGrad",kn="ResizeBilinear",vn="ResizeBilinearGrad",Nn="Relu6",In="Reverse",$n="Round",Cn="Rsqrt",Sn="ScatterNd",Tn="Select",En="Selu",An="Slice",Rn="Sin",Fn="Sinh",Dn="Sign",_n="Sigmoid",On="Softplus",Mn="Sqrt",Ln="Sum",zn="SpaceToBatchND",Bn="SplitV",Pn="Softmax",Wn="SquaredDifference",Vn="Square",Un="Sub",Gn="SparseToDense",Hn="StridedSlice",jn="Tan",Kn="Tanh",qn="Tile",Xn="TopK",Yn="Transform",Jn="Transpose",Zn="Unique",Qn="Unpack",es="UnsortedSegmentSum",ts="ZerosLike",ns="Step",ss="FromPixels",as="RotateWithOffset",rs="_FusedMatMul",is="FusedConv2D",os="FusedDepthwiseConv2D",ls=de("kernelRegistry",(()=>new Map)),us=de("gradRegistry",(()=>new Map));function cs(e,t){const n=ms(e,t);return ls.get(n)}function hs(e){return us.get(e)}function ps(e){const t=ls.entries(),n=[];for(;;){const{done:s,value:a}=t.next();if(s)break;const[r,i]=a,[o]=r.split("_");o===e&&n.push(i)}return n}function ds(e){const{kernelName:t,backendName:n}=e,s=ms(t,n);ls.has(s)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),ls.set(s,e)}function fs(e){const{kernelName:t}=e;us.has(t)&&ue().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`),us.set(t,e)}function ms(e,t){return`${t}_${e}`}function gs(e,t){return"string"===t?xs(e):ys([e],t)}function ys(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=F(e)),ue().getBool("DEBUG")&&function(e,t){for(let n=0;n{s=n()};let r;const i=bs();if(this.backendTimer.timerAvailable())r=this.backendTimer.time(a);else{a();for(const e of s)e.dataSync();r=Promise.resolve({kernelMs:bs()-i})}if(ue().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t{vs(t,n.dtype,e)}))}return{kernelName:e,outputs:s,inputs:t,timeMs:r.then((e=>e.kernelMs)),extraInfo:r.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:s,inputs:a,extraInfo:r}=e;n.forEach((e=>{Promise.all([e.data(),s,r]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])}))}))}}function vs(e,t,n){if("float32"!==t)return!1;for(let t=0;t0?s:""} `}}console.log(`%c${o}\t%c${i}\t%c${l}D ${c}\t%c${u}\t%c${h}\t%c${r}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Is(e,t,n,s){const a=Z(t),r=function(e,t,n,s){const a=D(t),r=s[s.length-1],i=new Array(r).fill(0),o=t.length,l="complex64"===n?Ts(e):e;if(o>1)for(let e=0;e" "+e)).join("\n")),l.join("\n")}function $s(e,t,n){let s;return s=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:K(e)?`'${e}'`:"bool"===n?Cs(e):parseFloat(e.toFixed(7)).toString(),L(s,t)}function Cs(e){return 0===e?"false":"true"}function Ss(e,t,n,s,a,r=!0){const i="complex64"===n?2:1,o=t[0],l=t.length;if(0===l)return"complex64"===n?[$s(Ts(e)[0],0,n)]:"bool"===n?[Cs(e[0])]:[e[0].toString()];if(1===l){if(o>20){const t=3*i;let s=Array.from(e.slice(0,t)),r=Array.from(e.slice((o-3)*i,o*i));return"complex64"===n&&(s=Ts(s),r=Ts(r)),["["+s.map(((e,t)=>$s(e,a[t],n))).join(", ")+", ..., "+r.map(((e,t)=>$s(e,a[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Ts(e):Array.from(e)).map(((e,t)=>$s(e,a[t],n))).join(", ")+"]"]}const u=t.slice(1),c=s.slice(1),h=s[0]*i,p=[];if(o>20){for(let t=0;t<3;t++){const s=t*h,r=s+h;p.push(...Ss(e.slice(s,r),u,n,c,a,!1))}p.push("...");for(let t=o-3;t`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||U(t,this.size),this.strides=Z(e)}set(e,...t){0===t.length&&(t=[0]),E(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;tws(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=As().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>ws(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await As().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(As().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Rs.print(this,e)}clone(){return this.throwIfDisposed(),Rs.clone(this)}toString(e=!1){return Is(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Rs.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),As().makeVariable(this,e,t,n)}}function _s(){return de("Tensor",(()=>Ds))}Object.defineProperty(Ds,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),_s();class Os extends Ds{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!_(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);As().disposeTensor(this),this.dataId=e.dataId,As().incRef(this,null)}dispose(){As().disposeVariable(this),this.isDisposedInternal=!0}}var Ms,Ls,zs,Bs,Ps;Object.defineProperty(Os,Symbol.hasInstance,{value:e=>e instanceof Ds&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(Ms||(Ms={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Ls||(Ls={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(zs||(zs={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Bs||(Bs={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ps||(Ps={}));const Ws={float32:Bs,int32:Ls,bool:zs,complex64:Ps};function Vs(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Ws[e][t]}function Us(e){return Vs(e,"int32")}function Gs(e,t){if(e.dtype===t.dtype)return[e,t];const n=Vs(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Hs(e,t){return t.some((t=>t.id===e.id))}function js(e){const t=[];return Ks(e,t,new Set),t}function Ks(e,t,n){if(null==e)return;if(e instanceof Ds)return void t.push(e);if(s=e,!Array.isArray(s)&&"object"!=typeof s)return;var s;const a=e;for(const e in a){const s=a[e];n.has(s)||(n.add(s),Ks(s,t,n))}}function qs(e){return null!=e.kernelName}class Xs{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class Ys{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Xs}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){ps(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof I||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,s=n.then((n=>!(t(tthis.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(s)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return Ys.nextTensorId++}nextVariableId(){return Ys.nextVariableId++}clone(e){const t=Zs.runKernel(It,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e};return Zs.runKernel(Oe,t,{dtype:"float32"})}})),[],{}),t}runKernel(e,t,n){if(null==cs(e,this.backendName))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const s=this.backend.numDataIds();let a=0;n.forEach((e=>{a+="complex64"===e.dtype?3:1}));const r=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=s-t-a-r;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const s=this.isTapeOn(),a=this.state.numBytes,r=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=qs(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(qs(e)){const{kernelName:t,inputs:a,attrs:r}=e;null==this.backendName&&this.backend;const l=cs(t,this.backendName);E(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:a,attrs:r,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const u=i.map((e=>{if(null!=e.rank)return e;const{dataId:t,shape:n,dtype:s}=e;return this.makeTensorFromDataId(t,n,s)}));if(s){const e=this.getTensorsForGradient(t,a,u);n=this.saveTensorsForBackwardMode(e)}return u}}else{const{forwardFunc:t}=e,a=e=>{s&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:u,attrs:c}=e,h=qs(e)?null:e.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(l,u,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=i()})),s&&this.addTapeNode(l,u,t,h,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-r,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map((e=>null!=u[e]?u[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map((e=>this.keep(this.clone(e))))}getTensorsForGradient(e,t,n){const s=hs(e);if(null!=s){const e=s.inputsToSave||[],a=s.outputsToSave||[];let r;s.saveAllInputs?(E(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),r=Object.keys(t).map((e=>t[e]))):r=e.map((e=>t[e]));const i=n.filter(((e,t)=>a[t]));return r.concat(i)}return[]}makeTensor(e,t,n,s){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let a=e;"string"===n&&K(e[0])&&(a=e.map((e=>xs(e))));const r=s.write(a,t,n),i=new Ds(t,n,r,this.nextTensorId());if(this.trackTensor(i,s),"string"===n){const e=this.state.tensorInfo.get(r),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,s){const a=new Ds(t,n=n||"float32",e,this.nextTensorId());return this.trackTensor(a,s),a}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),null!=s&&s!==e.dtype&&(e=e.cast(s));const a=new Os(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*j(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Os||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*j(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,s,a,r){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},o=hs(e);null!=o&&(s=o.gradFunc),null!=s&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],s=ne(e.size,e.dtype);return this.makeTensor(s,e.shape,e.dtype)}return e})),s(e.length>1?e:e[0],a,r))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=js(e),n=new Set(t.map((e=>e.id)));for(let e=0;e{e.kept||e.scopeId!==s.id||this.track(e)}))}gradients(e,t,n,s=!1){if(E(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));E(a instanceof Ds,(()=>"The result y returned by f() must be a tensor."));const r=function(e,t,n){const s={},a={};for(let e=0;es[e.id]=!0)),o=!0,a[r.id]=!0;break}if(o)break}}const r={};r[n.id]=!0;const i={};for(let t=e.length-1;t>=0;t--){const n=e[t],s=n.inputs;for(let e=0;e0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[a.id]=null==n?function(e){const t=te(D(e),"float32");return Zs.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,s){for(let a=t.length-1;a>=0;a--){const r=t[a],i=[];if(r.outputs.forEach((t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)})),null==r.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${r.kernelName}.`);const o=r.gradient(i);for(const t in r.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const a=n((()=>o[t]()));if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const i=r.inputs[t];if(!_(a.shape,i.shape))throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${i.shape}'`);if(null==e[i.id])e[i.id]=a;else{const t=e[i.id];e[i.id]=s(t,a),t.dispose()}}}}(e,r,(e=>this.tidy(e)),Qs);const s=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:a,grads:s}}))}customGrad(e){return E(Y(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;E(t.every((e=>e instanceof Ds)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const s={};return t.forEach(((e,t)=>{s[t]=e})),this.runKernelFunc({forwardFunc:(s,a)=>(n=e(...t,a),E(n.value instanceof Ds,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),E(Y(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,s)=>{const a=n.gradFunc(e,s),r=Array.isArray(a)?a:[a];E(r.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),E(r.every((e=>e instanceof Ds)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const i={};return r.forEach(((e,t)=>{i[t]=()=>e})),i},inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){const t=bs(),n=await this.backend.time(e);return n.wallMs=bs()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Xs;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function Js(){const e=pe();if(null==e._tfengine){const t=new le(e);e._tfengine=new Ys(t)}var t;return t=e._tfengine.ENV,he=t,As=()=>e._tfengine,e._tfengine}Ys.nextTensorId=0,Ys.nextVariableId=0;const Zs=Js();function Qs(e,t){const n={a:e,b:t};return Zs.runKernel(ye,n)}function ea(){if("undefined"!=typeof navigator&&null!=navigator){const e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}return!1}function ta(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const na=ue();function sa(e,t){let n=e;if(H(e))return"string"===t?[]:[e.length];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||H(n)&&"string"!==t;)s.push(n.length),n=n[0];return Array.isArray(e)&&ue().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&aa(e,s,[]),s}function aa(e,t,n){if(n=n||[],!Array.isArray(e)&&!H(e))return void E(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));E(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),E(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const s=t.slice(1);for(let t=0;t=0&&(a=s),ra(s,a,t,n),null==e||!H(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const s=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${s}'`)}const r=sa(e,a);H(e)||Array.isArray(e)||(e=[e]);const i="string"!==a?ys(e,a):F(e,[],!0);return Zs.makeTensor(i,r,a)}function oa(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,a)=>ia(e,`${t}[${a}]`,n,s)))}function la(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+="__op";const a=(...e)=>{Zs.startScope(n);try{const t=s(...e);return oe(t)&&console.error("Cannot return a Promise inside of tidy."),Zs.endScope(t),t}catch(e){throw Zs.endScope(null),e}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}na.registerFlag("DEBUG",(()=>!1),(e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),na.registerFlag("IS_BROWSER",(()=>ta())),na.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node)),na.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),na.registerFlag("PROD",(()=>!1)),na.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>na.getBool("DEBUG"))),na.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),na.registerFlag("IS_TEST",(()=>!1)),na.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>!0)),na.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1));const ua=la({complex_:function(e,t){const n=ia(e,"real","complex"),s=ia(t,"imag","complex");A(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);const a={real:n,imag:s};return Zs.runKernel(ze,a)}});function ca(e,t,n,s){if(null==s&&(s=X(e)),"complex64"===s)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!H(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){ae(t);const e=D(t),s=D(n);E(e===s,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${s}`));for(let e=0;e`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return H(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==s?ys(e,s):F(e,[],!0),Zs.makeTensor(e,t,s)}function ha(e,t,n){return ca(e,t,sa(e,n),n)}const pa={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};async function da(e,t){const n=[],s=[],a=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let r=0;r{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,s=new Uint8Array(n);let a=0;for(let e=0;e{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const s=new Uint8Array(t);let a=0;return n.forEach((e=>{s.set(new Uint8Array(e.buffer),a),a+=e.byteLength})),s.buffer}const ma="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function ga(e){return ma?Buffer.byteLength(e):new Blob([e]).size}function ya(e){if(1===e.length)return e[0];let t=0;e.forEach((e=>{t+=e.byteLength}));const n=new Uint8Array(t);let s=0;return e.forEach((e=>{n.set(new Uint8Array(e),s),s+=e.byteLength})),n.buffer}function ba(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:ga(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:ga(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function xa(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return s=>{const a=new ArrayBuffer(4*s.length),r=new Uint32Array(a);for(let a=0;a>10]+(1023&i)]+t[i>>10];r[a]=o}return new Float32Array(a)}}class wa{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==wa.instance&&(wa.instance=new wa),wa.instance}static registerSaveRouter(e){wa.getInstance().saveRouters.push(e)}static registerLoadRouter(e){wa.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return wa.getHandlers(e,"save")}static getLoadHandlers(e,t){return wa.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[];return("load"===t?wa.getInstance().loadRouters:wa.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&s.push(a)})),s}}const ka=e=>wa.getSaveHandlers(e),va="tensorflowjs",Na="models_store",Ia="model_info_store";function $a(){if(!ue().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Ca(e){const t=e.result;t.createObjectStore(Na,{keyPath:"modelPath"}),t.createObjectStore(Ia,{keyPath:"modelPath"})}class Sa{constructor(e){if(this.indexedDB=$a(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const s=this.indexedDB.open(va,1);s.onupgradeneeded=()=>Ca(s),s.onsuccess=()=>{const a=s.result;if(null==t){const t=a.transaction(Na,"readonly"),s=t.objectStore(Na).get(this.modelPath);s.onsuccess=()=>{if(null==s.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(s.result.modelArtifacts)},s.onerror=e=>(a.close(),n(s.error)),t.oncomplete=()=>a.close()}else{const s=ba(t),r=a.transaction(Ia,"readwrite");let i=r.objectStore(Ia);const o=i.put({modelPath:this.modelPath,modelArtifactsInfo:s});let l;o.onsuccess=()=>{l=a.transaction(Na,"readwrite");const o=l.objectStore(Na).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:s});o.onsuccess=()=>e({modelArtifactsInfo:s}),o.onerror=e=>{i=r.objectStore(Ia);const t=i.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(o.error)),t.onerror=e=>(a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),r.oncomplete=()=>{null==l?a.close():l.oncomplete=()=>a.close()}}},s.onerror=e=>n(s.error)}))}}Sa.URL_SCHEME="indexeddb://";const Ta=e=>{return ue().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Sa.URL_SCHEME)?(t=e.slice(Sa.URL_SCHEME.length),new Sa(t)):null;var t};wa.registerSaveRouter(Ta),wa.registerLoadRouter(Ta);class Ea{constructor(){this.indexedDB=$a()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(va,1);n.onupgradeneeded=()=>Ca(n),n.onsuccess=()=>{const s=n.result,a=s.transaction(Ia,"readonly"),r=a.objectStore(Ia).getAll();r.onsuccess=()=>{const t={};for(const e of r.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},r.onerror=e=>(s.close(),t(r.error)),a.oncomplete=()=>s.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(Sa.URL_SCHEME)?t.slice(Sa.URL_SCHEME.length):t,new Promise(((t,n)=>{const s=this.indexedDB.open(va,1);s.onupgradeneeded=()=>Ca(s),s.onsuccess=()=>{const a=s.result,r=a.transaction(Ia,"readwrite"),i=r.objectStore(Ia),o=i.get(e);let l;o.onsuccess=()=>{if(null==o.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const s=i.delete(e),r=()=>{l=a.transaction(Na,"readwrite");const s=l.objectStore(Na).delete(e);s.onsuccess=()=>t(o.result.modelArtifactsInfo),s.onerror=e=>n(o.error)};s.onsuccess=r,s.onerror=e=>(r(),a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),r.oncomplete=()=>{null==l?a.close():l.oncomplete=()=>a.close()}},s.onerror=e=>n(s.error)}))}}const Aa="/",Ra="tensorflowjs_models",Fa="info",Da="model_topology",_a="weight_specs",Oa="weight_data",Ma="model_metadata";function La(e){return{info:[Ra,e,Fa].join(Aa),topology:[Ra,e,Da].join(Aa),weightSpecs:[Ra,e,_a].join(Aa),weightData:[Ra,e,Oa].join(Aa),modelMetadata:[Ra,e,Ma].join(Aa)}}function za(e){const t=e.split(Aa);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Aa)}class Ba{constructor(e){if(!ue().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=La(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=ba(e);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(ma)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,s=t.length;e{return ue().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ba.URL_SCHEME)?(t=e.slice(Ba.URL_SCHEME.length),new Ba(t)):null;var t};wa.registerSaveRouter(Pa),wa.registerLoadRouter(Pa);class Wa{constructor(){E(ue().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),E("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=Ra+Aa,n=Aa+Fa;for(let s=0;s"scheme must not be undefined or null.")),e.endsWith("://")&&(e=e.slice(0,e.indexOf("://"))),E(e.length>0,(()=>"scheme must not be an empty string."));const n=Va.getInstance();E(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}class Ua{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}}if(ue().get("IS_BROWSER")){ue().setPlatform("browser",new Ua);try{Va.registerManager(Ba.URL_SCHEME,new Wa)}catch(e){}try{Va.registerManager(Sa.URL_SCHEME,new Ea)}catch(e){}}let Ga;function Ha(e,t="float32",n){return t=t||"float32",ae(e),new Es(e,t,n)}ue().get("IS_NODE")&&ue().setPlatform("node",new class{constructor(){this.util=n(628),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=ue().global.fetch?ue().global.fetch(e,t):(null==Ga&&(Ga=n(410)),Ga(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}});const ja=la({cast_:function(e,t){const n=ia(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const s={x:n},a={dtype:t};return Zs.runKernel(Oe,s,a)}}),Ka=la({clone_:function(e){const t={x:ia(e,"x","clone","string_or_numeric")};return Zs.runKernel(It,t)}});function qa(e){return new Promise((e=>setTimeout(e))).then(e)}Js(),Rs={buffer:Ha,cast:ja,clone:Ka,print:function(e,t=!1){console.log(e.toString(t))}};class Xa{constructor(e){if(!ue().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Xa.URL_SCHEME)&&(e=e.slice(Xa.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelTopologyFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};null!=e.signature&&(s.signature=e.signature),null!=e.userDefinedMetadata&&(s.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(s.modelInitializer=e.modelInitializer);const a=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),r=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor;if(r.download=this.modelTopologyFileName,r.href=a,await qa((()=>r.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=t,await qa((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:ba(e)}}}}function Ya(e,t,n,s){!function(e){E(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){E(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),E(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),E(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,s=null==s?1:s);let a=0;return Promise.all(e.map((r=>(r.then((r=>{const i=n+ ++a/e.length*(s-n);return t(i),r})),r))))}async function Ja(e,t){null==t&&(t={});const n=null==t.fetchFunc?ue().platform.fetch:t.fetchFunc,s=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),a=(null==t.onProgress?await Promise.all(s):await Ya(s,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(a):await Ya(a,t.onProgress,.5,1)}Xa.URL_SCHEME="downloads://",wa.registerSaveRouter((e=>ue().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Xa.URL_SCHEME)?function(e="model"){return new Xa(e)}(e.slice(Xa.URL_SCHEME.length)):null));class Za{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(E("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=ue().platform.fetch,E(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&E(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};null!=e.signature&&(s.signature=e.signature),null!=e.userDefinedMetadata&&(s.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(s.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(s)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const a=await this.fetch(this.path,t);if(a.ok)return{modelArtifactsInfo:ba(e),responses:[a]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${a.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,s=t.weightsManifest,a=t.generatedBy,r=t.convertedBy,i=t.format,o=t.signature,l=t.userDefinedMetadata;if(null==n&&null==s)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let u,c;if(null!=s){const e=await this.loadWeights(s);[u,c]=e}const h={modelTopology:n,weightSpecs:u,weightData:c,generatedBy:a,convertedBy:r,format:i};null!=o&&(h.signature=o),null!=l&&(h.userDefinedMetadata=l);const p=t.modelInitializer;return p&&(h.modelInitializer=p),h}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?");return[e.substring(0,t)+"/",n>t?e.substring(n):""]}(t),a=this.weightPathPrefix||n,r=[];for(const t of e)r.push(...t.weights);const i=[],o=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):i.push(a+e+s);return this.weightUrlConverter&&i.push(...await Promise.all(o)),[r,ya(await Ja(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress}))]}}function Qa(e){return null!=e.match(Za.URL_SCHEME_REGEX)}Za.URL_SCHEME_REGEX=/^https?:\/\//;const er=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Qa(e))):Qa(e),n)return tr(e,t)}return null};function tr(e,t){return new Za(e,t)}function nr(e,t){return tr(e,t)}let sr;wa.registerSaveRouter(er),wa.registerLoadRouter(er);const ar=la({fromPixels_:function(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,s=!1,a=!1,r=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)s=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)a=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)r=!0;else if(null!=e.getContext)i=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);o=!0}if(a){const t=2;if(a&&e.readyState element.")}if(null!=cs(ss,Zs.backendName)){const n={pixels:e},s={numChannels:t};return Zs.runKernel(ss,n,s)}const[l,u]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,h;if(i?c=e.getContext("2d").getImageData(0,0,l,u).data:s||n?c=e.data:(r||a||o)&&(null==sr&&(sr=document.createElement("canvas").getContext("2d")),sr.canvas.width=l,sr.canvas.height=u,sr.drawImage(e,0,0,l,u),c=sr.getImageData(0,0,l,u).data),4===t)h=new Int32Array(c);else{const e=l*u;h=new Int32Array(e*t);for(let n=0;n`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`)),E(s===n.length,(()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`));for(let a=0;a`Error in slice${s}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`))}function ir(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function or(e,t,n){const s=[];for(let a=0;a0){const l=t[0],u=n+1;c=pr(i,l,u,s,e),h=dr(o,l,u,a,e),p=lr(r,l,u,e)}else for(let t=0;t-1)r[a]=0;else{const i=ur(t,n,a);let o=s[i];e&1<-1)r[a]=Number.MAX_SAFE_INTEGER;else{const i=ur(t,n,a);let o=s[i];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const l=s[a];return i<0&&(i+=l),i=S(0,i,l-1),i}function gr(e,t,n,s,a,r){let i=t[a];const o=n[a]||1;(e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const l=s[a];return i<0&&(i+=l),i=o>0?S(0,i,l):S(-1,i,l-1),i}function yr(e,t,n){let s=n.length;for(let e=0;e1){s=e;break}for(let a=s+1;a0||n[a]!==e[a])return!1;return!0}function br(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{E(-1!==e,(()=>"slice() does not support negative begin indexing."))})),r=null==n?new Array(a).fill(-1):"number"==typeof n?[n,...new Array(a-1).fill(-1)]:n.lengtht>=0?t:(E(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-s[n]))),[s,r]}function wr(e,t,n,s,a,r,i,o,l){let u=t.slice(),c=n.slice(),h=s;null==s&&(h=new Array(u.length));const p=ir(i);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(0!==i&&0!==o)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(0!==i&&0!==l)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const d=e.length-u.length,f=ir(o),m=e.slice();f.forEach((e=>{u[e]=0,c[e]=1,m.splice(e,0,1)}));const{begin:g,end:y,strides:b}=hr(m,p,d,u,c,h,a,r,i);u=g,c=y,h=b;const x=ir(l);x.forEach((e=>{c[e]=u[e]+1,h[e]=1}));const w=or(u,c,h),k=w.filter(((e,t)=>-1===x.indexOf(t)));return{nonStrided:h.every((e=>1===e)),$begin:u,$end:c,$strides:h,size:w,newShape:m,outShape:k}}class kr{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class vr{constructor(){this.classNameMap={}}static getMap(){return null==vr.instance&&(vr.instance=new vr),vr.instance}static register(e){vr.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Nr(e){E(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),E("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),E(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),vr.register(e)}function Ir(){return Zs}function $r(){return Zs.memory()}function Cr(e,t){return Zs.tidy(e,t)}function Sr(e){js(e).forEach((e=>e.dispose()))}function Tr(e){return Zs.keep(e)}function Er(e){return Zs.setBackend(e)}function Ar(e,t,n=1){return Zs.registerBackend(e,t,n)}function Rr(e){return Zs.customGrad(e)}function Fr(e,t){if((H(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&H(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return ca(e,[],[],t)}Fs=function(e){ue().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")};class Dr extends kr{minimize(e,t=!1,n){const{value:s,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:a[e.name]})));this.applyGradients(e)}else this.applyGradients(a);return Sr(a),t?s:(s.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return function(e,t){E(Y(e),(()=>"The f passed in variableGrads(f) must be a function")),E(null==t||Array.isArray(t)&&t.every((e=>e instanceof Os)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in Zs.registeredVariables)t.push(Zs.registeredVariables[e])}const s=n?t.filter((e=>!e.trainable)):null,a=t.length;E((t=t.filter((e=>e.trainable))).length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`));const{value:r,grads:i}=Zs.gradients(e,t,null,!0);E(i.some((e=>null!=e)),(()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().")),E(0===r.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${r.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=i[t]&&(o[e.name]=i[t])})),null!=s&&s.forEach((e=>o[e.name]=null)),{value:r,grads:o}}(e,t)}dispose(){null!=this.iterations_&&Sr(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Fr(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(Dr,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});const _r=la({abs_:function(e){const t=ia(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return Zs.runKernel(Be,e)}{const e={x:t};return Zs.runKernel(fe,e)}}}),Or=la({add_:function(e,t){let n=ia(e,"a","add"),s=ia(t,"b","add");[n,s]=Gs(n,s);const a={a:n,b:s};return Zs.runKernel(ye,a)}}),Mr=la({all_:function(e,t=null,n=!1){const s={x:ia(e,"x","all","bool")},a={axis:t,keepDims:n};return Zs.runKernel(xe,s,a)}}),Lr=la({any_:function(e,t=null,n=!1){const s={x:ia(e,"x","any","bool")},a={axis:t,keepDims:n};return Zs.runKernel(we,s,a)}}),zr=la({argMax_:function(e,t=0){const n={x:ia(e,"x","argMax")},s={axis:t};return Zs.runKernel(ke,n,s)}});function Br(e,t,n,s,a="NHWC",r){return Vr(e,[...t,e[3]],n,r,s,null,null,Jr(a))}function Pr(e,t,n,s,a,r,i="channelsLast"){const[o,l]=Hr(t);let u;if("channelsLast"===i)u=[o,l,e[3],e[3]];else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);u=[o,l,e[1],e[1]]}return Vr(e,u,n,s,a,r,!1,i)}function Wr(e,t,n,s,a,r,i="NDHWC"){const[o,l,u]=jr(t);let c,h;if("NDHWC"===i)h="channelsLast",c=[o,l,u,e[4],e[4]];else{if("NCDHW"!==i)throw new Error(`Unknown dataFormat ${i}`);h="channelsFirst",c=[o,l,u,e[1],e[1]]}return Ur(e,c,n,s,a,!1,h,r)}function Vr(e,t,n,s,a,r,i=!1,o="channelsLast"){let[l,u,c,h]=[-1,-1,-1,-1];if("channelsLast"===o)[l,u,c,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[l,h,u,c]=e}const[p,d,,f]=t,[m,g]=Hr(n),[y,b]=Hr(s),x=Kr(p,y),w=Kr(d,b),{padInfo:k,outHeight:v,outWidth:N}=function(e,t,n,s,a,r,i,o,l){let u,c,h;if("number"==typeof e){u={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,s,a){null==s&&(s=Gr(e,t,n));const r=e[1];return[qr((e[0]-t+2*s)/n+1,a),qr((r-t+2*s)/n+1,a)]}([t,n],r,s,e,o);c=a[0],h=a[1]}else if("same"===e){c=Math.ceil(t/s),h=Math.ceil(n/a);const e=Math.max(0,(c-1)*s+r-t),o=Math.max(0,(h-1)*a+i-n),l=Math.floor(e/2),p=e-l,d=Math.floor(o/2);u={top:l,bottom:p,left:d,right:o-d,type:"SAME"}}else if("valid"===e)u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-r+1)/s),h=Math.ceil((n-i+1)/a);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===l?e[1][0]:e[2][0],d="channelsLast"===l?e[1][1]:e[2][1],f="channelsLast"===l?e[2][0]:e[3][0],m="channelsLast"===l?e[2][1]:e[3][1];u={top:p,bottom:d,left:f,right:m,type:0===p&&0===d&&0===f&&0===m?"VALID":"EXPLICIT"},c=qr((t-r+p+d)/s+1,o),h=qr((n-i+f+m)/a+1,o)}}return{padInfo:u,outHeight:c,outWidth:h}}(a,u,c,m,g,x,w,r,o),I=i?f*h:f;let $;return"channelsFirst"===o?$=[l,I,v,N]:"channelsLast"===o&&($=[l,v,N,I]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:c,inChannels:h,outHeight:v,outWidth:N,outChannels:I,padInfo:k,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:d,effectiveFilterHeight:x,effectiveFilterWidth:w,dilationHeight:y,dilationWidth:b,inShape:e,outShape:$,filterShape:t}}function Ur(e,t,n,s,a,r=!1,i="channelsLast",o){let[l,u,c,h,p]=[-1,-1,-1,-1,-1];if("channelsLast"===i)[l,u,c,h,p]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[l,p,u,c,h]=e}const[d,f,m,,g]=t,[y,b,x]=jr(n),[w,k,v]=jr(s),N=Kr(d,w),I=Kr(f,k),$=Kr(m,v),{padInfo:C,outDepth:S,outHeight:T,outWidth:E}=function(e,t,n,s,a,r,i,o,l,u,c){let h,p,d,f;if("number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const r=function(e,t,n,s,a,r){null==a&&(a=Gr(e,t,s));const i=e[1],o=e[2];return[qr((e[0]-t+2*a)/s+1,r),qr((i-t+2*a)/s+1,r),qr((o-t+2*a)/s+1,r),1]}([t,n,s,1],o,0,a,e,c);p=r[0],d=r[1],f=r[2]}else if("same"===e){p=Math.ceil(t/a),d=Math.ceil(n/r),f=Math.ceil(s/i);const e=(p-1)*a+o-t,c=(d-1)*r+l-n,m=(f-1)*i+u-s,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,w=Math.floor(m/2);h={top:b,bottom:x,left:w,right:m-w,front:g,back:y,type:"SAME"}}else{if("valid"!==e)throw Error(`Unknown padding parameter: ${e}`);h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-o+1)/a),d=Math.ceil((n-l+1)/r),f=Math.ceil((s-u+1)/i)}return{padInfo:h,outDepth:p,outHeight:d,outWidth:f}}(a,u,c,h,y,b,x,N,I,$,o),A=r?g*p:g;let R;return"channelsFirst"===i?R=[l,A,S,T,E]:"channelsLast"===i&&(R=[l,S,T,E,A]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:c,inWidth:h,inChannels:p,outDepth:S,outHeight:T,outWidth:E,outChannels:A,padInfo:C,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:d,filterHeight:f,filterWidth:m,effectiveFilterDepth:N,effectiveFilterHeight:I,effectiveFilterWidth:$,dilationDepth:w,dilationHeight:k,dilationWidth:v,inShape:e,outShape:R,filterShape:t}}function Gr(e,t,n,s=1){const a=Kr(t,s);return Math.floor((e[0]*(n-1)-n+a)/2)}function Hr(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function jr(e){return"number"==typeof e?[e,e,e]:e}function Kr(e,t){return t<=1?e:e+(e-1)*(t-1)}function qr(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function Xr(e){const[t,n,s]=Hr(e);return 1===t&&1===n&&1===s}function Yr(e,t){return Xr(e)||Xr(t)}function Jr(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}const Zr=la({reshape_:function(e,t){const n={x:ia(e,"x","reshape","string_or_numeric")},s={shape:t};return Zs.runKernel(bn,n,s)}}),Qr=la({avgPool_:function(e,t,n,s,a){const r=ia(e,"x","avgPool","float32");E(Yr(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let i=r,o=!1;3===r.rank&&(o=!0,i=Zr(r,[1,r.shape[0],r.shape[1],r.shape[2]])),E(4===i.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`)),null!=a&&E(O(s),(()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`));const l={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:a};let c=Zs.runKernel(Te,l,u);return c=ja(c,r.dtype),o?Zr(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),ei=la({avgPool3d_:function(e,t,n,s,a,r="NDHWC"){const i=ia(e,"x","avgPool3d","float32");let o=i,l=!1;4===i.rank&&(l=!0,o=Zr(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),E(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),E("NDHWC"===r,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`)),null!=a&&E(O(s),(()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`));const u={x:o},c={filterSize:t,strides:n,pad:s,dimRoundingMode:a,dataFormat:r};let h=Zs.runKernel(Ae,u,c);return h=ja(h,o.dtype),l?Zr(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),ti=la({batchNorm_:function(e,t,n,s,a,r){null==r&&(r=.001);const i=ia(e,"x","batchNorm"),o=ia(t,"mean","batchNorm"),l=ia(n,"variance","batchNorm");let u,c;null!=a&&(u=ia(a,"scale","batchNorm")),null!=s&&(c=ia(s,"offset","batchNorm")),E(o.rank===l.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),E(null==c||o.rank===c.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),E(null==u||o.rank===u.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const h={x:function(e){let t;return t=0===e.rank||1===e.rank?Zr(e,[1,1,1,e.size]):2===e.rank?Zr(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?Zr(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),scale:u,offset:c,mean:o,variance:l},p={varianceEpsilon:r},d=Zs.runKernel(xt,h,p);return Zr(d,i.shape)}}),ni=la({batchNorm2d_:function(e,t,n,s,a,r){const i=ia(e,"x","batchNorm"),o=ia(t,"mean","batchNorm"),l=ia(n,"variance","batchNorm");let u,c;return null!=a&&(u=ia(a,"scale","batchNorm")),null!=s&&(c=ia(s,"offset","batchNorm")),E(2===i.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`)),E(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),E(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=u&&E(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=c&&E(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`)),ti(i,o,l,c,u,r)}}),si=la({batchNorm3d_:function(e,t,n,s,a,r){const i=ia(e,"x","batchNorm"),o=ia(t,"mean","batchNorm"),l=ia(n,"variance","batchNorm");let u,c;return null!=a&&(u=ia(a,"scale","batchNorm")),null!=s&&(c=ia(s,"offset","batchNorm")),E(3===i.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`)),E(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),E(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=u&&E(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=c&&E(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`)),ti(i,o,l,c,u,r)}}),ai=la({batchNorm4d_:function(e,t,n,s,a,r){const i=ia(e,"x","batchNorm"),o=ia(t,"mean","batchNorm"),l=ia(n,"variance","batchNorm");let u,c;return null!=a&&(u=ia(a,"scale","batchNorm")),null!=s&&(c=ia(s,"offset","batchNorm")),E(4===i.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`)),E(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),E(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=u&&E(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=c&&E(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`)),ti(i,o,l,c,u,r)}}),ri=la({clipByValue_:function(e,t,n){const s=ia(e,"x","clipByValue");E(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`));const a={x:s},r={clipValueMin:t,clipValueMax:n};return Zs.runKernel(Le,a,r)}}),ii=la({concat_:function(e,t=0){E(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=oa(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return Ka(n[0]);const s=n,a={axis:t};return Zs.runKernel(Pe,s,a)}}),oi=la({concat1d_:function(e){return ii(e,0)}}),li=la({concat2d_:function(e,t){return ii(e,t)}}),ui=la({concat3d_:function(e,t){return ii(e,t)}}),ci=la({concat4d_:function(e,t){return ii(e,t)}}),hi=la({conv2d_:function(e,t,n,s,a="NHWC",r=[1,1],i){const o=ia(e,"x","conv2d"),l=ia(t,"filter","conv2d");let u=o,c=!1;3===o.rank&&(c=!0,u=Zr(o,[1,o.shape[0],o.shape[1],o.shape[2]])),E(4===u.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`)),E(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),null!=i&&E(O(s),(()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`));const h="NHWC"===a?u.shape[3]:u.shape[1];E(h===l.shape[2],(()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`)),E(Yr(n,r),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${r}'`));const p={x:u,filter:l},d={strides:n,pad:s,dataFormat:a,dilations:r,dimRoundingMode:i},f=Zs.runKernel(We,p,d);return c?Zr(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),pi=la({conv1d_:function(e,t,n,s,a="NWC",r=1,i){const o=ia(e,"x","conv1d"),l=ia(t,"filter","conv1d");let u=o,c=!1;2===o.rank&&(c=!0,u=Zr(o,[1,o.shape[0],o.shape[1]])),E(3===u.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`)),E(3===l.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`)),null!=i&&E(O(s),(()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`)),E(u.shape[2]===l.shape[1],(()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`)),E(Yr(n,r),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${r}'`)),E("NWC"===a,(()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`));const h=Zr(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=Zr(u,[u.shape[0],1,u.shape[1],u.shape[2]]),d=hi(p,h,[1,n],s,"NHWC",[1,r],i);return Zr(d,c?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}}),di=la({conv2DBackpropInput_:function(e,t,n,s,a,r="NHWC",i){E(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,l=t,u=!1;3===t.rank&&(u=!0,l=Zr(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),E(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),E(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),E(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const c="NHWC"===r?o[3]:o[1],h="NHWC"===r?l.shape[3]:l.shape[1];E(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`)),E(h===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`)),null!=i&&E(O(a),(()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`));const p={dy:l,filter:n},d={strides:s,pad:a,dataFormat:r,dimRoundingMode:i,inputShape:o},f=Zs.runKernel(Ue,p,d);return u?Zr(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),fi=la({conv2dTranspose_:function(e,t,n,s,a,r){const i=ia(e,"x","conv2dTranspose"),o=ia(t,"filter","conv2dTranspose");return di(n,i,o,s,a,"NHWC",r)}}),mi=la({conv3d_:function(e,t,n,s,a="NDHWC",r=[1,1,1]){const i=ia(e,"x","conv3d"),o=ia(t,"filter","conv3d");let l=i,u=!1;4===i.rank&&(u=!0,l=Zr(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),E(5===l.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`)),E(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),E(l.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),E(Yr(n,r),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${r}'`)),E("NDHWC"===a,(()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`));const c={x:l,filter:o},h={strides:n,pad:s,dataFormat:a,dilations:r},p=Zs.runKernel(Ge,c,h);return u?Zr(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),gi=la({depthwiseConv2d_:function(e,t,n,s,a="NHWC",r=[1,1],i){const o=ia(e,"x","depthwiseConv2d"),l=ia(t,"filter","depthwiseConv2d");let u=o,c=!1;3===o.rank&&(c=!0,u=Zr(o,[1,o.shape[0],o.shape[1],o.shape[2]])),E(4===u.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`)),E(4===l.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`)),E(u.shape[3]===l.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`)),null!=i&&E(O(s),(()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`));const h={x:u,filter:l},p={strides:n,pad:s,dataFormat:a,dilations:r,dimRoundingMode:i},d=Zs.runKernel(Qe,h,p);return c?Zr(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),yi=la({floorDiv_:function(e,t){let n=ia(e,"a","floorDiv"),s=ia(t,"b","floorDiv");[n,s]=Gs(n,s);const a={a:n,b:s};return Zs.runKernel(bt,a)}}),bi=la({div_:function(e,t){let n=ia(e,"a","div"),s=ia(t,"b","div");if([n,s]=Gs(n,s),"int32"===n.dtype&&"int32"===s.dtype)return yi(n,s);const a={a:n,b:s};return Zs.runKernel(it,a,{})}}),xi=la({elu_:function(e){const t={x:ia(e,"x","elu")};return Zs.runKernel(ot,t)}});function wi(e,t){const n=e.length,s=[];for(let a=0;a1&&1===i&&s.unshift(r)}return s}function ki(e,t){const n=[];for(let s=0;s1)&&n.unshift(r)}return n}function vi(e,t){const n=[],s=Math.max(e.length,t.length);for(let a=0;a"Axis must be <= rank of the tensor"));const s={input:n},a={dim:t};return Zs.runKernel(pt,s,a)}}),$i=la({tile_:function(e,t){const n=ia(e,"x","tile","string_or_numeric");E(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const s={x:n},a={reps:t};return Zs.runKernel(qn,s,a)}}),Ci=la({eye_:function(e,t,n,s="float32"){null==t&&(t=e);const a=Ha([e,t],s),r=e<=t?e:t;for(let e=0;e{const s=Oi(e,t,!0),a=Li(e,s),r=Li(ja(a,"float32"),Di(zi(_i(a),t,!0)));return n([r]),{value:r,gradFunc:(e,n)=>{const[s]=n,a=_i(s);return Li(e,Mi(zi(e,t,!0),a))}}}))(n)}}),Pi=la({logicalAnd_:function(e,t){const n=ia(e,"a","logicalAnd","bool"),s=ia(t,"b","logicalAnd","bool");vi(n.shape,s.shape);const a={a:n,b:s};return Zs.runKernel(Mt,a)}}),Wi=la({maxPool_:function(e,t,n,s,a){const r=ia(e,"x","maxPool");let i=r,o=!1;3===r.rank&&(o=!0,i=Zr(r,[1,r.shape[0],r.shape[1],r.shape[2]])),E(4===i.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`)),E(Yr(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),null!=a&&E(O(s),(()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`));const l={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:a},c=Zs.runKernel(Ut,l,u);return o?Zr(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Vi=la({maxPool3d_:function(e,t=[1,1,1],n,s,a,r="NDHWC"){const i=ia(e,"x","maxPool3d");let o=i,l=!1;4===i.rank&&(l=!0,o=Zr(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),E(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),E("NDHWC"===r,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`)),null!=a&&E(O(s),(()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`));const u={x:o},c={filterSize:t,strides:n,pad:s,dimRoundingMode:a,dataFormat:r},h=Zs.runKernel(Ht,u,c);return l?Zr(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),Ui=la({maximum_:function(e,t){let n=ia(e,"a","maximum"),s=ia(t,"b","maximum");[n,s]=Gs(n,s),"bool"===n.dtype&&(n=ja(n,"int32"),s=ja(s,"int32")),vi(n.shape,s.shape);const a={a:n,b:s};return Zs.runKernel(Vt,a)}}),Gi=la({mean_:function(e,t=null,n=!1){const s={x:ia(e,"x","mean")},a={axis:t,keepDims:n};return Zs.runKernel(qt,s,a)}}),Hi=la({min_:function(e,t=null,n=!1){const s={x:ia(e,"x","min")},a={axis:t,keepDims:n};return Zs.runKernel(Xt,s,a)}}),ji=la({minimum_:function(e,t){let n=ia(e,"a","minimum"),s=ia(t,"b","minimum");[n,s]=Gs(n,s),"bool"===n.dtype&&(n=ja(n,"int32"),s=ja(s,"int32")),vi(n.shape,s.shape);const a={a:n,b:s};return Zs.runKernel(Yt,a)}});function Ki(e,t){for(let n=0;ne[t]))]}function Yi(e,t){return qi(e,t.map((e=>1)),t)}function Ji(e,t,n){E(Ki(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function Zi(e,t){if(Ki(e,t))return null;const n=[];for(let s=0;sn.push(e))),n}function Qi(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function eo(e,t){const n=[];for(let s=t-e;s=2, but it is ${t}`);const a={indices:ia(e,"indices","oneHot","int32")},r={depth:t,onValue:n,offValue:s};return Zs.runKernel(ln,a,r)}});function io(e,t="float32"){if("complex64"===t){const t=io(e,"float32"),n=io(e,"float32");return ua(t,n)}const n=ne(D(e),t);return Zs.makeTensor(n,e,t)}function oo(e,t="float32"){if("complex64"===t){const t=oo(e,"float32"),n=io(e,"float32");return ua(t,n)}const n=te(D(e),t);return Zs.makeTensor(n,e,t)}const lo=la({onesLike_:function(e){const t={x:ia(e,"x","onesLike")};return Zs.runKernel(on,t)}}),uo=la({pad_:function(e,t,n=0){const s=ia(e,"x","pad");if(0===s.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const a={paddings:t,constantValue:n},r={x:s};return Zs.runKernel(cn,r,a)}}),co=la({prelu_:function(e,t){const n={x:ia(e,"x","prelu"),alpha:ia(t,"alpha","prelu")};return Zs.runKernel(pn,n)}});var ho=n(377);class po{constructor(e,t,n,s,a){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=s,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const r=a||Math.random();this.random=ho.alea(r.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let s,a,r;do{s=2*this.random()-1,a=2*this.random()-1,r=s*s+a*a}while(r>=1||0===r);const i=Math.sqrt(-2*Math.log(r)/r);e=this.mean+this.stdDev*s*i,t=this.mean+this.stdDev*a*i,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class fo{constructor(e=0,t=1,n,s){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==s&&(s=Math.random()),"number"==typeof s&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ho.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const mo=la({randomNormal_:function(e,t=0,n=1,s,a){if(null!=s&&"bool"===s)throw new Error(`Unsupported data type ${s}`);const r=new po(t,n,s,!1,a),i=Ha(e,s);for(let e=0;e`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`)),E(4===l.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`)),E(4===u.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`)),E(1===u.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`)),E(1===u.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`));const p=l.shape[2],d=l.shape[3];E(u.shape[2]===p*d,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*d}, but got ${u.shape[2]}.`));const f=gi(c,l,s,a,i,r),m=hi(f,u,1,"valid",i);return h?Zr(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}),ko=la({sigmoid_:function(e){const t={x:ia(e,"x","sigmoid")};return Zs.runKernel(_n,t)}}),vo=la({slice_:function(e,t,n){const s=ia(e,"x","slice","string_or_numeric");if(0===s.rank)throw new Error("Slicing scalar is not possible");const a={x:s},r={begin:t,size:n};return Zs.runKernel(An,a,r)}}),No=la({slice1d_:function(e,t,n){const s=ia(e,"x","slice1d");return E(1===s.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`)),vo(s,[t],[n])}}),Io=la({slice2d_:function(e,t,n){const s=ia(e,"x","slice2d");return E(2===s.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`)),vo(s,t,n)}}),$o=la({slice3d_:function(e,t,n){const s=ia(e,"x","slice3d");return E(3===s.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`)),vo(s,t,n)}}),Co=la({slice4d_:function(e,t,n){const s=ia(e,"x","slice4d");return E(4===s.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`)),vo(s,t,n)}}),So=la({softmax_:function(e,t=-1){const n=ia(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const s={logits:n},a={dim:t};return Zs.runKernel(Pn,s,a)}}),To=la({softplus_:function(e){const t={x:ia(e,"x","softplus")};return Zs.runKernel(On,t)}}),Eo=la({split_:function(e,t,n=0){const s={x:ia(e,"x","split")},a={numOrSizeSplits:t,axis:n};return Zs.runKernel(Bn,s,a)}}),Ao=la({sqrt_:function(e){const t={x:ia(e,"x","sqrt")};return Zs.runKernel(Mn,t)}}),Ro=la({squeeze_:function(e,t){const n=ia(e,"x","squeeze");return Zr(n,W(n.shape,t).newShape)}}),Fo=la({stack_:function(e,t=0){const n=oa(e,"tensors","stack","string_or_numeric");E(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&E(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const s=n,a={axis:t};return Zs.runKernel(un,s,a)}}),Do=la({tanh_:function(e){const t={x:ia(e,"x","tanh")};return Zs.runKernel(Kn,t)}});function _o(e,t){R(e);const n=sa(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return ca(e,null,n,t)}function Oo(e,t,n){if(R(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const s=sa(e,n);if(2!==s.length&&1!==s.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return ca(e,t,s,n)}const Mo=la({truncatedNormal_:function(e,t=0,n=1,s,a){if(null!=s&&"bool"===s)throw new Error("Unsupported data type $ { dtype }");const r=new po(t,n,s,!0,a),i=Ha(e,s);for(let e=0;e=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const s={value:n},a={axis:t};return Zs.runKernel(Qn,s,a)}}),zo=la({broadcastTo_:function(e,t){let n=ia(e,"broadcastTo","x");const s=n.shape;if(t.some((e=>!(e>0)||e%1!=0)))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){const e=n.shape.slice();for(;e.length=0;e--)if(a[e]===t[e])r[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(0===r.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return Ka(n);const i={x:n},o={reps:r};return Zs.runKernel(qn,i,o)}}),Bo=la({where_:function(e,t,n){const s=ia(t,"a","where"),a=ia(n,"b","where"),r=ia(e,"condition","where","bool"),i=vi(s.shape,a.shape),o=zo(s,i),l=zo(a,i);1===r.rank&&E(r.shape[0]===s.shape[0],(()=>"The first dimension of `a` must match the size of `condition`.")),1!==r.rank&&A(r.shape,l.shape,"Error in where: ");const u={condition:r,t:o,e:l};return Zs.runKernel(Tn,u)}}),Po=la({zerosLike_:function(e){const t={x:ia(e,"x","zerosLike")};return Zs.runKernel(ts,t)}}),Wo=la({transpose_:function(e,t){const n=ia(e,"x","transpose");if(null==t&&(t=n.shape.map(((e,t)=>t)).reverse()),E(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`)),t.forEach((e=>{E(e>=0&&e"All entries in 'perm' must be between 0 and "+(n.rank-1)+` but got ${t}`))})),n.rank<=1)return n.clone();const s={x:n},a={perm:t};return Zs.runKernel(Jn,s,a)}}),Vo=la({dropout_:function(e,t,n,s){const a=ia(e,"x","dropout");if(E("float32"===a.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`)),E(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof Ds?a.clone():a;const r=function(e,t){if(null==t)return e.shape.slice();if(_(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let s=0;s`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Zs.runKernel(ft,t)}}),jo=la({rfft_:function(e,t){E("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const s=e.size/n;let a;if(null!=t&&t0)),r=e.shape.map((e=>e));r[e.shape.length-1]=t,a=vo(e,s,r),n=t}else if(null!=t&&t>n){const s=e.shape.map((e=>e));s[e.shape.length-1]=t-n,a=ii([e,io(s)],e.shape.length-1),n=t}else a=e;const r=Po(a),i=Zr(ua(a,r),[s,n]),o=Ho(i),l=Math.floor(n/2)+1,u=Go(o),c=Uo(o),h=Eo(u,[l,n-l],u.shape.length-1),p=Eo(c,[l,n-l],c.shape.length-1),d=a.shape.slice();return d[a.shape.length-1]=l,Zr(ua(h[0],p[0]),d)}}),Ko=la({ifft_:function(e){E("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Zs.runKernel($t,t)}}),qo=la({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let s;if(t<=2){const a=Zr(e,[n,t]);s=Ko(a)}else{const a=[n,2*(t-1)],r=Zr(Go(e),[n,t]),i=Zr(Uo(e),[n,t]),o=bo(vo(r,[0,1],[n,t-2]),1),l=Mi(bo(vo(i,[0,1],[n,t-2]),1),Fr(-1)),u=ii([r,o],1),c=ii([i,l],1),h=Zr(ua(u,c),[a[0],a[1]]);s=Ko(h)}if(s=Go(s),3===e.rank&&0!==e.shape[0]){const t=s,n=e.shape[0];s=Zr(s,[n,s.shape[0]/n,s.shape[1]]),t.dispose()}return s}}),Xo=la({conv2DBackpropFilter_:function(e,t,n,s,a,r="NHWC",i){let o=e;3===e.rank&&(o=Zr(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=Zr(t,[1,t.shape[0],t.shape[1],t.shape[2]])),E(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),E(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),E(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const u="NHWC"===r?o.shape[3]:o.shape[1],c="NHWC"===r?l.shape[3]:l.shape[1];E(u===n[2],(()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`)),E(c===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`)),null!=i&&E(O(a),(()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`));const h={x:o,dy:l},p={strides:s,pad:a,dataFormat:r,dimRoundingMode:i,filterShape:n};return Zs.runKernel(Ve,h,p)}}),Yo=la({relu6_:function(e){const t={x:ia(e,"x","relu6")};return Zs.runKernel(Nn,t)}}),Jo=la({step_:function(e,t=0){const n={x:ia(e,"x","step")},s={alpha:t};return Zs.runKernel(ns,n,s)}});function Zo(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Mi(e,Jo(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Qo(e,t){let n=t;const s=ki(e.shape,t.shape);return s.length>0&&(n=zi(n,s)),Zr(n,e.shape)}function el(e,t,n,s){if("linear"===t)return e;if("relu"===t)return yo(e);if("elu"===t)return xi(e);if("relu6"===t)return Yo(e);if("prelu"===t)return co(e,n);if("leakyrelu"===t)return Fi(e,s);throw new Error(`Unknown fused activation ${t}.`)}const tl=(e,t)=>!(e>0)||"linear"===t,nl=la({fusedConv2d_:function({x:e,filter:t,strides:n,pad:s,dataFormat:a="NHWC",dilations:r=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",!1===tl(Zs.state.gradientDepth,l)){let h=hi(e,t,n,s,a,r,i);return null!=o&&(h=Or(h,o)),el(h,l,u,c)}const h=ia(e,"x","conv2d"),p=ia(t,"filter","conv2d");let d=h,f=!1;3===h.rank&&(f=!0,d=Zr(h,[1,h.shape[0],h.shape[1],h.shape[2]])),E(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),E(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),null!=i&&E(O(s),(()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`)),E(d.shape[3]===p.shape[2],(()=>`Error in conv2d: depth of input (${d.shape[3]}) must match input depth for filter ${p.shape[2]}.`)),E(Yr(n,r),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${r}'`)),E("NHWC"===a,(()=>`Error in conv2d: got dataFormat of ${a} but only NHWC is currently supported.`));const m=Vr(d.shape,p.shape,n,r,s,i);let g,y;null!=o&&(g=ia(o,"bias","fused conv2d"),[g]=Gs(g,h),vi(m.outShape,g.shape)),null!=u&&(y=ia(u,"prelu weights","fused conv2d"));const b=(e,t)=>{const[a,i,o,u]=t,c=Zo(e,o,l);E(Xr(r),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`));const h=[di(i.shape,c,a,n,s),Xo(i,c,a.shape,n,s)];if(null!=u){const e=Qo(u,c);h.push(e)}return h},x={x:d,filter:p,bias:g,preluActivationWeights:y},w={strides:n,pad:s,dataFormat:a,dilations:r,dimRoundingMode:i,activation:l,leakyreluAlpha:c};return null==o?Rr(((e,t,n)=>{let s=Zs.runKernel(is,x,w);return n([t,e,s]),f&&(s=Zr(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}))(d,p):Rr(((e,t,n,s)=>{let a=Zs.runKernel(is,x,w);return s([t,e,a,n]),f&&(a=Zr(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}))(d,p,g)}}),sl=la({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,s,a,r=[1,1],i){let o=e;3===e.rank&&(o=Zr(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=Zr(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={x:o,dy:l},c={strides:s,pad:a,dimRoundingMode:i,dilations:r,filterShape:n};return Zs.runKernel(et,u,c)}}),al=la({depthwiseConv2dNativeBackpropInput_:function(e,t,n,s,a,r=[1,1],i){let o=t,l=!1;3===t.rank&&(l=!0,o=Zr(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={dy:o,filter:n},c={strides:s,pad:a,dimRoundingMode:i,dilations:r,inputShape:e},h=Zs.runKernel(tt,u,c);return l?Zr(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),rl=la({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:s,dataFormat:a="NHWC",dilations:r=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(!1===tl(Zs.state.gradientDepth,l)){let h=gi(e,t,n,s,a,r,i);return null!=o&&(h=Or(h,o)),el(h,l,u,c)}const h=ia(e,"x","depthwiseConv2d"),p=ia(t,"filter","depthwiseConv2d");let d=h,f=!1;3===h.rank&&(f=!0,d=Zr(h,[1,h.shape[0],h.shape[1],h.shape[2]])),E(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),E(4===p.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`)),E(d.shape[3]===p.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`)),null==r&&(r=[1,1]),E(Yr(n,r),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${r}'`)),null!=i&&E(O(s),(()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${s}.`));const m=Vr(d.shape,p.shape,n,r,s,i,!0);let g,y;null!=o&&(g=ia(o,"bias","fused conv2d"),[g]=Gs(g,h),vi(m.outShape,g.shape)),null!=u&&(y=ia(u,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{E(Xr(r),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${r}'`));const[a,o,u,c]=t,h=Zo(e,u,l),p=al(o.shape,h,a,n,s,r,i),d=sl(o,h,a.shape,n,s,r,i);return null!=c?[p,d,Qo(g,h)]:[p,d]},x={x:d,filter:p,bias:g,preluActivationWeights:y},w={strides:n,pad:s,dataFormat:a,dilations:r,dimRoundingMode:i,activation:l,leakyreluAlpha:c};return null==o?Rr(((e,t,n)=>{let s=Zs.runKernel(os,x,w);return n([t,e,s]),f&&(s=Zr(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}))(d,p):Rr(((e,t,n,s)=>{let a=Zs.runKernel(os,x,w);return s([t,e,a,n]),f&&(a=Zr(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}))(d,p,g)}}),il=la({matMul_:function(e,t,n=!1,s=!1){let a=ia(e,"a","matMul"),r=ia(t,"b","matMul");[a,r]=Gs(a,r);const i={a,b:r},o={transposeA:n,transposeB:s};return Zs.runKernel(Fe,i,o)}}),ol=la({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:a,activation:r="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(!1===tl(Zs.state.gradientDepth,r)){let l=il(e,t,n,s);return null!=a&&(l=Or(l,a)),el(l,r,i,o)}let l=ia(e,"a","fused matMul"),u=ia(t,"b","fused matMul");[l,u]=Gs(l,u);const c=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=s?u.shape[u.rank-1]:u.shape[u.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],d=s?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=D(f),y=D(m);E(l.rank>=2&&u.rank>=2&&l.rank===u.rank,(()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`)),E(_(f,m),(()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`)),E(c===h,(()=>`Error in fused matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${s} must match.`));const b=l.shape.slice(0,-2).concat([p,d]),x=Zr(l,n?[g,c,p]:[g,p,c]),w=Zr(u,s?[y,d,h]:[y,h,d]);let k,v;null!=a&&(k=ia(a,"bias","fused matMul"),[k]=Gs(k,l),vi(b,k.shape)),null!=i&&(v=ia(i,"prelu weights","fused matMul"));const N=(e,t)=>{const[i,o,l,u]=t,c=Zo(Zr(e,l.shape),l,r);let h,p;return n||s?!n&&s?(h=il(c,o,!1,!1),p=il(c,i,!0,!1)):n&&!s?(h=il(o,c,!1,!0),p=il(i,c,!1,!1)):(h=il(o,c,!0,!0),p=il(c,i,!0,!0)):(h=il(c,o,!1,!0),p=il(i,c,!0,!1)),null!=a?[h,p,Qo(u,c)]:[h,p]},I={a:x,b:w,bias:k,preluActivationWeights:v},$={transposeA:n,transposeB:s,activation:r,leakyreluAlpha:o};return null==a?Rr(((e,t,n)=>{const s=Zs.runKernel(rs,I,$);return n([e,t,s]),{value:Zr(s,b),gradFunc:N}}))(x,w):Rr(((e,t,n,s)=>{const a=Zs.runKernel(rs,I,$);return s([e,t,a,n]),{value:Zr(a,b),gradFunc:N}}))(x,w,k)}});function ll(e,t,n){const s=1-e%2,a=new Float32Array(e);for(let r=0;r`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),E(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`)),E(1===l.rank&&l.shape[0]===u,(()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`)),E(2===s.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`)),E(s[0]>=1&&s[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${s}`)),E("bilinear"===a||"nearest"===a,(()=>`method must be bilinear or nearest, but was ${a}`));const c={image:i,boxes:o,boxInd:l},h={method:a,extrapolationValue:r,cropSize:s};return Zs.runKernel(Ye,c,h)}}),pl=la({flipLeftRight_:function(e){const t=ia(e,"image","flipLeftRight","float32");E(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return Zs.runKernel(gt,n,{})}}),dl=la({rotateWithOffset_:function(e,t,n=0,s=.5){const a=ia(e,"image","rotateWithOffset","float32");E(4===a.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`));const r={image:a},i={radians:t,fillValue:n,center:s};return Zs.runKernel(as,r,i)}});function fl(e,t,n,s,a,r){null==s&&(s=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==r&&(r=0);const i=e.shape[0];return n=Math.min(n,i),E(0<=s&&s<=1,(()=>`iouThreshold must be in [0, 1], but was '${s}'`)),E(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),E(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),E(1===t.rank,(()=>"scores must be a 1D tensor")),E(t.shape[0]===i,(()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`)),E(0<=r&&r<=1,(()=>`softNmsSigma must be in [0, 1], but was '${r}'`)),{maxOutputSize:n,iouThreshold:s,scoreThreshold:a,softNmsSigma:r}}const ml=la({nonMaxSuppression_:function(e,t,n,s=.5,a=Number.NEGATIVE_INFINITY){const r=ia(e,"boxes","nonMaxSuppression"),i=ia(t,"scores","nonMaxSuppression"),o=fl(r,i,n,s,a),l={maxOutputSize:n=o.maxOutputSize,iouThreshold:s=o.iouThreshold,scoreThreshold:a=o.scoreThreshold};return Zs.runKernel(sn,{boxes:r,scores:i},l)}});function gl(e,t,n){const s=function(e,t,n){return function(e,t,n){let s=0,a=e.length,r=0,i=!1;for(;s>>1);const o=n(t,e[r]);o>0?s=r+1:(a=r,i=!o)}return i?s:-s-1}(e,t,n||yl)}(e,t,n),a=s<0?-(s+1):s;e.splice(a,0,t)}function yl(e,t){return e>t?1:ea&&u.push({score:t[e],boxIndex:e,suppressBeginIndex:0});u.sort(Il);const c=r>0?-.5/r:0,h=[],p=[];for(;h.length0;){const t=u.pop(),{score:n,boxIndex:r,suppressBeginIndex:i}=t;if(n=i;--n){const i=vl(e,r,h[n]);if(i>=s){o=!0;break}if(t.score=t.score*Nl(s,c,i),t.score<=a)break}t.suppressBeginIndex=h.length,o||(t.score===n?(h.push(r),p.push(t.score)):t.score>a&&gl(u,t,Il))}const d=h.length,f=n-d;o&&f>0&&(h.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:h};return i&&(m.selectedScores=p),l&&(m.validOutputs=d),m}function vl(e,t,n){const s=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),r=Math.min(s[0],s[2]),i=Math.min(s[1],s[3]),o=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),u=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),h=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),d=(o-r)*(l-i),f=(h-u)*(p-c);if(d<=0||f<=0)return 0;const m=Math.max(r,u),g=Math.max(i,c),y=Math.min(o,h),b=Math.min(l,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(d+f-x)}function Nl(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function Il(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const $l=la({nonMaxSuppressionWithScore_:function(e,t,n,s=.5,a=Number.NEGATIVE_INFINITY,r=0){const i=ia(e,"boxes","nonMaxSuppression"),o=ia(t,"scores","nonMaxSuppression"),l=fl(i,o,n,s,a,r),u={boxes:i,scores:o},c={maxOutputSize:n=l.maxOutputSize,iouThreshold:s=l.iouThreshold,scoreThreshold:a=l.scoreThreshold,softNmsSigma:r=l.softNmsSigma},h=Zs.runKernel(rn,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}}),Cl=la({nonMaxSuppressionPadded_:function(e,t,n,s=.5,a=Number.NEGATIVE_INFINITY,r=!1){const i=ia(e,"boxes","nonMaxSuppression"),o=ia(t,"scores","nonMaxSuppression"),l=fl(i,o,n,s,a,null),u={boxes:i,scores:o},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:r},h=Zs.runKernel(an,u,c);return{selectedIndices:h[0],validOutputs:h[1]}}}),Sl=la({resizeBilinear_:function(e,t,n=!1,s=!1){const a=ia(e,"images","resizeBilinear");E(3===a.rank||4===a.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`)),E(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),E(!1===s||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let r=a,i=!1;3===a.rank&&(i=!0,r=Zr(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const[]=t,o={images:r},l={alignCorners:n,halfPixelCenters:s,size:t},u=Zs.runKernel(kn,o,l);return i?Zr(u,[u.shape[1],u.shape[2],u.shape[3]]):u}}),Tl=la({resizeNearestNeighbor_:function(e,t,n=!1,s=!1){const a=ia(e,"images","resizeNearestNeighbor");E(3===a.rank||4===a.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`)),E(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),E("float32"===a.dtype||"int32"===a.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),E(!1===s||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let r=a,i=!1;3===a.rank&&(i=!0,r=Zr(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const[]=t,o={images:r},l={alignCorners:n,halfPixelCenters:s,size:t},u=Zs.runKernel(xn,o,l);return i?Zr(u,[u.shape[1],u.shape[2],u.shape[3]]):u}}),El=la({transform_:function(e,t,n="nearest",s="constant",a=0,r){const i=ia(e,"image","transform","float32"),o=ia(t,"transforms","transform","float32");E(4===i.rank,(()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`)),E(2===o.rank&&(o.shape[0]===i.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),E(null==r||2===r.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${r}.`));const l={image:i,transforms:o},u={interpolation:n,fillMode:s,fillValue:a,outputShape:r};return Zs.runKernel(Yn,l,u)}}),Al=la({lessEqual_:function(e,t){let n=ia(e,"a","lessEqual"),s=ia(t,"b","lessEqual");[n,s]=Gs(n,s),vi(n.shape,s.shape);const a={a:n,b:s};return Zs.runKernel(Ft,a)}});function Rl(e,t,n=1,s="float32"){if(0===n)throw new Error("Cannot have a step of zero");const a={start:e,stop:t,step:n,dtype:s};return Zs.runKernel(fn,{},a)}const Fl=la({bandPart_:function(e,t,n){E(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),E(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const s=ia(e,"a","bandPart");E(s.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`));const a=s.shape,[r,i]=s.shape.slice(-2);if(!(t<=r))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${r}).`);if(!(n<=i))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`);t<0&&(t=r),n<0&&(n=i);const o=Zr(Rl(0,r,1,"int32"),[-1,1]),l=Rl(0,i,1,"int32"),u=Li(o,l),c=Pi(Al(u,Fr(+t,"int32")),Ri(u,Fr(-n,"int32"))),h=io([r,i],s.dtype);return Zr(Fo(Lo(Zr(s,[-1,r,i])).map((e=>Bo(c,e,h)))),a)}}),Dl=la({pow_:function(e,t){let n=ia(e,"base","pow"),s=ia(t,"exp","pow");[n,s]=Gs(n,s);const a={a:n,b:s};return Zs.runKernel(hn,a)}});function _l(e,t,n=null){if(0===e.rank)return _r(e);if(1!==e.rank&&null===n)return _l(Zr(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return zi(_r(e),n);if(t===1/0)return Oi(_r(e),n);if(t===-1/0)return Hi(_r(e),n);if("euclidean"===t||2===t)return Ao(zi(Dl(_r(e),Fr(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return Oi(zi(_r(e),n[0]),n[1]-1);if(t===1/0)return Oi(zi(_r(e),n[1]),n[0]);if(t===-1/0)return Hi(zi(_r(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Ao(zi(to(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Ol=la({norm_:function(e,t="euclidean",n=null,s=!1){const a=_l(e=ia(e,"x","norm"),t,n);let r=a.shape;if(s){const t=P(n,e.shape);r=Yi(a.shape,t)}return Zr(a,r)}}),Ml=la({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,E(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=Eo(e,e.shape[0],0).map((e=>Ro(e,[0])));E(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],s=e;for(let t=0;t{let e=s[t];if(t>0)for(let s=0;s{E(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],s=e.shape[1];let a=Ci(n),r=Ka(e);const i=Oo([[1]],[1,1]);let o=Ka(i);const l=n>=s?s:n;for(let e=0;e{const t=vo(r,[e,e],[n-e,1]),l=Ol(t),u=vo(r,[e,e],[1,1]),c=Bo(Ai(u,0),Oo([[-1]]),Oo([[1]])),h=Li(u,Mi(c,l)),p=bi(t,h);o=1===p.shape[0]?Ka(i):ii([i,vo(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=so(bi(il(c,h),l)),f=vo(r,[e,0],[n-e,s]),m=Mi(d,o),g=Wo(o);if(0===e)r=Li(f,il(m,il(g,f)));else{const t=Li(f,il(m,il(g,f)));r=ii([vo(r,[0,0],[e,s]),t],0)}const y=Wo(m),b=vo(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=Li(b,il(il(b,o),y));else{const t=Li(b,il(il(b,o),y));a=ii([vo(a,[0,0],[n,e]),t],1)}return[o,r,a]})),Sr([t,l,u])}return!t&&n>s&&(a=vo(a,[0,0],[n,s]),r=vo(r,[0,0],[s,s])),[a,r]}))}const zl=la({qr_:function(e,t=!1){if(E(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return Ll(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),s=Lo(Zr(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],r=[];return s.forEach((e=>{const[n,s]=Ll(e,t);a.push(n),r.push(s)})),[Zr(Fo(a,0),e.shape),Zr(Fo(r,0),e.shape)]}}});var Bl;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(Bl||(Bl={}));const Pl=la({computeWeightedLoss_:function(e,t,n=Bl.SUM_BY_NONZERO_WEIGHTS){const s=ia(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=ia(t,"weights","computeWeightedLoss"));const r=null==a?s:Mi(s,a);if(n===Bl.NONE)return r;if(n===Bl.SUM)return zi(r);if(n===Bl.MEAN){if(null==a)return Gi(r);{const e=s.size/a.size,t=bi(zi(r),zi(a));return e>1?bi(t,Fr(e)):t}}if(n===Bl.SUM_BY_NONZERO_WEIGHTS){if(null==a)return bi(zi(r),Fr(s.size));{const e=Mi(a,oo(s.shape)),t=ja(zi(ao(e,Fr(0))),"float32");return bi(zi(r),t)}}throw Error(`Unknown reduction: ${n}`)}});la({absoluteDifference_:function(e,t,n,s=Bl.SUM_BY_NONZERO_WEIGHTS){const a=ia(e,"labels","absoluteDifference"),r=ia(t,"predictions","absoluteDifference");let i=null;null!=n&&(i=ia(n,"weights","absoluteDifference")),A(a.shape,r.shape,"Error in absoluteDifference: ");const o=_r(Li(a,r));return Pl(o,i,s)}}),la({cosineDistance_:function(e,t,n,s,a=Bl.SUM_BY_NONZERO_WEIGHTS){const r=ia(e,"labels","cosineDistance"),i=ia(t,"predictions","cosineDistance");let o=null;null!=s&&(o=ia(s,"weights","cosineDistance")),A(r.shape,i.shape,"Error in cosineDistance: ");const l=Fr(1),u=Li(l,zi(Mi(r,i),n,!0));return Pl(u,o,a)}}),la({hingeLoss_:function(e,t,n,s=Bl.SUM_BY_NONZERO_WEIGHTS){let a=ia(e,"labels","hingeLoss");const r=ia(t,"predictions","hingeLoss");let i=null;null!=n&&(i=ia(n,"weights","hingeLoss")),A(a.shape,r.shape,"Error in hingeLoss: ");const o=Fr(1);a=Li(Mi(Fr(2),a),o);const l=yo(Li(o,Mi(a,r)));return Pl(l,i,s)}}),la({huberLoss_:function(e,t,n,s=1,a=Bl.SUM_BY_NONZERO_WEIGHTS){const r=ia(e,"labels","huberLoss"),i=ia(t,"predictions","huberLoss");let o=null;null!=n&&(o=ia(n,"weights","huberLoss")),A(r.shape,i.shape,"Error in huberLoss: ");const l=Fr(s),u=_r(Li(i,r)),c=ji(u,l),h=Li(u,c),p=Or(Mi(Fr(.5),to(c)),Mi(l,h));return Pl(p,o,a)}}),la({logLoss_:function(e,t,n,s=1e-7,a=Bl.SUM_BY_NONZERO_WEIGHTS){const r=ia(e,"labels","logLoss"),i=ia(t,"predictions","logLoss");let o=null;null!=n&&(o=ia(n,"weights","logLoss")),A(r.shape,i.shape,"Error in logLoss: ");const l=Fr(1),u=Fr(s),c=so(Mi(r,Di(Or(i,u)))),h=Mi(Li(l,r),Di(Or(Li(l,i),u))),p=Li(c,h);return Pl(p,o,a)}});const Wl=la({squaredDifference_:function(e,t){let n=ia(e,"a","squaredDifference"),s=ia(t,"b","squaredDifference");[n,s]=Gs(n,s),vi(n.shape,s.shape);const a={a:n,b:s};return Zs.runKernel(Wn,a,{})}});la({meanSquaredError_:function(e,t,n,s=Bl.SUM_BY_NONZERO_WEIGHTS){const a=ia(e,"labels","meanSquaredError"),r=ia(t,"predictions","meanSquaredError");let i=null;null!=n&&(i=ia(n,"weights","meanSquaredError")),A(a.shape,r.shape,"Error in meanSquaredError: ");const o=Wl(a,r);return Pl(o,i,s)}});const Vl=la({log1p_:function(e){const t={x:ia(e,"x","log1p")};return Zs.runKernel(Ot,t)}});la({sigmoidCrossEntropy_:function(e,t,n,s=0,a=Bl.SUM_BY_NONZERO_WEIGHTS){let r=ia(e,"multiClassLabels","sigmoidCrossEntropy");const i=ia(t,"logits","sigmoidCrossEntropy");let o=null;if(null!=n&&(o=ia(n,"weights","sigmoidCrossEntropy")),A(r.shape,i.shape,"Error in sigmoidCrossEntropy: "),s>0){const e=Fr(s),t=Fr(1),n=Fr(.5);r=Or(Mi(r,Li(t,e)),Mi(n,e))}const l=function(e,t){const n=ia(e,"labels","sigmoidCrossEntropyWithLogits"),s=ia(t,"logits","sigmoidCrossEntropyWithLogits");A(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=yo(s),r=Mi(s,n),i=Vl(_i(so(_r(s))));return Or(Li(a,r),i)}(r,i);return Pl(l,o,a)}});const Ul=la({logSumExp_:function(e,t=null,n=!1){const s=ia(e,"x","logSumExp"),a=P(t,s.shape),r=Oi(s,a,!0),i=Li(s,r),o=_i(i),l=zi(o,a),u=Di(l),c=Or(Zr(r,u.shape),u);if(n){const e=Yi(c.shape,a);return Zr(c,e)}return c}});la({softmaxCrossEntropy_:function(e,t,n,s=0,a=Bl.SUM_BY_NONZERO_WEIGHTS){let r=ia(e,"onehotLabels","softmaxCrossEntropy");const i=ia(t,"logits","softmaxCrossEntropy");let o=null;if(null!=n&&(o=ia(n,"weights","softmaxCrossEntropy")),A(r.shape,i.shape,"Error in softmaxCrossEntropy: "),s>0){const e=Fr(s),t=Fr(1),n=Fr(r.shape[1]);r=Or(Mi(r,Li(t,e)),bi(e,n))}const l=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return Rr(((e,t,s)=>{const a=Ul(t,[n],!0),r=Li(ja(t,"float32"),a);s([e,r]);const i=so(Mi(r,e));return{value:zi(i,[n]),gradFunc:(e,t)=>{const[s,a]=t,r=Yi(e.shape,[n]);return[Mi(Zr(e,r),Li(ja(s,"float32"),_i(a))),Mi(Zr(e,r),Li(_i(a),ja(s,"float32")))]}}}))(e,t)}(r,i);return Pl(l,o,a)}});const Gl={flipLeftRight:pl,resizeNearestNeighbor:Tl,resizeBilinear:Sl,rotateWithOffset:dl,cropAndResize:hl,nonMaxSuppression:ml,nonMaxSuppressionAsync:async function(e,t,n,s=.5,a=Number.NEGATIVE_INFINITY){const r=ia(e,"boxes","nonMaxSuppressionAsync"),i=ia(t,"scores","nonMaxSuppressionAsync"),o=fl(r,i,n,s,a);n=o.maxOutputSize,s=o.iouThreshold,a=o.scoreThreshold;const l=await Promise.all([r.data(),i.data()]),u=l[0],c=l[1],{selectedIndices:h}=bl(u,c,n,s,a);return r!==e&&r.dispose(),i!==t&&i.dispose(),_o(h,"int32")},nonMaxSuppressionWithScore:$l,nonMaxSuppressionWithScoreAsync:async function(e,t,n,s=.5,a=Number.NEGATIVE_INFINITY,r=0){const i=ia(e,"boxes","nonMaxSuppressionAsync"),o=ia(t,"scores","nonMaxSuppressionAsync"),l=fl(i,o,n,s,a,r);n=l.maxOutputSize,s=l.iouThreshold,a=l.scoreThreshold,r=l.softNmsSigma;const u=await Promise.all([i.data(),o.data()]),c=u[0],h=u[1],{selectedIndices:p,selectedScores:d}=wl(c,h,n,s,a,r);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:_o(p,"int32"),selectedScores:_o(d)}},nonMaxSuppressionPadded:Cl,nonMaxSuppressionPaddedAsync:async function(e,t,n,s=.5,a=Number.NEGATIVE_INFINITY,r=!1){const i=ia(e,"boxes","nonMaxSuppressionAsync"),o=ia(t,"scores","nonMaxSuppressionAsync"),l=fl(i,o,n,s,a,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[p,d]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=xl(p,d,u,c,h,r);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:_o(f,"int32"),validOutputs:Fr(m,"int32")}},transform:El},Hl={bandPart:Fl,gramSchmidt:Ml,qr:zl};class jl extends Dr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=Zs.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Zs.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Cr((()=>Po(s).variable(!1)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Cr((()=>Po(s).variable(!1)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const r=this.accumulatedGrads[n].variable,i=this.accumulatedUpdates[n].variable;Cr((()=>{const e=Or(Mi(r,this.rho),Mi(to(a),1-this.rho)),t=Mi(bi(Ao(Or(i,this.epsilon)),Ao(Or(r,this.epsilon))),a),n=Or(Mi(i,this.rho),Mi(to(t),1-this.rho));r.assign(e),i.assign(n);const o=Or(Mi(t,-this.learningRate),s);s.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Sr(this.accumulatedGrads.map((e=>e.variable))),Sr(this.accumulatedUpdates.map((e=>e.variable))))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}jl.className="Adadelta",Nr(jl);class Kl extends Dr{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Zs.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Cr((()=>Si(s.shape,this.initialAccumulatorValue).variable(e)))}}const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const r=this.accumulatedGrads[n].variable;Cr((()=>{const e=Or(r,to(a));r.assign(e);const t=Or(Mi(bi(a,Ao(Or(e,Zs.backend.epsilon()))),-this.learningRate),s);s.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Sr(this.accumulatedGrads.map((e=>e.variable)))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}Kl.className="Adagrad",Nr(Kl);class ql extends Dr{constructor(e,t,n,s=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Cr((()=>{this.accBeta1=Fr(t).variable(),this.accBeta2=Fr(n).variable()})),null==s&&(this.epsilon=Zs.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Cr((()=>{const n=Li(1,this.accBeta1),s=Li(1,this.accBeta2);t.forEach(((t,a)=>{const r=Zs.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Cr((()=>Po(r).variable(!1)))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:Cr((()=>Po(r).variable(!1)))});const i=Array.isArray(e)?e[a].tensor:e[t];if(null==i)return;const o=this.accumulatedFirstMoment[a].variable,l=this.accumulatedSecondMoment[a].variable,u=Or(Mi(o,this.beta1),Mi(i,1-this.beta1)),c=Or(Mi(l,this.beta2),Mi(to(i),1-this.beta2)),h=bi(u,n),p=bi(c,s);o.assign(u),l.assign(c);const d=Or(Mi(bi(h,Or(Ao(p),this.epsilon)),-this.learningRate),r);r.assign(d)})),this.accBeta1.assign(Mi(this.accBeta1,this.beta1)),this.accBeta2.assign(Mi(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Sr(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&Sr(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),Cr((()=>{this.accBeta1.assign(Dl(this.beta1,this.iterations_+1)),this.accBeta2.assign(Dl(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}ql.className="Adam",Nr(ql);class Xl extends Dr{constructor(e,t,n,s=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Cr((()=>{this.iteration=Fr(0).variable(),this.accBeta1=Fr(t).variable()})),null==s&&(this.epsilon=Zs.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Cr((()=>{const n=Li(1,this.accBeta1),s=bi(-this.learningRate,Or(Mi(this.iteration,this.decay),1));t.forEach(((t,a)=>{const r=Zs.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Po(r).variable(!1)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:Po(r).variable(!1)});const i=Array.isArray(e)?e[a].tensor:e[t];if(null==i)return;const o=this.accumulatedFirstMoment[a].variable,l=this.accumulatedWeightedInfNorm[a].variable,u=Or(Mi(o,this.beta1),Mi(i,1-this.beta1)),c=Mi(l,this.beta2),h=_r(i),p=Ui(c,h);o.assign(u),l.assign(p);const d=Or(Mi(bi(s,n),bi(u,Or(p,this.epsilon))),r);r.assign(d)})),this.iteration.assign(Or(this.iteration,1)),this.accBeta1.assign(Mi(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Sr(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&Sr(this.accumulatedWeightedInfNorm.map((e=>e.variable)))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}Xl.className="Adamax",Nr(Xl);class Yl extends Dr{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const a=Zs.registeredVariables[t];Cr((()=>{const e=Or(Mi(this.c,s),a);a.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Tr(Fr(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}Yl.className="SGD",Nr(Yl);class Jl extends Yl{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Fr(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Zs.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Cr((()=>Po(s).variable(e)))}}const a=this.accumulations[n].variable,r=Array.isArray(e)?e[n].tensor:e[t];null!=r&&Cr((()=>{let e;const t=Or(Mi(this.m,a),r);e=this.useNesterov?Or(Mi(this.c,Or(r,Mi(t,this.m))),s):Or(Mi(this.c,t),s),a.assign(t),s.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Sr(this.accumulations.map((e=>e.variable)))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}Jl.className="Momentum",Nr(Jl);class Zl extends Dr{constructor(e,t=.9,n=0,s=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,null==s&&(this.epsilon=Zs.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Zs.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Cr((()=>Po(s).variable(a)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Cr((()=>Po(s).variable(a)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Cr((()=>Po(s).variable(a)))});const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;Cr((()=>{const e=Or(Mi(i,this.decay),Mi(to(r),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=Or(Mi(t,this.decay),Mi(r,1-this.decay)),l=bi(Mi(r,this.learningRate),Ao(Li(e,Or(to(a),this.epsilon)))),u=Or(Mi(o,this.momentum),l);i.assign(e),t.assign(a),o.assign(u);const c=Li(s,u);s.assign(c)}else{const e=Or(Mi(i,this.decay),Mi(to(r),1-this.decay)),t=Or(Mi(o,this.momentum),bi(Mi(r,this.learningRate),Ao(Or(e,this.epsilon))));i.assign(e),o.assign(t);const n=Li(s,t);s.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Sr(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&Sr(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&Sr(this.accumulatedMoments.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedMoments=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}Zl.className="RMSProp",Nr(Zl);class Ql{static sgd(e){return new Yl(e)}static momentum(e,t,n=!1){return new Jl(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,a=!1){return new Zl(e,t,n,s,a)}static adam(e=.001,t=.9,n=.999,s=null){return new ql(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new jl(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,a=0){return new Xl(e,t,n,s,a)}static adagrad(e,t=.1){return new Kl(e,t)}}const eu={sgd:Ql.sgd,momentum:Ql.momentum,adadelta:Ql.adadelta,adagrad:Ql.adagrad,rmsprop:Ql.rmsprop,adamax:Ql.adamax,adam:Ql.adam},tu="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function nu(){return new Promise((e=>tu((()=>e()))))}function su(e,t){const n=e[0].length;e.forEach(((e,t)=>{E(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),E(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const s=e[0];e.forEach(((e,a)=>{for(let r=0;r`Error in concat${n}D: Shape of tensors[${a}] (${e}) does not match the shape of the rest (${s}) along the non-concatenated axis ${a}.`))}))}function au(e,t){const n=e[0].slice();for(let s=1;s=2*t+1||s%2==1?a.push(s):n.push(s);s.push(...n),s.push(0),s.push(...a)}return s}function cu(e,t,n,s=!0){const a=[];s?a.push(e[0]/n):a.push(e[0]*n);for(let n=1;nn)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(0===D(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const a=t.shape,r=a[a.length-1];let i=1;for(let e=0;ee/u)),1].slice(0,r);return[l,i,u,c]}function fu(e,t,n){const s=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,r=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${a}.`;if(n.rank1?t.shape[s-1]:1,r=n.length;let i=1;for(let e=a;e"Number of splits must evenly divide the axis.")),s=new Array(t).fill(e.shape[n]/t);else{E(t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0)<=1,(()=>"There should be only one negative value in split array."));const a=t.indexOf(-1);if(-1!==a){const s=t.reduce(((e,t)=>t>0?e+t:e));t[a]=e.shape[n]-s}E(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),s=t}return s}function Mu(e,t){let n,s=!1;for(e<=ru?(n=e,s=!0):n=J(e,Math.floor(Math.sqrt(e)));!s;)n>t||n===e?s=!0:n=J(e,n+1);return n}function Lu(e,t,n){const s=[],a=e.length;for(let r=0;ra))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${s}`);if(s<0&&(s+=a),s>r)throw new Error(`batchDims (${s}) must be less than rank(x) (\n ${r}).`);if(nws(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Pu(e){return e.map((e=>xs(e)))}function Wu(e,t){const n=[];for(let e=0;e{const[n]=t;return{x:()=>Mi(e,Jo(ja(n,"float32"),-1))}}},Uu={kernelName:me,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=to(ja(n,"float32")),s=Ao(Li(Fr(1),t));return so(bi(e,s))}}}},Gu={kernelName:ge,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ao(Li(to(ja(n,"float32")),1));return bi(e,t)}}}},Hu={kernelName:ye,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,a=vi(n.shape,s.shape);return{a:()=>{let t=e;const s=ki(n.shape,a);return s.length>0&&(t=zi(t,s)),Zr(t,n.shape)},b:()=>{let t=e;const n=ki(s.shape,a);return n.length>0&&(t=zi(t,n)),Zr(t,s.shape)}}}},ju={kernelName:be,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,s)=>{n[s]=()=>e.clone()})),n}},Ku={kernelName:ke,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Po(n)}}},qu={kernelName:ve,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Po(n)}}},Xu={kernelName:Ne,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>bi(e,Ao(Li(Fr(1),to(ja(n,"float32")))))}}},Yu={kernelName:Ie,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ao(Or(Fr(1),to(ja(n,"float32"))));return bi(e,t)}}}},Ju={kernelName:Se,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,a=vi(n.shape,s.shape);return{a:()=>{const t=Or(to(n),to(s));let r=Mi(e,bi(s,t));const i=ki(n.shape,a);return i.length>0&&(r=zi(r,i)),Zr(r,n.shape)},b:()=>{const t=Or(to(n),to(s));let r=so(Mi(e,bi(n,t)));const i=ki(s.shape,a);return i.length>0&&(r=zi(r,i)),Zr(r,s.shape)}}}},Zu={kernelName:$e,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>bi(e,Or(to(ja(n,"float32")),1))}}},Qu={kernelName:Ce,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>bi(e,Li(Fr(1),to(ja(n,"float32"))))}}},ec=la({avgPool3dGrad_:function(e,t,n,s,a,r){const i=ia(e,"dy","avgPool3dGrad"),o=ia(t,"input","avgPool3dGrad");let l=i,u=o,c=!1;4===o.rank&&(c=!0,l=Zr(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=Zr(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),E(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),E(5===u.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`)),null!=r&&E(O(a),(()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`));const h={dy:l,input:u},p={filterSize:n,strides:s,pad:a,dimRoundingMode:r},d=Zs.runKernel(Re,h,p);return c?Zr(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),tc={kernelName:Ae,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:a,strides:r,pad:i,dimRoundingMode:o}=n;return{x:()=>ec(e,s,a,r,i,o)}}},nc=la({avgPoolGrad_:function(e,t,n,s,a){const r=ia(e,"dy","avgPoolGrad"),i=ia(t,"input","avgPoolGrad");E(i.rank===r.rank,(()=>`Rank of input (${i.rank}) does not match rank of dy (${r.rank})`));let o=i,l=r,u=!1;3===i.rank&&(u=!0,o=Zr(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=Zr(r,[1,r.shape[0],r.shape[1],r.shape[2]])),E(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),E(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const c={dy:l,input:o},h={filterSize:n,strides:s,pad:a},p=Zs.runKernel(Ee,c,h);return u?Zr(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),sc={kernelName:Te,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:a,strides:r,pad:i}=n;return{x:()=>nc(e,s,a,r,i)}}},ac={kernelName:Fe,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,a]=t,{transposeA:r,transposeB:i}=n;return r||i?!r&&i?{a:()=>il(e,a,!1,!1),b:()=>il(e,s,!0,!1)}:r&&!i?{a:()=>il(a,e,!1,!0),b:()=>il(s,e,!1,!1)}:{a:()=>il(a,e,!0,!0),b:()=>il(e,s,!0,!0)}:{a:()=>il(e,a,!1,!0),b:()=>il(s,e,!0,!1)}}},rc=la({spaceToBatchND_:function(e,t,n){const s=ia(e,"x","spaceToBatchND");E(s.rank>=1+t.length,(()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`)),E(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),E(s.shape.reduce(((e,s,a)=>a>0&&a<=t.length?e&&(s+n[a-1][0]+n[a-1][1])%t[a-1]==0:e),!0),(()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const a={x:s},r={blockShape:t,paddings:n};return Zs.runKernel(zn,a,r)}}),ic={kernelName:De,gradFunc:(e,t,n)=>{const{blockShape:s,crops:a}=n;return{x:()=>rc(e,s,a)}}},oc={kernelName:"BroadcastTo",gradFunc:(e,t,n)=>{const s=n,a=s.inputShape,r=s.shape,i=Array.from(r);for(let e=a.length-1;e>=0;e--)if(a[e]===r[e])i[e]=1;else if(1!==a[e])throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${r}].`);const o=[];for(let e=0;e1&&o.push(e);return{x:()=>zi(e,o,!0)}}},lc={kernelName:Oe,gradFunc:e=>({x:()=>e.clone()})},uc={kernelName:Me,gradFunc:e=>({x:()=>Po(e)})},cc={kernelName:Le,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:a,clipValueMax:r}=n;return{x:()=>Bo(Pi(Ri(s,a),Al(s,r)),e,Po(e))}}},hc={kernelName:Be,inputsToSave:["x"],gradFunc:Vu.gradFunc},pc={kernelName:Pe,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map((e=>e.shape)),{axis:a}=n,r=P(a,t[0].shape)[0],i=s.map((e=>e[r]));return Eo(e,i,r).map((e=>()=>e))}},dc={kernelName:We,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,a]=t,{dilations:r,strides:i,pad:o,dataFormat:l}=n;return E(Xr(r),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`)),{x:()=>di(s.shape,e,a,i,o,l),filter:()=>Xo(s,e,a.shape,i,o,l)}}},fc={kernelName:Ue,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,a]=t,{strides:r,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>hi(e,a,r,i,o,1,l),filter:()=>Xo(e,s,a.shape,r,i,o,l)}}},mc=la({conv3DBackpropFilter_:function(e,t,n,s,a){let r=e;4===e.rank&&(r=Zr(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=Zr(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),E(5===r.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${r.shape}.`)),E(5===i.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`)),E(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),E(r.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${r.shape[4]}) must match input depth in filter (${n[3]}.`)),E(i.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:r,dy:i},l={strides:s,pad:a,filterShape:n};return Zs.runKernel(He,o,l)}}),gc=la({conv3DBackpropInput_:function(e,t,n,s,a){E(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let r=e,i=t,o=!1;4===t.rank&&(o=!0,i=Zr(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),r=[1,e[0],e[1],e[2],e[3]]);const l=r[4],u=i.shape[4];E(5===r.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${r.length}.`)),E(5===i.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`)),E(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),E(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),E(u===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`));const c={dy:i,filter:n},h={pad:a,strides:s,inputShape:r},p=Zs.runKernel(je,c,h);return o?Zr(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),yc={kernelName:Ge,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:a,pad:r}=n;E(Xr(s),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const[i,o]=t;return{x:()=>gc(i.shape,e,o,a,r),filter:()=>mc(i,e,o.shape,a,r)}}},bc=la({sin_:function(e){const t={x:ia(e,"x","sin")};return Zs.runKernel(Rn,t)}}),xc={kernelName:Ke,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(so(bc(ja(n,"float32"))),e)}}},wc=la({sinh_:function(e){const t={x:ia(e,"x","sinh")};return Zs.runKernel(Fn,t)}}),kc={kernelName:qe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(wc(ja(n,"float32")),e)}}},vc=la({cumsum_:function(e,t=0,n=!1,s=!1){const a={x:ia(e,"x","cumsum")},r={axis:t,exclusive:n,reverse:s};return Zs.runKernel(Xe,a,r)}}),Nc={kernelName:Xe,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:a,exclusive:r,reverse:i}=n;return{x:()=>{const t=Zi([a],s.rank);let n=vc(e,a,r,!i);return null!=t&&(n=Wo(n,t)),n}}}},Ic={kernelName:Qe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:a,pad:r,dimRoundingMode:i}=n,o=null==s?[1,1]:s;E(Xr(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,u]=t;return E(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),E(4===u.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`)),E(l.shape[3]===u.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`)),E(Yr(a,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`)),null!=i&&E(O(r),(()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`)),{x:()=>al(l.shape,e,u,a,r,s,i),filter:()=>sl(l,e,u.shape,a,r,s,i)}}},$c={kernelName:st,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,a]=t,r={x:s,filter:a,dy:e},i={x:s,filter:a,dy:e};return{x:()=>Zs.runKernel(at,r,n),filter:()=>Zs.runKernel(rt,i,n)}}},Cc={kernelName:ot,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s={dy:e,y:n};return{x:()=>Zs.runKernel(lt,s)}}},Sc={kernelName:ut,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=Mi(_i(so(to(n))),2/Math.sqrt(Math.PI));return{x:()=>Mi(e,s)}}},Tc={kernelName:ht,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(e,n)}}},Ec={kernelName:pt,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>Zr(e,n.shape)}}},Ac={kernelName:dt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(e,_i(n))}}},Rc={kernelName:yt,gradFunc:e=>({x:()=>Po(e)})},Fc={kernelName:bt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,a=vi(n.shape,s.shape);return{a:()=>{const t=bi(e,ja(s,"float32")),r=ki(n.shape,a);return r.length>0?Zr(zi(t,r),n.shape):t},b:()=>{let t=Mi(e,ja(n,"float32"));const r=ki(s.shape,a);r.length>0&&(t=Zr(zi(t,r),s.shape));const i=to(s);return so(bi(t,ja(i,"float32")))}}}},Dc=la({rsqrt_:function(e){const t={x:ia(e,"x","rsqrt")};return Zs.runKernel(Cn,t)}}),_c={kernelName:xt,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[a,r,i,o]=t,l=null==o?Fr(1):o,u=ki(r.shape,a.shape),c=[];if(1===r.rank){for(let e=0;e1===r.rank?Zr(Mi(Mi(e,$i(Zr(d,[1,1,1,r.shape[0]]),c)),l),a.shape):Zr(Mi(Mi(e,d),l),a.shape),mean:()=>{let e=Mi(Mi(d,Fr(-1)),p);return 1===r.rank&&(e=zi(e,u)),Zr(e,r.shape)},variance:()=>{let e=Mi(Mi(f,h),p);return 1===r.rank&&(e=zi(e,u)),Zr(e,r.shape)},scale:()=>{const t=Mi(h,d);let n=Mi(e,t);return 1===r.rank&&(n=zi(n,u)),Zr(n,r.shape)},offset:()=>{let t=e;return 1===r.rank&&(t=zi(t,u)),Zr(t,r.shape)}}}},Oc=la({unsortedSegmentSum_:function(e,t,n){const s=ia(e,"x","unsortedSegmentSum"),a=ia(t,"segmentIds","unsortedSegmentSum","int32");E(O(n),(()=>"numSegments must be of dtype int"));const r={x:s,segmentIds:a},i={numSegments:n};return Zs.runKernel(es,r,i)}}),Mc={kernelName:wt,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,a]=t,{axis:r}=n,i=P(r,s.shape)[0];return{x:()=>{const t=s.shape,n=a.size,o=t.slice(0,i),l=o.length,u=t.slice(r,t.length).slice(1),c=u.length,h=Lc(0,l),p=Lc(l+1,l+1+c),d=zc([o,[n],u]),f=Zr(e,d),m=Zr(a,[n]),g=zc([[l],h,p]),y=Wo(f,g);let b=Oc(y,m,s.shape[i]);const x=Qi(g);return b=Wo(b,x),b},indices:()=>a}}};function Lc(e,t){const n=[];for(let s=e;s{const[n,s]=t;return{a:()=>Po(n),b:()=>Po(s)}}},Pc={kernelName:It,gradFunc:e=>({x:()=>ja(e,"float32")})},Wc={kernelName:St,gradFunc:e=>({x:()=>Po(e)})},Vc={kernelName:Tt,gradFunc:e=>({x:()=>Po(e)})},Uc={kernelName:Et,gradFunc:e=>({x:()=>Po(e)})},Gc={kernelName:At,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{alpha:a}=n,r=Ai(s,0);return{x:()=>Bo(r,e,Mi(e,a))}}},Hc={kernelName:Ot,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>bi(e,Or(n,1))}}},jc={kernelName:_t,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>bi(e,ja(n,"float32"))}}},Kc={kernelName:"LogSoftmax",inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:a}=n;return{logits:()=>{const t=_i(s);return Li(e,Mi(zi(e,a,!0),t))}}}},qc=la({localResponseNormalizationBackprop_:function(e,t,n,s=5,a=1,r=1,i=.5){const o={x:e,y:t,dy:n},l={depthRadius:s,bias:a,alpha:r,beta:i};return Zs.runKernel(Pt,o,l)}}),Xc={kernelName:Bt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,a]=t,{depthRadius:r,bias:i,alpha:o,beta:l}=n;return{x:()=>qc(s,a,e,r,i,o,l)}}};function Yc(e,t,n,s){return t.rankMi(e,ja(Ni(n,t),e.dtype))}}const Jc={kernelName:Wt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:a}=s,r=t[0],i=Yc(e,t[1],r,P(a,r.shape));return{x:()=>i.x()}}},Zc=la({less_:function(e,t){let n=ia(e,"a","less"),s=ia(t,"b","less");[n,s]=Gs(n,s),vi(n.shape,s.shape);const a={a:n,b:s};return Zs.runKernel(Rt,a)}}),Qc={kernelName:Vt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Mi(e,ja(Ri(n,s),"float32")),b:()=>Mi(e,ja(Zc(n,s),"float32"))}}},eh=la({maxPool3dGrad_:function(e,t,n,s,a,r,i){const o=ia(e,"dy","maxPool3dGrad"),l=ia(t,"input","maxPool3dGrad"),u=ia(n,"output","maxPool3dGrad");let c=o,h=l,p=u,d=!1;4===l.rank&&(d=!0,c=Zr(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=Zr(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=Zr(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),E(5===c.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`)),E(5===h.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`)),E(5===p.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`)),null!=i&&E(O(r),(()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`));const f={dy:c,input:h,output:p},m={filterSize:s,strides:a,pad:r,dimRoundingMode:i},g=Zs.runKernel(jt,f,m);return d?Zr(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),th={kernelName:Ht,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,a]=t,{filterSize:r,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>eh(e,s,a,r,i,o,l)}}},nh=la({maxPoolGrad_:function(e,t,n,s,a,r,i){const o=ia(e,"dy","maxPoolGrad"),l=ia(t,"input","maxPoolGrad"),u=ia(n,"output","maxPoolGrad");E(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),E(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),E(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),null!=i&&E(O(r),(()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`));const c={dy:o,input:l,output:u},h={filterSize:s,strides:a,pad:r,dimRoundingMode:i};return Zs.runKernel(Gt,c,h)}}),sh={kernelName:Ut,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,a]=t,{filterSize:r,strides:i,pad:o}=n;return{x:()=>nh(e,s,a,r,i,o)}}},ah={kernelName:qt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:a}=n,r=P(a,s.shape),i=D(Xi(s.shape,r)[1]);return{x:()=>{const t=s.shape.slice();r.forEach((e=>{t[e]=1}));const n=Zr(e,t);return bi(Mi(n,oo(s.shape,"float32")),i)}}}},rh={kernelName:Xt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:a}=s,[r,i]=t,o=Yc(e,i,r,P(a,r.shape));return{x:()=>o.x()}}},ih={kernelName:Yt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Mi(e,ja(Al(n,s),"float32")),b:()=>Mi(e,ja(Ai(n,s),"float32"))}}},oh={kernelName:Jt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:a}=n,r=a.map((e=>e[0]));return{x:()=>vo(e,r,s.shape)}}},lh={kernelName:Zt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,a=vi(n.shape,s.shape);return{a:()=>{const t=ki(n.shape,a);return t.length>0?Zr(zi(e,t),n.shape):e},b:()=>{const t=Mi(e,so(Ti(bi(n,s)))),r=ki(s.shape,a);return r.length>0?Zr(zi(t,r),s.shape):t}}}},uh={kernelName:en,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,a=vi(n.shape,s.shape);return{a:()=>{const t=Mi(e,ja(s,"float32")),r=ki(n.shape,a);return r.length>0?Zr(zi(t,r),n.shape):t},b:()=>{const t=Mi(e,ja(n,"float32")),r=ki(s.shape,a);return r.length>0?Zr(zi(t,r),s.shape):t}}}},ch={kernelName:tn,gradFunc:e=>({x:()=>so(e)})},hh={kernelName:ln,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>io(n.shape,"float32")}}},ph={kernelName:on,gradFunc:e=>({x:()=>Po(e)})},dh={kernelName:un,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:s}=n;return Lo(e,s).map((e=>()=>e))}},fh={kernelName:cn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:a}=n,r=a.map((e=>e[0]));return{x:()=>vo(e,r,s.shape)}}},mh={kernelName:hn,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,a]=t,r=n,i=s,o=vi(r.shape,i.shape);return{a:()=>{const t=ja(i,"float32");let n=Mi(e,Mi(t,Dl(r,Li(t,Fr(1)))));const s=ki(r.shape,o);return s.length>0&&(n=zi(n,s)),Zr(n,r.shape)},b:()=>{const t=Ai(r,0),n=Bo(t,Di(r),Po(r));let s=Mi(e,Mi(a,n));const l=ki(i.shape,o);return l.length>0&&(s=zi(s,l)),Zr(s,i.shape)}}}},gh={kernelName:pn,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,a=Ai(n,0);return{x:()=>Bo(a,e,Mi(e,s)),alpha:()=>{let t=Bo(a,Po(e),Mi(e,n));const r=ki(s.shape,e.shape);return r.length>0&&(t=zi(t,r)),Zr(t,s.shape)}}}},yh={kernelName:it,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,a=vi(n.shape,s.shape);return{a:()=>{const t=bi(e,ja(s,"float32")),r=ki(n.shape,a);return r.length>0?Zr(zi(t,r),n.shape):t},b:()=>{let t=Mi(e,ja(n,"float32"));const r=ki(s.shape,a);r.length>0&&(t=Zr(zi(t,r),s.shape));const i=to(s);return so(bi(t,ja(i,"float32")))}}}},bh={kernelName:gn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>bi(e,so(to(n)))}}},xh={kernelName:Nn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=Mi(Al(n,6),Jo(n));return{x:()=>Mi(e,ja(s,"float32"))}}},wh={kernelName:yn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(e,ja(Jo(n),"float32"))}}},kh={kernelName:bn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Zr(e,n.shape)}}},vh={kernelName:kn,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,a={dy:e,images:s};return{images:()=>Zs.runKernel(vn,a,n)}}},Nh={kernelName:xn,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,a={dy:e,images:s};return{images:()=>Zs.runKernel(wn,a,n)}}},Ih={kernelName:In,gradFunc:(e,t,n)=>{const{dims:s}=n,a=P(s,e.shape);return{x:()=>bo(e,a)}}},$h={kernelName:$n,gradFunc:e=>({x:()=>Po(e)})},Ch={kernelName:Cn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>so(bi(e,Mi(Dl(n,1.5),2)))}}},Sh=la({logicalNot_:function(e){const t={x:ia(e,"x","logicalNot","bool")};return Zs.runKernel(Lt,t)}}),Th={kernelName:Tn,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>ja(Po(n),"float32"),t:()=>Mi(e,ja(n,e.dtype)),e:()=>Mi(e,ja(Sh(n),e.dtype))}}},Eh={kernelName:En,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ai(n,Fr(0)),s=Fr(yu),a=Fr(bu),r=Mi(e,a),i=Mi(Mi(e,s),_i(ja(n,"float32")));return Bo(t,r,i)}}}},Ah={kernelName:_n,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(e,Mi(n,Li(Fr(1),n)))}}},Rh={kernelName:Dn,gradFunc:e=>({x:()=>Po(e)})},Fh=la({cos_:function(e){const t={x:ia(e,"x","cos")};return Zs.runKernel(Ke,t)}}),Dh={kernelName:Rn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(Fh(ja(n,"float32")),e)}}},_h=la({cosh_:function(e){const t={x:ia(e,"x","cosh")};return Zs.runKernel(qe,t)}}),Oh={kernelName:Fn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(_h(ja(n,"float32")),e)}}},Mh={kernelName:An,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:a,size:r}=n,i=s.shape,[o,l]=xr(s,a,r),u=[];for(let t=0;tuo(e,u)}}},Lh={kernelName:Pn,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:a}=n,r=Mi(e,s);return{logits:()=>Li(r,Mi(zi(r,[a],!0),s))}}},zh={kernelName:On,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(e,ko(n))}}},Bh=la({batchToSpaceND_:function(e,t,n){const s=ia(e,"x","batchToSpaceND"),a=t.reduce(((e,t)=>e*t));E(s.rank>=1+t.length,(()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`)),E(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),E(s.shape[0]%a==0,(()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`));const r={x:s},i={blockShape:t,crops:n};return Zs.runKernel(De,r,i)}}),Ph={kernelName:zn,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:a}=n;return{x:()=>Bh(e,s,a)}}},Wh={kernelName:Bn,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>ii(e,s)}}},Vh=[Vu,Uu,Gu,Hu,ju,Ku,qu,Xu,Yu,Ju,Zu,Qu,tc,sc,ac,ic,oc,lc,uc,cc,hc,pc,fc,dc,yc,xc,kc,Nc,Ic,$c,yh,Cc,Sc,Tc,Ec,Ac,Fc,Rc,_c,Mc,Bc,Pc,Wc,Vc,Uc,Gc,Hc,jc,Kc,Xc,Jc,Jc,Qc,th,sh,ah,rh,ih,oh,lh,uh,ch,hh,ph,dh,fh,fh,mh,gh,bh,xh,wh,kh,vh,Nh,Ih,$h,Ch,Th,Eh,Ah,Rh,Dh,Oh,Mh,Lh,zh,Ph,Ph,Wh,Wh,{kernelName:Mn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>bi(e,Mi(Ao(ja(n,"float32")),2))}}},{kernelName:Wn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,a=Fr(2);return{a:()=>Mi(e,Mi(a,Li(n,s))),b:()=>Mi(e,Mi(a,Li(s,n)))}}},{kernelName:Vn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(e,Mi(ja(n,"float32"),2))}}},{kernelName:ns,gradFunc:e=>({x:()=>Po(e)})},{kernelName:Un,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,a=vi(n.shape,s.shape);return{a:()=>{let t=e;const s=ki(n.shape,a);return s.length>0&&(t=zi(t,s)),Zr(t,n.shape)},b:()=>{let t=e;const n=ki(s.shape,a);return n.length>0&&(t=zi(t,n)),Zr(so(t),s.shape)}}}},{kernelName:Ln,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,a=s.shape.slice(),{axis:r}=n;P(r,s.shape).forEach((e=>{a[e]=1}));const i=Zr(e,a),o=Mi(i,oo(s.shape,"float32"));return{x:()=>o}}},{kernelName:jn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>bi(e,to(Fh(n)))}}},{kernelName:Kn,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Mi(Li(Fr(1),to(n)),e)}}},{kernelName:qn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:a}=n;return{x:()=>{let t=Po(s);if(1===s.rank)for(let n=0;n{const s=n,{perm:a}=s,r=Qi(a);return{x:()=>Wo(e,r)}}},{kernelName:Qn,gradFunc:(e,t,n)=>{const s=n,{axis:a}=s;return{value:()=>Fo(e,a)}}},{kernelName:es,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=Ui(t,Po(t)),s=Ei(e,n);let a=Ri(t,Fr(0,"int32"));const r=s.rank-a.rank;for(let e=0;e({x:()=>Po(e)})}];for(const e of Vh)fs(e);_s().prototype.abs=function(){return this.throwIfDisposed(),_r(this)};const Uh=la({acos_:function(e){const t={x:ia(e,"x","acos")};return Zs.runKernel(me,t)}});_s().prototype.acos=function(){return this.throwIfDisposed(),Uh(this)};const Gh=la({acosh_:function(e){const t={x:ia(e,"x","acosh")};return Zs.runKernel(ge,t)}});_s().prototype.acosh=function(){return this.throwIfDisposed(),Gh(this)},_s().prototype.add=function(e){return this.throwIfDisposed(),Or(this,e)},_s().prototype.all=function(e,t){return this.throwIfDisposed(),Mr(this,e,t)},_s().prototype.any=function(e,t){return this.throwIfDisposed(),Lr(this,e,t)},_s().prototype.argMax=function(e){return this.throwIfDisposed(),zr(this,e)};const Hh=la({argMin_:function(e,t=0){const n={x:ia(e,"x","argMin")},s={axis:t};return Zs.runKernel(ve,n,s)}});_s().prototype.argMin=function(e){return this.throwIfDisposed(),Hh(this,e)},_s().prototype.asScalar=function(){return this.throwIfDisposed(),E(1===this.size,(()=>"The array must have only 1 element.")),Zr(this,[])},_s().prototype.asType=function(e){return this.throwIfDisposed(),ja(this,e)},_s().prototype.as1D=function(){return this.throwIfDisposed(),Zr(this,[this.size])},_s().prototype.as2D=function(e,t){return this.throwIfDisposed(),Zr(this,[e,t])},_s().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),Zr(this,[e,t,n])},_s().prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),Zr(this,[e,t,n,s])},_s().prototype.as5D=function(e,t,n,s,a){return this.throwIfDisposed(),Zr(this,[e,t,n,s,a])};const jh=la({asin_:function(e){const t={x:ia(e,"x","asin")};return Zs.runKernel(Ne,t)}});_s().prototype.asin=function(){return this.throwIfDisposed(),jh(this)};const Kh=la({asinh_:function(e){const t={x:ia(e,"x","asinh")};return Zs.runKernel(Ie,t)}});_s().prototype.asinh=function(){return this.throwIfDisposed(),Kh(this)};const qh=la({atan_:function(e){const t={x:ia(e,"x","atan")};return Zs.runKernel($e,t)}});_s().prototype.atan=function(){return this.throwIfDisposed(),qh(this)};const Xh=la({atan2_:function(e,t){let n=ia(e,"a","atan2"),s=ia(t,"b","atan2");[n,s]=Gs(n,s);const a={a:n,b:s};return Zs.runKernel(Se,a)}});_s().prototype.atan2=function(e){return this.throwIfDisposed(),Xh(this,e)};const Yh=la({atanh_:function(e){const t={x:ia(e,"x","atanh")};return Zs.runKernel(Ce,t)}});_s().prototype.atanh=function(){return this.throwIfDisposed(),Yh(this)},_s().prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),Qr(this,e,t,n,s)},_s().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Bh(this,e,t)},_s().prototype.batchNorm=function(e,t,n,s,a){return this.throwIfDisposed(),ti(this,e,t,n,s,a)},_s().prototype.broadcastTo=function(e){return this.throwIfDisposed(),zo(this,e)},_s().prototype.cast=function(e){return this.throwIfDisposed(),ja(this,e)};const Jh=la({ceil_:function(e){const t={x:ia(e,"x","ceil")};return Zs.runKernel(Me,t)}});_s().prototype.ceil=function(){return this.throwIfDisposed(),Jh(this)},_s().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),ri(this,e,t)},_s().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Ds&&(e=[e]),ii([this,...e],t)},_s().prototype.conv1d=function(e,t,n,s,a,r){return this.throwIfDisposed(),pi(this,e,t,n,s,a,r)},_s().prototype.conv2dTranspose=function(e,t,n,s,a){return this.throwIfDisposed(),fi(this,e,t,n,s,a)},_s().prototype.conv2d=function(e,t,n,s,a,r){return this.throwIfDisposed(),hi(this,e,t,n,s,a,r)},_s().prototype.cos=function(){return this.throwIfDisposed(),Fh(this)},_s().prototype.cosh=function(){return this.throwIfDisposed(),_h(this)},_s().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),vc(this,e,t,n)};const Zh=la({depthToSpace_:function(e,t,n="NHWC"){const s=ia(e,"x","depthToSpace"),a="NHWC"===n?s.shape[1]:s.shape[2],r="NHWC"===n?s.shape[2]:s.shape[3],i="NHWC"===n?s.shape[3]:s.shape[1];E(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${s.shape}`)),E(r*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${r} and ${t} for depthToSpace with input shape\n ${s.shape}`)),E(i%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${s.shape}`));const o={x:s},l={blockSize:t,dataFormat:n};return Zs.runKernel(Ze,o,l)}});_s().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Zh(this,e,t)},_s().prototype.depthwiseConv2d=function(e,t,n,s,a,r){return this.throwIfDisposed(),gi(this,e,t,n,s,a,r)};const Qh=la({dilation2d_:function(e,t,n,s,a=[1,1],r="NHWC"){const i=ia(e,"x","dilation2d"),o=ia(t,"filter","dilation2d");E(3===i.rank||4===i.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`)),E(3===o.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`)),E("NHWC"===r,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${r}`));let l=i,u=!1;3===i.rank&&(l=Zr(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);const c={x:l,filter:o},h={strides:n,pad:s,dilations:a},p=Zs.runKernel(st,c,h);return u?Zr(p,[p.shape[1],p.shape[2],p.shape[3]]):p}});_s().prototype.dilation2d=function(e,t,n,s,a){return this.throwIfDisposed(),Qh(this,e,t,n,s,a)};const ep=la({divNoNan_:function(e,t){let n=ia(e,"a","div"),s=ia(t,"b","div");[n,s]=Gs(n,s);const a=bi(n,s),r=Po(a),i=Ni(s,r);return Bo(i,r,a)}});_s().prototype.divNoNan=function(e){return this.throwIfDisposed(),ep(this,e)},_s().prototype.div=function(e){return this.throwIfDisposed(),bi(this,e)};const tp=la({dot_:function(e,t){const n=ia(e,"t1","dot"),s=ia(t,"t2","dot");E(!(1!==n.rank&&2!==n.rank||1!==s.rank&&2!==s.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`));const a=1===n.rank?n.size:n.shape[1],r=1===s.rank?s.size:s.shape[0];if(E(a===r,(()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${r}.`)),1===n.rank&&1===s.rank){const e=Zr(n,[1,-1]),t=Zr(s,[-1,1]),a=il(e,t);return Zr(a,[])}if(1===n.rank&&2===s.rank){const e=Zr(n,[1,-1]),t=Zr(s,[s.shape[0],s.shape[1]]),a=il(e,t);return Zr(a,[a.size])}if(2===n.rank&&1===s.rank){const e=Zr(s,[-1,1]),t=il(n,e);return Zr(t,[t.size])}{const e=Zr(s,[s.shape[0],s.shape[1]]);return il(n,e)}}});_s().prototype.dot=function(e){return this.throwIfDisposed(),tp(this,e)},_s().prototype.elu=function(){return this.throwIfDisposed(),xi(this)},_s().prototype.equal=function(e){return this.throwIfDisposed(),Ni(this,e)};const np=la({erf_:function(e){let t=ia(e,"x","erf");E("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=ja(t,"float32"));const n={x:t};return Zs.runKernel(ut,n)}});_s().prototype.erf=function(){return this.throwIfDisposed(),np(this)},_s().prototype.exp=function(){return this.throwIfDisposed(),_i(this)},_s().prototype.expandDims=function(e){return this.throwIfDisposed(),Ii(this,e)};const sp=la({expm1_:function(e){const t={x:ia(e,"x","expm1")};return Zs.runKernel(dt,t)}});_s().prototype.expm1=function(){return this.throwIfDisposed(),sp(this)},_s().prototype.fft=function(){return this.throwIfDisposed(),Ho(this)},_s().prototype.flatten=function(){return this.throwIfDisposed(),Zr(this,[this.size])},_s().prototype.floor=function(){return this.throwIfDisposed(),Ti(this)},_s().prototype.floorDiv=function(e){return this.throwIfDisposed(),yi(this,e)},_s().prototype.gather=function(e,t){return this.throwIfDisposed(),Ei(this,e,t)},_s().prototype.greaterEqual=function(e){return this.throwIfDisposed(),Ri(this,e)},_s().prototype.greater=function(e){return this.throwIfDisposed(),Ai(this,e)},_s().prototype.ifft=function(){return this.throwIfDisposed(),Ko(this)},_s().prototype.irfft=function(){return this.throwIfDisposed(),qo(this)};const ap=la({isFinite_:function(e){const t={x:ia(e,"x","isFinite")};return Zs.runKernel(St,t)}});_s().prototype.isFinite=function(){return this.throwIfDisposed(),ap(this)};const rp=la({isInf_:function(e){const t={x:ia(e,"x","isInf")};return Zs.runKernel(Tt,t)}});_s().prototype.isInf=function(){return this.throwIfDisposed(),rp(this)};const ip=la({isNaN_:function(e){const t={x:ia(e,"x","isNaN")};return Zs.runKernel(Et,t)}});_s().prototype.isNaN=function(){return this.throwIfDisposed(),ip(this)},_s().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Fi(this,e)},_s().prototype.lessEqual=function(e){return this.throwIfDisposed(),Al(this,e)},_s().prototype.less=function(e){return this.throwIfDisposed(),Zc(this,e)};const op=la({localResponseNormalization_:function(e,t=5,n=1,s=1,a=.5){const r=ia(e,"x","localResponseNormalization");E(4===r.rank||3===r.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${r.rank}.`)),E(O(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let i=r,o=!1;3===r.rank&&(o=!0,i=Zr(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const l={x:i},u={depthRadius:t,bias:n,alpha:s,beta:a},c=Zs.runKernel(Bt,l,u);return o?Zr(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});_s().prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),op(this,e,t,n,s)};const lp=la({logSigmoid_:function(e){const t=ia(e,"x","logSigmoid");return Rr((e=>({value:so(To(so(e))),gradFunc:t=>Mi(t,ko(so(e)))})))(t)}});_s().prototype.logSigmoid=function(){return this.throwIfDisposed(),lp(this)},_s().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Bi(this,e)},_s().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Ul(this,e,t)},_s().prototype.log=function(){return this.throwIfDisposed(),Di(this)},_s().prototype.log1p=function(){return this.throwIfDisposed(),Vl(this)},_s().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Pi(this,e)},_s().prototype.logicalNot=function(){return this.throwIfDisposed(),Sh(this)};const up=la({logicalOr_:function(e,t){const n=ia(e,"a","logicalOr","bool"),s=ia(t,"b","logicalOr","bool");vi(n.shape,s.shape);const a={a:n,b:s};return Zs.runKernel(zt,a)}});_s().prototype.logicalOr=function(e){return this.throwIfDisposed(),up(this,e)};const cp=la({logicalXor_:function(e,t){const n=ia(e,"a","logicalXor","bool"),s=ia(t,"b","logicalXor","bool");return vi(n.shape,s.shape),Pi(up(e,t),Sh(Pi(e,t)))}});_s().prototype.logicalXor=function(e){return this.throwIfDisposed(),cp(this,e)},_s().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),il(this,e,t,n)},_s().prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),Wi(this,e,t,n,s)},_s().prototype.max=function(e,t){return this.throwIfDisposed(),Oi(this,e,t)},_s().prototype.maximum=function(e){return this.throwIfDisposed(),Ui(this,e)},_s().prototype.mean=function(e,t){return this.throwIfDisposed(),Gi(this,e,t)},_s().prototype.min=function(e,t){return this.throwIfDisposed(),Hi(this,e,t)},_s().prototype.minimum=function(e){return this.throwIfDisposed(),ji(this,e)};const hp=la({mirrorPad_:function(e,t,n){E("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const s=ia(e,"x","mirrorPad");if(0===s.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");E(t.length===s.rank,(()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`));const a="reflect"===n?1:0;for(let e=0;e"Invalid number of paddings. Must be length of 2 each.")),E(t[e][0]>=0&&t[e][0]<=s.shape[e]-a&&t[e][1]>=0&&t[e][1]<=s.shape[e]-a,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${s.shape[e]-a} or less than 0 for input of shape ${s.shape}`));const r={paddings:t,mode:n},i={x:s};return Zs.runKernel(Jt,i,r)}});_s().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),hp(this,e,t)};const pp=la({mod_:function(e,t){let n=ia(e,"a","mod"),s=ia(t,"b","mod");[n,s]=Gs(n,s);const a={a:n,b:s};return Zs.runKernel(Zt,a)}});_s().prototype.mod=function(e){return this.throwIfDisposed(),pp(this,e)},_s().prototype.mul=function(e){return this.throwIfDisposed(),Mi(this,e)},_s().prototype.neg=function(){return this.throwIfDisposed(),so(this)},_s().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Ol(this,e,t,n)},_s().prototype.notEqual=function(e){return this.throwIfDisposed(),ao(this,e)},_s().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),ro(this,e,t,n)},_s().prototype.onesLike=function(){return this.throwIfDisposed(),lo(this)},_s().prototype.pad=function(e,t){return this.throwIfDisposed(),uo(this,e,t)};const dp=la({pool_:function(e,t,n,s,a,r){null==a&&(a=[1,1]),null==r&&(r=1),0===s&&(s="valid");const i=ia(e,"x","maxPool");let o=i,l=!1;3===i.rank&&(l=!0,o=Zr(i,[1,i.shape[0],i.shape[1],i.shape[2]])),E(Yr(r,a),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${r} and dilations '${a}'`));const u=Pr(o.shape,t,r,a,s),c=[u.dilationHeight,u.dilationWidth];let h;h="same"===s?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))).map((e=>e-1)),s=n.map((e=>Math.floor(e/2))),a=n.map(((e,t)=>e-s[t]));return n.map(((e,t)=>[s[t],a[t]]))}([u.filterHeight,u.filterWidth],c):[[0,0],[0,0]];const p=1===c[0]&&1===c[1],[d,f]=function(e,t,n){const s=n.map((e=>e[0])),a=n.map((e=>e[1])),r=e.concat(s,a),i=t.map(((e,t)=>(e-r[t]%e)%e)),o=a.map(((e,t)=>e+i[t]));return[t.map(((e,t)=>[s[t],o[t]])),t.map(((e,t)=>[0,i[t]]))]}([u.inHeight,u.inWidth],c,h),m=p?s:"valid",g=p?o:rc(o,c,d),y=("avg"===n?()=>Qr(g,t,r,m):()=>Wi(g,t,r,m))(),b=p?y:Bh(y,c,f);return l?Zr(b,[b.shape[1],b.shape[2],b.shape[3]]):b}});_s().prototype.pool=function(e,t,n,s,a){return this.throwIfDisposed(),dp(this,e,t,n,s,a)},_s().prototype.pow=function(e){return this.throwIfDisposed(),Dl(this,e)},_s().prototype.prelu=function(e){return this.throwIfDisposed(),co(this,e)};const fp=la({prod_:function(e,t=null,n=!1){let s=ia(e,"x","prod");"bool"===s.dtype&&(s=ja(s,"int32"));const a={x:s},r={axis:t,keepDims:n};return Zs.runKernel(dn,a,r)}});_s().prototype.prod=function(e,t){return this.throwIfDisposed(),fp(this,e,t)};const mp=la({reciprocal_:function(e){const t={x:ia(e,"x","reciprocal")};return Zs.runKernel(gn,t)}});_s().prototype.reciprocal=function(){return this.throwIfDisposed(),mp(this)},_s().prototype.relu=function(){return this.throwIfDisposed(),yo(this)},_s().prototype.relu6=function(){return this.throwIfDisposed(),Yo(this)},_s().prototype.reshapeAs=function(e){return this.throwIfDisposed(),Zr(this,e.shape)},_s().prototype.reshape=function(e){return this.throwIfDisposed(),Zr(this,e)},_s().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),Sl(this,e,t,n)},_s().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),Tl(this,e,t,n)},_s().prototype.reverse=function(e){return this.throwIfDisposed(),bo(this,e)},_s().prototype.rfft=function(){return this.throwIfDisposed(),jo(this)};const gp=la({round_:function(e){const t={x:ia(e,"x","round")};return Zs.runKernel($n,t)}});_s().prototype.round=function(){return this.throwIfDisposed(),gp(this)},_s().prototype.rsqrt=function(){return this.throwIfDisposed(),Dc(this)},_s().prototype.selu=function(){return this.throwIfDisposed(),xo(this)},_s().prototype.separableConv2d=function(e,t,n,s,a,r){return this.throwIfDisposed(),wo(this,e,t,n,s,a,r)},_s().prototype.sigmoid=function(){return this.throwIfDisposed(),ko(this)};const yp=la({sign_:function(e){const t={x:ia(e,"x","sign")};return Zs.runKernel(Dn,t)}});_s().prototype.sign=function(){return this.throwIfDisposed(),yp(this)},_s().prototype.sin=function(){return this.throwIfDisposed(),bc(this)},_s().prototype.sinh=function(){return this.throwIfDisposed(),wc(this)},_s().prototype.slice=function(e,t){return this.throwIfDisposed(),vo(this,e,t)},_s().prototype.softmax=function(e){return this.throwIfDisposed(),So(this,e)},_s().prototype.softplus=function(){return this.throwIfDisposed(),To(this)},_s().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),rc(this,e,t)},_s().prototype.split=function(e,t){return this.throwIfDisposed(),Eo(this,e,t)},_s().prototype.sqrt=function(){return this.throwIfDisposed(),Ao(this)},_s().prototype.square=function(){return this.throwIfDisposed(),to(this)},_s().prototype.squaredDifference=function(e){return this.throwIfDisposed(),Wl(this,e)},_s().prototype.squeeze=function(e){return this.throwIfDisposed(),Ro(this,e)},_s().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof Ds?[this,e]:[this,...e];return Fo(n,t)},_s().prototype.step=function(e){return this.throwIfDisposed(),Jo(this,e)};const bp=la({stridedSlice_:function(e,t,n,s,a=0,r=0,i=0,o=0,l=0){const u={x:ia(e,"x","stridedSlice")},c={begin:t,end:n,strides:s,beginMask:a,endMask:r,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return Zs.runKernel(Hn,u,c)}});_s().prototype.stridedSlice=function(e,t,n,s,a,r,i,o){return this.throwIfDisposed(),bp(this,e,t,n,s,a,r,i,o)},_s().prototype.sub=function(e){return this.throwIfDisposed(),Li(this,e)},_s().prototype.sum=function(e,t){return this.throwIfDisposed(),zi(this,e,t)};const xp=la({tan_:function(e){const t={x:ia(e,"x","tan")};return Zs.runKernel(jn,t)}});_s().prototype.tan=function(){return this.throwIfDisposed(),xp(this)},_s().prototype.tanh=function(){return this.throwIfDisposed(),Do(this)},_s().prototype.tile=function(e){return this.throwIfDisposed(),$i(this,e)},_s().prototype.toBool=function(){return this.throwIfDisposed(),ja(this,"bool")},_s().prototype.toFloat=function(){return this.throwIfDisposed(),ja(this,"float32")},_s().prototype.toInt=function(){return this.throwIfDisposed(),ja(this,"int32")};const wp=la({topk_:function(e,t=1,n=!0){const s=ia(e,"x","topk");if(0===s.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const a=s.shape[s.shape.length-1];if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);const r={x:s},i={k:t,sorted:n},[o,l]=Zs.runKernel(Xn,r,i);return{values:o,indices:l}}});_s().prototype.topk=function(e,t){return this.throwIfDisposed(),wp(this,e,t)},_s().prototype.transpose=function(e){return this.throwIfDisposed(),Wo(this,e)};const kp=la({unique_:function(e,t=0){const n=ia(e,"x","unique","string_or_numeric");E(n.rank>0,(()=>"The input tensor must be at least 1D"));const s={x:n},a={axis:t},[r,i]=Zs.runKernel(Zn,s,a);return{values:r,indices:i}}});let vp;function Np(){return null==vp&&(vp=Zs.backend.epsilon()),vp}_s().prototype.unique=function(e){return this.throwIfDisposed(),kp(this,e)},_s().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),Oc(this,e,t)},_s().prototype.unstack=function(e){return this.throwIfDisposed(),Lo(this,e)},_s().prototype.where=function(e,t){return this.throwIfDisposed(),Bo(e,this,t)},_s().prototype.zerosLike=function(){return this.throwIfDisposed(),Po(this)};class Ip extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ip.prototype)}}class $p extends Error{constructor(e){super(e),Object.setPrototypeOf(this,$p.prototype)}}class Cp extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Cp.prototype)}}class Sp extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Sp.prototype)}}class Tp extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Tp.prototype)}}function Ep(e,t){if(Array.isArray(e)){let n=[];for(let s=0;st.toUpperCase()))}Error;let Mp={};function Lp(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function zp(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>zp(e)));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"==typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!=typeof t.value?zp(t):e[n]=t.value)}}}function Bp(e,t={},n={},s="object",a=!1){if("string"==typeof e){const a=e;let r;if(a in n)r=n[a];else if(a in Mp)r=Mp[a];else if(r=t[a],null==r)throw new Cp(`Unknown ${s}: ${e}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return r}{const r=e;if(null==r.className||null==r.config)throw new Cp(`${s}: Improper config format: ${JSON.stringify(r)}.\n'className' and 'config' must set.`);const i=r.className;let o,l;if(i in n?[o,l]=n[i]:i in Mp?[o,l]=Mp.className:i in t&&([o,l]=t[i]),null==o)throw new Cp(`Unknown ${s}: ${i}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=l){const e={};for(const t of Object.keys(Mp))e[t]=Mp[t];for(const t of Object.keys(n))e[t]=n[t];r.config.customObjects=e;const t=Object.assign({},Mp);for(const e of Object.keys(n))Mp[e]=n[e];zp(r.config);const s=l(o,r.config,n,a);return Mp=Object.assign({},t),s}{const e=Object.assign({},Mp);for(const e of Object.keys(n))Mp[e]=n[e];const t=new o(r.config);return Mp=Object.assign({},e),t}}}function Pp(e,t){return-1*function(e,t){return et?1:0}(e,t)}function Wp(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function Vp(e){if(null==e)throw new Cp(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Up(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new Cp(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function Gp(e,t,n=0,s=1/0){return Ap(n>=0),Ap(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every((e=>typeof e===t))}function Hp(e,t){Array.isArray(e)?(E(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>Hp(e,`element ${n+1} of ${t}`)))):E(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${jp(e)}.`))}function jp(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>jp(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function Kp(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}function qp(e,t){return Cr((()=>Ao(zi(Mi(e,e),t,!0))))}class Xp extends kr{getConfig(){return{}}}class Yp extends Xp{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Cr((()=>{const t=qp(e,this.axis),n=ri(t,0,this.maxValue);return Mi(e,bi(n,Or(Np(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Yp.className="MaxNorm",Nr(Yp);class Jp extends Xp{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Cr((()=>bi(e,Or(Np(),qp(e,this.axis)))))}getConfig(){return{axis:this.axis}}}Jp.className="UnitNorm",Nr(Jp);class Zp extends Xp{apply(e){return yo(e)}}Zp.className="NonNeg",Nr(Zp);class Qp extends Xp{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Cr((()=>{const t=qp(e,this.axis),n=Or(Mi(this.rate,ri(t,this.minValue,this.maxValue)),Mi(1-this.rate,t));return Mi(e,bi(n,Or(Np(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Qp.className="MinMaxNorm",Nr(Qp);const ed={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function td(e){return Lp(e)}function nd(e,t={}){return Bp(e,vr.getMap().classNameMap,t,"constraint")}function sd(e){return null==e?null:"string"==typeof e?nd({className:e in ed?ed[e]:e,config:{}}):e instanceof Xp?e:nd(e)}const ad=["channelsFirst","channelsLast"],rd=["nearest","bilinear"],id=["valid","same","causal"],od=["max","avg"],ld=["sum","mul","concat","ave"],ud=new Map;function cd(e){Up(ad,"DataFormat",e)}function hd(e){Up(id,"PaddingMode",e)}function pd(e){Up(od,"PoolMode",e)}const dd=[];function fd(e,t){dd.push(e);try{const e=t();return dd.pop(),e}catch(e){throw dd.pop(),e}}function md(e){if(!bd(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===dd.length?"":dd.join("/")+"/")+e}function gd(e){if(!bd(e))throw new Error("Not a valid tensor name: '"+e+"'");ud.has(e)||ud.set(e,0);const t=ud.get(e);if(ud.set(e,ud.get(e)+1),t>0){const n=`${e}_${t}`;return ud.set(n,1),n}return e}const yd=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function bd(e){return!!e.match(yd)}function xd(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let s=1;for(let a=t;a{switch(e.rank){case 1:return No(e,t,n);case 2:return Io(e,[t,0],[n,e.shape[1]]);case 3:return $o(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Co(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return vo(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return vo(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new Cp(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Sd(e,t,n){return Cr((()=>{switch(e.rank){case 1:return No(e,t,n);case 2:return Io(e,[0,t],[e.shape[0],n]);case 3:return $o(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Co(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Cp(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Td(e,t,n,s){return Cr((()=>{switch(e.rank){case 1:return No(e,t,n);case 2:switch(s){case 1:return Cd(e,t,n);case 2:return Sd(e,t,n);default:throw new Cp(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return Cd(e,t,n);case 2:return $o(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Sd(e,t,n);default:throw new Cp(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return Cd(e,t,n);case 2:return Co(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Co(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Sd(e,t,n);default:throw new Cp(`The axis is not within the rank of the tensor ${s}`)}default:throw new Cp(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ed(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),ii(e,t)}function Ad(e,t){switch(e.rank){case 1:return oi([e,t]);case 2:return li([e,t],0);case 3:return ui([e,t],0);case 4:return ci([e,t],0);default:throw new Cp(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Rd(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Cp(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return $i(e,t)}function Fd(e,t=0,n=1,s,a){return mo(e,t,n,s,a)}function Dd(e,t,n,s){if(e.rank<2||t.rank<2)throw new Sp(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3&&e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new Sp(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`);if(2===e.rank&&2===t.rank)return ol({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?Md(e.rank,s,"channelsLast"):null,activation:n});{const a=e.shape.slice(),r=a.pop();e=e.reshape([-1,r]);const i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],c=Array.from({length:t.rank},((e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n));t=t.transpose(c).reshape([l,-1]);const h=[...a,...u];return ol({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?Md(e.rank,s,"channelsLast"):null,activation:n}).reshape(h)}}function _d(e,t,n){return Cr((()=>(t=Array.isArray(t)?_o(t,"int32"):t.toInt(),Ei(e,t,n))))}function Od(e){return Mi(e,e)}function Md(e,t,n){const s=t.shape;if(1!==t.rank&&t.rank!==e)throw new Cp(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===s.length?t.reshape([1,s[0],1,1,1]):t.reshape([1,s[3],s[0],s[1],s[2]]);if("channelsLast"===n)return 1===s.length?t.reshape([1,1,1,1,s[0]]):t.reshape([1].concat(s))}else if(4===e){if("channelsFirst"===n)return 1===s.length?t.reshape([1,s[0],1,1]):t.reshape([1,s[2],s[0],s[1]]);if("channelsLast"===n)return 1===s.length?t.reshape([1,1,1,s[0]]):t.reshape([1].concat(s))}else if(3===e){if("channelsFirst"===n)return 1===s.length?t.reshape([1,s[0],1]):t.reshape([1,s[1],s[0]]);if("channelsLast"===n)return 1===s.length?t.reshape([1,1,s[0]]):t.reshape([1].concat(s))}else if(e<3)return t;throw new Cp(`Unsupported input rank by biasAdd: ${t.rank}`)}function Ld(e,t,n){return Cr((()=>(null==n&&(n="channelsLast"),cd(n),e.add(Md(e.rank,t,n)))))}function zd(e,t,n,s){return Cr((()=>Vo(e,t,n,s)))}function Bd(e,t,n=!1){return n?e():t()}const Pd=["fanIn","fanOut","fanAvg"],Wd=["normal","uniform","truncatedNormal"];class Vd extends kr{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Ud extends Vd{apply(e,t){return io(e,t)}}Ud.className="Zeros",Nr(Ud);class Gd extends Vd{apply(e,t){return oo(e,t)}}Gd.className="Ones",Nr(Gd);class Hd extends Vd{constructor(e){if(super(),"object"!=typeof e)throw new Cp(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new Cp(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return Cr((()=>Mi(Fr(this.value),oo(e,t))))}getConfig(){return{value:this.value}}}Hd.className="Constant",Nr(Hd);class jd extends Vd{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return go(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}jd.className="RandomUniform",Nr(jd);class Kd extends Vd{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Sp(`randomNormal does not support dType ${t}.`);return Fd(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Kd.className="RandomNormal",Nr(Kd);class qd extends Vd{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Sp(`truncatedNormal does not support dType ${t}.`);return Mo(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}qd.className="TruncatedNormal",Nr(qd);class Xd extends Vd{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return Cr((()=>{if(2!==e.length||e[0]!==e[1])throw new Cp("Identity matrix initializer can only be used for 2D square matrices.");return Mi(this.gain,Ci(e[0]))}))}getConfig(){return{gain:this.gain}}}Xd.className="Identity",Nr(Xd);class Yd extends Vd{constructor(e){if(super(),e.scale<0)throw new Cp(`scale must be a positive float. Got: ${e.scale}`);var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,Up(Pd,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){Up(Wd,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,s;if(cd(t),2===e.length)n=e[0],s=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=xd(e,2);n=e[1]*t,s=e[0]*t}else if("channelsLast"===t){const t=xd(e,0,e.length-2);n=e[e.length-2]*t,s=e[e.length-1]*t}}else{const t=xd(e);n=Math.sqrt(t),s=Math.sqrt(t)}return[n,s]}(e),s=n[0],a=n[1];let r=this.scale;if("fanIn"===this.mode?r/=Math.max(1,s):"fanOut"===this.mode?r/=Math.max(1,a):r/=Math.max(1,(s+a)/2),"normal"===this.distribution){const n=Math.sqrt(r);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Sp(`${this.getClassName()} does not support dType ${t}.`);return Mo(e,0,n,t,this.seed)}{const n=Math.sqrt(3*r);return go(e,-n,n,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Yd.className="VarianceScaling",Nr(Yd);class Jd extends Yd{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Yd.className}}Jd.className="GlorotUniform",Nr(Jd);class Zd extends Yd{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Yd.className}}Zd.className="GlorotNormal",Nr(Zd);class Qd extends Yd{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Yd.className}}Qd.className="HeNormal",Nr(Qd);class ef extends Yd{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Yd.className}}ef.className="HeUniform",Nr(ef);class tf extends Yd{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Yd.className}}tf.className="LeCunNormal",Nr(tf);class nf extends Yd{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Yd.className}}nf.className="LeCunNormal",Nr(nf);class sf extends Vd{constructor(e){if(super(),this.DEFAULT_GAIN=1,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,null!=this.seed)throw new Sp("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return Cr((()=>{if(e.length<2)throw new Sp("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);const t=Fd(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32");let n=Hl.gramSchmidt(t);return e[0]>e[1]&&(n=n.transpose()),Mi(this.gain,n)}))}getConfig(){return{gain:this.gain,seed:this.seed}}}sf.className="Orthogonal",Nr(sf);const af={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function rf(e,t={}){return Bp(e,vr.getMap().classNameMap,t,"initializer")}function of(e){return Lp(e)}function lf(e){if("string"==typeof e){const t=e in af?af[e]:e;if("GlorotNormal"===t)return new Zd;if("GlorotUniform"===t)return new Jd;if("HeNormal"===t)return new Qd;if("HeUniform"===t)return new ef;if("LeCunNormal"===t)return new tf;if("LeCunUniform"===t)return new nf;{const e={};return e.className=t,e.config={},rf(e)}}return e instanceof Vd?e:rf(e)}let uf=0;function cf(){return uf++}const hf={};function pf(e=""){return e in hf||(hf[e]=0),hf[e]+=1,e+hf[e].toString()}function df(e){return Array.isArray(e)&&Array.isArray(e[0])}function ff(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function mf(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new Cp(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function gf(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return(e=e)[0];throw new Cp(`Expected exactly 1 Shape; got ${e.length}`)}return e}function yf(e){let t=0;for(const n of e)0===n.shape.length?t+=1:t+=n.shape.reduce(((e,t)=>e*t));return t}class bf{constructor(e,t="float32",n="Variable",s=!0,a=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=cf(),n=null==n?"Variable":n,this.originalName=md(n),this.name=gd(this.originalName),this.trainable_=s,this.constraint=a,this.val=function(e,t=!0,n,s){return Zs.makeVariable(e,t,n,s)}(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function xf(e){return e.map((e=>e.read()))}function wf(e){e.forEach((e=>{e[0].write(e[1])}))}class kf{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class vf{constructor(e,t,n,s,a,r,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=a,this.outputTensorIndex=i,this.id=cf(),null!=r&&(this.originalName=md(r),this.name=gd(this.originalName)),this.rank=t.length}}let Nf=0;class If{constructor(e,t){this.callArgs=t,this.id=Nf++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let $f=0;class Cf extends kr{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=$f++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=_p(e)+"_"+pf(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new $p(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Cp(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Fp(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Fp(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Ip(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new Ip(`Layer ${this.name} is not connected, no input to return.`);return Fp(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Ip(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Ip(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Fp(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((e=>e()))}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach((t=>t.trainable=e)),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((e=>e.trainable)):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((e=>!e.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Dp(e),null==this.inputSpec||0===this.inputSpec.length)return;const t=Dp(this.inputSpec);if(e.length!==t.length)throw new Cp(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;na.maxNDim)throw new Cp(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${r}`);if(null!=a.minNDim&&r=0?e[s]:e[e.length+s];if(null!=r&&-1===[r,null].indexOf(i))throw new Cp(`Input ${n} is incompatible with layer ${this.name}: expected axis ${s} of input shape to have value ${r} but got shape ${e}.`)}}if(null!=a.shape)for(let e=0;e{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Dp(e))t.push(n.shape);this.build(Fp(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let s=this.call(e,t);const a=Dp(s),r=[];for(let e of a)-1!==n.indexOf(e)&&(e=e.clone()),r.push(e);if(s=Fp(r),null!=this.activityRegularizer)throw new Sp("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}{const n=function(e){e=Dp(e);const t=[];for(const n of e)t.push(n.shape);return Fp(t)}(e),s=this.computeOutputShape(n);let a;const r="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),a=null!=s&&s.length>0&&Array.isArray(s[0])?s.map(((n,s)=>new vf(r,n,this,Dp(e),t,this.name,s))):new vf(r,s,this,Dp(e),t,this.name),this.addInboundNode(e,a,null,null,n,s,t),this._refCount++,null!=this.activityRegularizer)throw new Sp("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach(((n,s)=>{null!=n&&null!=e[s]&&e[s]!==n&&(t=!0)})),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Ip(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new Ip(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new $p(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return yf(this.weights)}build(e){this.built=!0}getWeights(e=!1){return xf(e?this.trainableWeights:this.weights)}setWeights(e){Cr((()=>{const t=this.weights;if(t.length!==e.length)throw new Cp(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],s=xf(t);for(let a=0;aa.apply(l.read()))),null==r&&(r=!0),r?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=Dp(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}addInboundNode(e,t,n,s,a,r,i=null){const o=Dp(e);t=Dp(t),n=Dp(n),s=Dp(s),a=ff(a),r=ff(r);const l=[],u=[],c=[];for(const e of o)l.push(e.sourceLayer),u.push(e.nodeIndex),c.push(e.tensorIndex);new If({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:c,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:a,outputShapes:r},i);for(let e=0;ee.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function Sf(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n0){const a=await Promise.all(t);for(let t=0;tOr(this.totals[e],Mi(s,n))));this.totals[e]=a,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const e of this.params.metrics)null!=this.totals[e]&&("number"==typeof this.totals[e]?t[e]=this.totals[e]/this.seen:Cr((()=>{const n=Mi(bi(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),Tr(t[e])})))}}class Of extends Ff{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const e in t)null==this.history[e]&&(this.history[e]=[]),this.history[e].push(t[e])}async syncData(){const e=[],t=[],n=[];for(const s in this.history){const a=this.history[s];for(let r=0;r{const r=bs();return r-snew Mf(e,t)))}class zf{constructor(){}static registerCallbackConstructor(e,t){E(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),zf.checkForDuplicate(t),null==zf.constructors[e]&&(zf.constructors[e]=[]),zf.constructors[e].push(t)}static checkForDuplicate(e){for(const t in zf.constructors)zf.constructors[+t].forEach((t=>{if(t===e)throw new Cp("Duplicate callback constructor.")}))}static clear(){zf.constructors={}}static createCallbacks(e){const t=[];for(const n in zf.constructors){const s=+n;e>=s&&t.push(...zf.constructors[s])}return t.map((e=>new e))}}function Bf(e,t,n,s,a,r,i,o,l){const u=new Of,c=[new _f,...zf.createCallbacks(t)];null!=e&&c.push(...e),c.push(u);const h=new Df(c);return h.setParams({epochs:n,initialEpoch:s,samples:a,steps:r,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function Pf(e,t={},n=!1){return Bp(e,vr.getMap().classNameMap,t,"layer",n)}function Wf(e,t){return Cr((()=>{"float32"!==e.dtype&&(e=e.asType("float32"));const n=zi(Od(e),t,!0),s=Si(n.shape,Np()),a=Ao(Ui(n,s));return bi(e,a)}))}function Vf(e,t){return Cr((()=>Gi(Od(Li(t,e)),-1)))}function Uf(e,t){return Cr((()=>Gi(_r(Li(t,e)),-1)))}function Gf(e,t){return Cr((()=>{const n=Li(e,t),s=ri(_r(e),Np(),Number.MAX_VALUE),a=_r(bi(n,s));return Mi(100,Gi(a,-1))}))}function Hf(e,t,n=!1){return Cr((()=>{if(n)t=So(t);else{const e=zi(t,t.shape.length-1,!0);t=bi(t,e)}return t=ri(t,Np(),1-Np()),so(zi(Mi(e.toFloat(),Di(t)),t.shape.length-1))}))}function jf(e,t,n=!1){return Cr((()=>{const s=Ti(function(e){const t=[xd(e.shape)];return e.reshape(t)}(e)).toInt(),a=(t=ri(t,Np(),1-Np())).shape;return Hf(ro(s,a[a.length-1]).reshape(a),t,n)}))}function Kf(e,t){return Cr((()=>{let n;return n=ri(t,Np(),1-Np()),n=Di(bi(n,Li(1,n))),Gi(function(e,t){if(!_(e.shape,t.shape))throw new Cp(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return Cr((()=>{const n=t.relu(),s=t.abs().neg();return n.sub(t.mul(e)).add(s.exp().log1p())}))}(e,n),-1)}))}function qf(e,t){return Cr((()=>{const n=Wf(e,-1),s=Wf(t,-1),a=Mi(n,s);return so(zi(a,-1))}))}zf.constructors={};const Xf={meanSquaredError:Vf,meanAbsoluteError:Uf,meanAbsolutePercentageError:Gf,meanSquaredLogarithmicError:function(e,t){return Cr((()=>{const n=ri(t,Np(),Number.MAX_VALUE),s=Di(Or(1,n)),a=ri(e,Np(),Number.MAX_VALUE),r=Di(Or(1,a));return Gi(Od(Li(s,r)),-1)}))},squaredHinge:function(e,t){return Cr((()=>{const n=Ui(0,Li(1,Mi(e,t)));return Gi(Od(n),-1)}))},hinge:function(e,t){return Cr((()=>{const n=Ui(0,Li(1,Mi(e,t)));return Gi(n,-1)}))},categoricalHinge:function(e,t){return Cr((()=>{const n=zi(Mi(e,t),-1),s=Oi(Mi(Li(1,e),t),-1);return Ui(0,Or(1,Li(s,n)))}))},logcosh:function(e,t){return Cr((()=>{const n=Math.log(2),s=Li(t,e),a=Li(Or(s,To(Mi(-2,s))),n);return Gi(a,-1)}))},categoricalCrossentropy:Hf,sparseCategoricalCrossentropy:jf,binaryCrossentropy:Kf,kullbackLeiblerDivergence:function(e,t){return Cr((()=>{const n=ri(e,Np(),1),s=ri(t,Np(),1);return zi(Mi(e,Di(bi(n,s))),-1)}))},poisson:function(e,t){return Cr((()=>{const n=Di(Or(Np(),t));return Gi(Li(t,Mi(e,n)),-1)}))},cosineProximity:qf};function Yf(e){if("string"==typeof e){if(e in Xf)return Xf[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new Cp(t)}return e}function Jf(e,t){return Cr((()=>{const n=Mi(.5,lo(t)),s=Id(Ai(t,n),e.dtype);return Gi(Ni(e,s),-1)}))}function Zf(e,t){return Cr((()=>Id(Ni(zr(e,-1),zr(t,-1)),"float32")))}function Qf(e,t){return Kf(e,t)}function em(e,t){return e.rank===t.rank&&(e=e.squeeze([e.rank-1])),(t=t.argMax(-1)).dtype!==e.dtype&&(t=t.asType(e.dtype)),Ni(e,t).asType("float32")}const tm=Hf,nm=jf,sm={binaryAccuracy:Jf,categoricalAccuracy:Zf,precision:function(e,t){return Cr((()=>{const n=function(e,t){return Cr((()=>Pi(e.equal(1),t.equal(1)).sum().cast("float32")))}(e,t),s=function(e,t){return Cr((()=>Pi(e.equal(0),t.equal(1)).sum().cast("float32")))}(e,t),a=n.add(s);return Bo(Ai(a,0),n.div(a),0).cast("float32")}))},categoricalCrossentropy:tm,sparseCategoricalCrossentropy:nm,mse:Vf,MSE:Vf,mae:Uf,MAE:Uf,mape:Gf,MAPE:Gf,cosine:qf};function am(e){if("string"==typeof e&&e in sm)return sm[e];if("string"!=typeof e&&null!=e)return e;throw new Cp(`Unknown metric ${e}`)}function rm(e){if(Ap(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(Xf))if(Xf[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(sm))if(sm[n]===e){t=n;break}return void 0!==t?t:e.name}}function im(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!om(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(e);n.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function om(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!=typeof n)return!1;if(!om(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!om(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}function lm(e,t,n=console.log){let s="";for(let n=0;n0&&(s=s.slice(0,s.length-1)+" "),s+=e[n],s=s.slice(0,t[n]),s+=" ".repeat(t[n]-s.length);n(s)}function um(e,t,n){let s;try{s=JSON.stringify(e.outputShape)}catch(e){s="multiple"}lm([`${e.name} (${e.getClassName()})`,s,e.countParams().toString()],t,n)}function cm(e,t,n,s){let a;try{a=JSON.stringify(e.outputShape)}catch(e){a="multiple"}const r=[];for(const t of e.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(t)))for(let e=0;ee.name)),l=[],u=t.names();for(const e of o)-1!==u.indexOf(e)?l.push(t.getValue(e)):l.push(null);null!=s&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);const c=o.join(",")+"|"+t.names().join(",");let h,p;if(null==mm[c]){const e=function(e,t){E(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],s={};if(1===e.length){const a=xm(e[0],t);n=a.sorted,s=a.recipientMap}else{const a=new Set;for(const r of e){const{sorted:e,recipientMap:i}=xm(r,t);for(const t of e)a.has(t.name)||(n.push(t),a.add(t.name));for(const e in i)null==s[e]&&(s[e]=new Set),i[e].forEach((t=>s[e].add(t)))}}return{sorted:n,recipientCounts:bm(s)}}(i,t);h=e.sorted,p=e.recipientCounts,mm[c]=h,gm[c]=p}h=mm[c],p={},a||Object.assign(p,gm[c]);const d=new fm(t);for(let e=0;es.maxNumTensors&&(s.maxNumTensors=e),e0;){const e=r[r.length-1];if(n.has(e.name)){r.pop();continue}const t=i[i.length-1]===r.length-1;if(0===e.inputs.length||t)r.pop(),s.push(e),n.add(e.name),t&&i.pop();else{i.push(r.length-1);for(const t of e.inputs)null==a[t.name]&&(a[t.name]=new Set),a[t.name].add(e.name),n.has(t.name)||r.push(t)}}return{sorted:s,recipientMap:a}}function wm(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;te.name))}`);Wp(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,s=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(s)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,s=e.tensorIndex;Ap(0===n,"input layer has >1 nodes"),Ap(0===s,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(s)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;te.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},s={},a={},r={},i=[],o=(e,t,n,s,a,l)=>{null!=s&&null!=a&&null!=l||(s=e.sourceLayer,a=e.nodeIndex,l=e.tensorIndex);const u=s.inboundNodes[a];if(-1!==n.indexOf(u))throw new $p(`The tensor ${e.name} at layer "${s.name}" is part of a cycle.`);if(-1!==t.indexOf(u))return;this.containerNodes.add(km.nodeKey(s,a)),s.id in r||(r[s.id]=Object.keys(r).length),-1===n.indexOf(u)&&n.push(u);const c=u.inboundLayers.length;for(let e=0;e=0;)n.splice(n.indexOf(u),1);i.push(u)},l=[],u=[];for(const e of this.outputs)o(e,l,u);const c=i.slice().reverse();for(const e of c){n[e.id]=e,e.id in t||(t[e.id]=0);let r=t[e.id];const i=null==s[e.outboundLayer.id]?0:s[e.outboundLayer.id];r=Math.max(r,i),s[e.outboundLayer.id]=r,a[e.outboundLayer.id]=e.outboundLayer,t[e.id]=r;for(let s=0;sparseInt(e,10))).sort(Pp);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=r[e.id],s=r[t.id];return ns?1:0}));for(const e of t)e instanceof km&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(Pp);const f=this.inputs.slice(),m=[];for(const e of d)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===f.indexOf(n))throw new $p(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${m}`);for(const e of t.outputTensors)f.push(e);m.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new $p(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new If({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new Cp("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let s=0;for(const e of this.layers)for(const t of e.weights){if(null!=n[t.originalName])throw new Cp(`Duplicate weight name: ${t.originalName}`);n[t.originalName]=t,s++}const a=[];for(const s in e){let r=s;if(null==n[s]){const e=s.split("/");r=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[r])a.push([n[r],e[s]]);else if(t)throw new Cp(`Provided weight data has no target variable: ${s}`);delete n[r]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new Cp(`${e.length} of ${s} weights are not set: ${e}`)}wf(a)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion="tfjs-layers 3.3.0",t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=dm(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return Cr((()=>{e=Dp(e);const n=new fm;for(let t=0;t{let n;return e=Dp(e),n=null==t?Ep(null,e.length):Dp(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=ff(e);if(t.length!==this.inputLayers.length)throw new Cp(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;eparseInt(e,10))).sort(Pp);if(s.length>1)for(const e of s){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const s=[];for(let t=0;tparseInt(e,10))).sort(Pp);for(const e of s){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,s=e.inputTensors,a=e.outputTensors,r=new Array;for(const e of s)e.id in n&&r.push(n[e.id]);if(r.length===s.length){let s,i,o,l,u={};if(null!=e.callArgs&&(u=e.callArgs),1===r.length){const[e,n]=r[0];null==u.mask&&(u.mask=n),o=Dp(t.call(e,u)),l=Dp(t.computeMask(e,n)),s=[e],i=[n]}else s=r.map((e=>e[0])),i=r.map((e=>e[1])),null==u.mask&&(u.mask=i),o=Dp(t.call(s,u)),l=Dp(t.computeMask(s,i));if(t.activityRegularizer)throw new Sp("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e{const e=[];for(const t of this.layers)for(let n=0;n0){const e=[];for(let n=0;n0&&e.apply(Fp(n),s)}function l(e){const n=e.name,r=Pf(e,null!=t.customObjects?t.customObjects:{});r.setFastWeightInitDuringBuild(s),a[n]=r,e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new Cp(`Corrupted configuration, expected array for nodeData: ${e}`);i(r,e)}))}const u=t.name,c=t.layers;for(const e of c)l(e);for(;!Vp(r);)for(const e of c){const t=a[e.name];if(t.name in r){const e=r[t.name];delete r[t.name];for(const n of e)o(t,n)}}const h=[],p=[],d=t.inputLayers;for(const e of d){const t=e[0],n=e[1],s=e[2];Ap(t in a);const r=a[t].inboundNodes[n].outputTensors;h.push(r[s])}const f=t.outputLayers;for(const e of f){const t=e[0],n=e[1],s=e[2];Ap(t in a);const r=a[t].inboundNodes[n].outputTensors;p.push(r[s])}return new e({inputs:h,outputs:p,name:u})}get stateful(){if(this._stateful)throw new Cp("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){Cr((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}function vm(e,t){return function(e,t,n){const s=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===s)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){const n=[];return t.forEach((t=>{t in e?n.push(e[t]):n.push(null)})),n}throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}(e,t,"classWeight")}async function Nm(e,t,n,s){if(null!=t||null!=s)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=Cr((()=>{if(1===e.shape.length)return e.clone();if(2===e.shape.length){if(e.shape[1]>1){const t=1;return e.argMax(t)}if(1===e.shape[1])return e.reshape([e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)})),s=Array.from(await t.data());Sr(t);const a=[];return s.forEach((e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);a.push(n[e])})),_o(a,"float32")}return null}function Im(e,t){return Mi(e,t)}function $m(e,t){let n,s;const a=t;n=a.xs,s=a.ys,E(null!=n&&null!=s,(()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`));const r=Cm("input",e.inputNames,n),i=Cm("output",e.outputNames,s),o=r[0].shape[0];E(r.length===e.inputs.length,(()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${r.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`)),E(i.length===e.outputs.length,(()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`));for(let t=0;t`Batch size mismatch: input ${e.inputNames[t]} has ${r[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));for(let t=0;t`Batch size mismatch: output ${e.outputNames[t]} has ${i[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));return{xs:r,ys:i}}function Cm(e,t,n){if(n instanceof Ds)return[n];if(Array.isArray(n))return E(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const s=[];for(const a of t){if(null==n[a])throw new Cp(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);s.push(n[a])}return s}}function Sm(e){return"function"==typeof e.iterator}function Tm(e){E(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function Em(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>Cd(e,t,n-t))):Cd(e,t,n-t)}function Am(e,t){return Cr((()=>null==e?null:Array.isArray(e)?e.map((e=>Am(e,t))):_d(e,"int32"===t.dtype?t:t.toInt())))}function Rm(e,t){const n=[];let s=0,a=null;for(;s=e&&(a=e),n.push([s,a]),s=a;return n}function Fm(e){const t=[];e instanceof Ds&&(e=[e]);for(let n=0;nn.push(e.id)));else if(null!=t)for(const e in t){const s=t[e];n.push(s.id)}const s=[];if(e instanceof Ds)-1===n.indexOf(e.id)&&s.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&s.push(e)}));else if(null!=e)for(const t in e){const a=e[t];-1===n.indexOf(a.id)&&s.push(a)}s.forEach((e=>{e.isDisposed||e.dispose()}))}function _m(e){return Array.isArray(e)}function Om(e){return!function(e){return e instanceof Ds}(e)&&!_m(e)}function Mm(e,t,n,s=!0,a=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(_m(e)&&e.length>0)t=!0;else if(Om(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Cp(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let r;if(Om(e)){e=e,r=[];for(const n of t){if(null==e[n])throw new Cp(`No data provided for "${n}". Need data for each key in: ${t}`);r.push(e[n])}}else if(_m(e)){if((e=e).length!==t.length)throw new Cp(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);r=e}else{if(e=e,t.length>1)throw new Cp(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);r=[e]}if(r=Fm(r),null!=n)for(let e=0;e=0&&o!==l)throw new Cp(`Error when checking ${a}: expected ${t[e]} to have shape [${n[e]}], but got array with shape [${i.shape}].`)}}return r}function Lm(e,t,n,s=!0,a=""){let r;if(Array.isArray(e)){if(e.length!==t.length)throw new Cp(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);r=e}else{if(t.length>1)throw new Cp(`The model expects ${t.length} ${a} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);r=[e]}if(null!=n)for(let e=0;e1||1===e.length&&e[0].inboundLayers.length>1){t=!1;break}s.push(...e)}if(t)for(const n of e.layers){let e=!1;for(const a of n.inboundNodes)if(-1!==s.indexOf(a)){if(e){t=!1;break}e=!0}if(!t)break}return t}(e),r=["Layer (type)","Output shape","Param #"];let i;if(a?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map((e=>Math.floor(t*e)))),!a){r.push("Receives inputs"),i=[];for(const t in e.nodesByDepth)i.push(...e.nodesByDepth[t])}s("_".repeat(t)),lm(r,n,s),s("=".repeat(t));const o=e.layers;for(let e=0;eeu.adagrad(.01),Adadelta:()=>eu.adadelta(1,.95,Np()),Adam:()=>eu.adam(.001,.9,.999,Np()),Adamax:()=>eu.adamax(.002,.9,.999,Np(),0),RMSProp:()=>eu.rmsprop(.001,.9,0,Np()),SGD:()=>eu.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new Cp(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Dr))throw new Cp("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new Cp(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>Yf(e)))}else{const n=Yf(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new Cp(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(Yf(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e{for(let e=0;e1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const s=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const s of t){let t=n.hasOwnProperty(s)?n[s]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),a=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};fd("metric",(()=>{for(let e=0;e{let n,s,r;for(const i of t){if("string"==typeof i&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(i)){const t=this.internalOutputShapes[e];let a;1===t[t.length-1]||this.lossFunctions[e]===Kf?-1!==["accuracy","acc"].indexOf(i)?s=Jf:-1!==["crossentropy","ce"].indexOf(i)&&(s=Qf):this.lossFunctions[e]===jf?-1!==["accuracy","acc"].indexOf(i)?s=em:-1!==["crossentropy","ce"].indexOf(i)&&(s=nm):-1!==["accuracy","acc"].indexOf(i)?s=Zf:-1!==["crossentropy","ce"].indexOf(i)&&(s=tm),-1!==["accuracy","acc"].indexOf(i)?a="acc":-1!==["crossentropy","ce"].indexOf(i)&&(a="ce"),r=s,n=""+a}else{const e=am(i);r=e,n=""+rm(i)}let t;fd(n,(()=>{t=r})),a(e,n,t)}})(s[e])})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const s=null==n.batchSize?32:n.batchSize;Tm(s);const a=this.standardizeUserDataXY(e,t,!0,s);try{const r=a[0].concat(a[1]);this.makeTestFunction();const i=this.testFunction;return Fp(this.testLoop(i,r,s,n.verbose,n.steps))}finally{Dm(a[0],e),Dm(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const s=null!=(n=n||{}).batches,a=e.testFunction;let r=[];if(n.verbose>0)throw new Sp("Verbose mode is not implemented yet.");E(!s||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const i="function"==typeof t.next?t:await t.iterator();let o=0,l=0;for(;!s||l{if(t.value){const{xs:n,ys:s}=$m(e,t.value),i=n.concat(s),u=Cr((()=>a(i)));if(Sr(i),0===l)for(let e=0;eOr(r[e],Mi(c,t)))),l>0&&Sr(n)}Sr(u),o+=c,++l}return r})),t.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;ee.name));for(let s=0;s0){const n=[];throw t.forEach(((t,s)=>{null==t&&n.push(e[s])})),new Cp(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return Cr((()=>{const s=this.checkNumSamples(e);if(n)throw new Sp("Verbose predictLoop() is not implemented yet.");const a=Rm(s,t),r=this.outputs.map((e=>[]));for(let t=0;t{const n=a[t][0],s=a[t][1],r=Em(e,n,s),i=[];if(Array.isArray(r))for(let e=0;er[t].push(e)));return Fp(r.map((e=>ii(e,0))))}))}predict(e,t={}){const n=Fm(e);Lm(n,this.inputNames,this.feedInputShapes,!1);try{const s=null==t.batchSize?32:t.batchSize;return Tm(s),this.predictLoop(n,s)}finally{Dm(n,e)}}predictOnBatch(e){Lm(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(null==this.optimizer_)throw new $p("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const a=[];for(let e=0;ee.shape[0])));s.sort();const a=Wp(t.map((e=>e.shape[0])));if(a.sort(),s.length>1)throw new Cp(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(a.length>1)throw new Cp(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(s.length>0&&a.length>0&&!_(s,a))throw new Cp(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${a[0]} target sample(s).`)}(e=Mm(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Mm(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){const s=[Vf,Kf,Hf];for(let a=0;a0&&e[0].shape[0]%s!=0)throw new Cp(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,a=!0,r){const[i,o]=this.standardizeUserDataXY(e,t,a,r);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=s){const e=vm(s,this.outputNames);l=[];for(let t=0;t{const r=this.checkNumSamples(t,n,a,"steps"),i=[];if(s>0)throw new Sp("Verbose mode is not implemented yet.");if(null!=a)throw new Sp("steps mode in testLoop() is not implemented yet");{const s=Rm(r,n),a=_o(Nd(0,r));for(let n=0;n1&&(a+=`_${Rp(e.slice(0,n),s)}`),t.push(a)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),r=[],i=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t1&&e{l=Or(l,e)})),l}),!0,i)].concat(r)}}makeTestFunction(){this.testFunction=e=>Cr((()=>{const t=[];let n;const s=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=[];for(let e=0;e0){if(m=!0,2!==s.validationData.length)throw 3===s.validationData.length?new Sp("validationData including sample weights is not supported yet."):new Cp(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);i=s.validationData[0],o=s.validationData[1];const t=!0,n=await e.standardizeUserData(i,o,null,null,t,h);l=n[0],u=n[1],f=l.concat(u)}else if(null!=s.validationSplit&&s.validationSplit>0&&s.validationSplit<1){m=!0;const e=Math.floor(a[0].shape[0]*(1-s.validationSplit)),t=a[0].shape[0];l=Em(a,e,t),a=Em(a,0,e),u=Em(r,e,t),r=Em(r,0,e),f=l.concat(u)}else null!=s.validationSteps&&(m=!0);const g=a.concat(r).concat(c);e.checkTrainableWeightsConsistency();const y=e.makeTrainFunction(),b=e.getDedupedMetricsNames();let x,w;m?(e.makeTestFunction(),x=e.testFunction,w=b.slice().concat(b.map((e=>"val_"+e)))):(x=null,f=[],w=b.slice());const k=Lf(s.callbacks,s.yieldEvery);return await async function(e,t,n,s,a,r,i,o,l,u,c,h,p,d,f){null==a&&(a=32),null==r&&(r=1),null==c&&(c=!0),null==p&&(p=0);let m=!1;null!=l&&null!=u&&(m=!0);const g=e.checkNumSamples(n,a,d,"steps_per_epoch");let y;null!=g&&(y=Nd(0,g)),null==i&&(i=1);const{callbackList:b,history:x}=Bf(o,i,r,p,g,d,a,m,h);b.setModel(e),e.history=x,await b.onTrainBegin(),e.stopTraining_=!1;for(let i=p;i{const p=o[c][0],d=o[c][1],f=Cd(i,p,d-p);h.batch=c,h.size=d-p;const g=Am(n,f),y=t(g);for(let e=0;e"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),E(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),E(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`)),E(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),E(null==n.validationSplit,(()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead.")),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const a=null!=n.validationData;let r,i;if(a)if(Sm(n.validationData))E(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),(()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`));else{const e=function(e){if(3===e.length)throw new Sp("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);r=e.xs,i=e.ys}const o=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let u;u=a?l.slice().concat(l.map((e=>"val_"+e))):l.slice();const c=Lf(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:p,history:d}=Bf(c,h,n.epochs,null,null,function(e,t){let n=null;return null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}(t,n),null,a,u);p.setModel(e),e.history=d,await p.onTrainBegin(),e.stopTraining_=!1;let f=null==n.initialEpoch?0:n.initialEpoch,m=await t.iterator();for(;f=n.batchesPerEpoch:t.done){if(a){let t;t=Sm(n.validationData)?Dp(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):Dp(e.evaluate(r,i,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n_p(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const s of t){if("string"!=typeof n[s])throw new Error("Serialization of non-string loss is not supported.");e[s]=_p(n[s])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[_p(rm(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>_p(rm(e))));{const e={};for(const t in this.metrics)e[t]=_p(rm(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Pf(pm(e.optimizer_config));let n,s;if("string"==typeof e.loss)n=Op(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Op(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Op(e.loss[t])}if(Array.isArray(e.metrics))s=e.metrics.map((e=>Op(e)));else if(null!=e.metrics){s={};for(const t in e.metrics)s[t]=Op(e.metrics[t])}this.compile({loss:n,metrics:s,optimizer:t})}async save(e,t){if("string"==typeof e){const t=ka(e);if(0===t.length)throw new Cp(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Cp(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Cp("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await da(this.getNamedWeights(t)),s={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v3.3.0",convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){s.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:a}=await da(await this.optimizer.getWeights(),e);n.specs.push(...a),n.data=ya([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;im(this.userDefinedMetadata,this.name,e),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){im(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}zm.className="Model",Nr(zm);class Bm extends zm{}Bm.className="Functional",Nr(Bm);class Pm extends zm{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:pf("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new Cp(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof Pm||e instanceof zm;let n;if(t){if(n=e,1!==n.outputs.length)throw new Cp("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new Cp("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new Cp("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=function(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new Cp("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;return null==n&&(n="float32"),new Tf({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new Cp(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new Cp("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=Sf(this.outputs[0])}this.inboundNodes=[],new If({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Ep(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(gf(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new zm({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new $p("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new $p("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new $p("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new $p("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let a,r={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new Cp("Legacy serialization format not supported yet.");a=t}else E(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),a=t.layers,delete t.layers,r=t;const i=new e(r);if(!(i instanceof Pm))throw new Sp(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const e of a){const t=Pf(e,void 0,s);s&&t.setFastWeightInitDuringBuild(!0),i.add(t)}return i}set stopTraining(e){if(null==this.model)throw new Cp("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new Cp("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}Pm.className="Sequential",Nr(Pm);class Wm extends kr{getConfig(){return{}}}class Vm extends Wm{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Sp(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return xi(e)}(e,t)}}Vm.className="elu",Nr(Vm);class Um extends Wm{apply(e){return xo(e)}}Um.className="selu",Nr(Um);class Gm extends Wm{apply(e){return yo(e)}}Gm.className="relu",Nr(Gm);class Hm extends Wm{apply(e){return Cr((()=>ji(6,yo(e))))}}Hm.className="relu6",Nr(Hm);class jm extends Wm{apply(e){return e}}jm.className="linear",Nr(jm);class Km extends Wm{apply(e){return ko(e)}}Km.className="sigmoid",Nr(Km);class qm extends Wm{apply(e){return function(e){return Cr((()=>{const t=Or(.5,Mi(.2,e));return ri(t,0,1)}))}(e)}}qm.className="hardSigmoid",Nr(qm);class Xm extends Wm{apply(e){return To(e)}}Xm.className="softplus",Nr(Xm);class Ym extends Wm{apply(e){return function(e){return Cr((()=>bi(e,_r(e).add(1))))}(e)}}Ym.className="softsign",Nr(Ym);class Jm extends Wm{apply(e){return Do(e)}}Jm.className="tanh",Nr(Jm);class Zm extends Wm{apply(e,t=-1){return So(e,t)}}Zm.className="softmax",Nr(Zm);class Qm extends Wm{apply(e,t=-1){return Bi(e,t)}}Qm.className="logSoftmax",Nr(Qm);class eg extends Wm{apply(e,t=1){return Cr((()=>ko(e.mul(t)).mul(e)))}}function tg(e){return e.getClassName()}function ng(e,t={}){return Bp(e,vr.getMap().classNameMap,t,"activation")}function sg(e){if(null==e){return ng({className:"linear",config:{}})}if("string"==typeof e){const t={};return t.className=e,t.config={},ng(t)}return e instanceof Wm?e:ng(e)}eg.className="swish",Nr(eg);class ag extends kr{}class rg extends ag{constructor(e){super(),function(e){if(null!=e&&"object"!=typeof e)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return Cr((()=>{let t=io([1]);return this.hasL1&&(t=Or(t,zi(Mi(this.l1,_r(e))))),this.hasL2&&(t=Or(t,zi(Mi(this.l2,Od(e))))),t.asScalar()}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}rg.className="L1L2",Nr(rg);const ig={l1l2:"L1L2"};function og(e){return Lp(e)}function lg(e,t={}){return Bp(e,vr.getMap().classNameMap,t,"regularizer")}function ug(e){return null==e?null:"string"==typeof e?lg({className:e in ig?ig[e]:e,config:{}}):e instanceof ag?e:lg(e)}class cg extends Cf{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=mf(e);let n=yo(e);return null!=this.maxValue&&(n=ri(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}cg.className="ReLU",Nr(cg);class hg extends Cf{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=mf(e);return Fi(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}hg.className="LeakyReLU",Nr(hg);class pg extends Cf{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=lf(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=ug(e.alphaRegularizer),this.alphaConstraint=sd(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new Cp(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=gf(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t(cd(t),"channelsFirst"===t?Wo(e,[0,2,3,1]):e)))}function wg(e,t){return Cr((()=>(cd(t),"channelsFirst"===t?Wo(e,[0,2,3,4,1]):e)))}function kg(e,t,n,s=[1,1],a="valid",r,i,o=null){return Cr((()=>{if(null==r&&(r="channelsLast"),cd(r),3!==e.rank&&4!==e.rank)throw new Cp(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Cp(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=xg(e,r);if("causal"===a)throw new Sp("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=nl({x:l,filter:t,strides:s,pad:"same"===a?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===r&&(l=Wo(l,[0,3,1,2])),l}))}mg.className="Softmax",Nr(mg);class vg extends Cf{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",vg.verifyArgs(t),this.rank=e,Hp(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Sp(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=gg(t.kernelSize,e,"kernelSize"),this.strides=gg(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,hd(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,cd(this.dataFormat),this.activation=sg(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=lf(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=sd(t.biasConstraint),this.biasRegularizer=ug(t.biasRegularizer),this.activityRegularizer=ug(t.activityRegularizer),this.dilationRate=gg(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Cp(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new Cp(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new Cp(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Ap("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!Gp(e.kernelSize,"number",1,3))throw new Cp(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:tg(this.activation),useBias:this.useBias,biasInitializer:of(this.biasInitializer),biasRegularizer:og(this.biasRegularizer),activityRegularizer:og(this.activityRegularizer),biasConstraint:td(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class Ng extends vg{constructor(e,t){super(e,t),this.kernel=null,Ng.verifyArgs(t),this.filters=t.filters,Hp(this.filters,"filters"),this.kernelInitializer=lf(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=sd(t.kernelConstraint),this.kernelRegularizer=ug(t.kernelRegularizer)}build(e){e=gf(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Cp(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return Cr((()=>{let t;e=mf(e);const n=null==this.bias?null:this.bias.read(),s=Kp(this.activation.getClassName());if(null!=s&&2===this.rank)t=kg(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(1===this.rank)t=function(e,t,n,s=1,a="valid",r,i=1){return Cr((()=>{if(null==r&&(r="channelsLast"),cd(r),3!==e.shape.length)throw new Cp(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Cp(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Cp(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===r&&(e=Wo(e,[0,2,1])),"causal"===a)throw new Sp("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=pi(e,t,s,"same"===a?"same":"valid","NWC",i);return null!=n&&(o=Ld(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=kg(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Sp("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,s=[1,1,1],a="valid",r,i){return Cr((()=>{if(null==r&&(r="channelsLast"),cd(r),4!==e.rank&&5!==e.rank)throw new Cp(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Cp(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=wg(e,r);if("causal"===a)throw new Sp("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=mi(o,t,s,"same"===a?"same":"valid","NDHWC",i),null!=n&&(o=Ld(o,n)),"channelsFirst"===r&&(o=Wo(o,[0,4,1,2,3])),o}))}(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=gf(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e 0 but got ${JSON.stringify(e.filters)}`)}}class Ig extends Ng{constructor(e){super(2,e),Ig.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!Gp(e.kernelSize,"number",1,2))throw new Cp(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Ig.className="Conv2D",Nr(Ig);class $g extends Ng{constructor(e){super(3,e),$g.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new Cp(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}$g.className="Conv3D",Nr($g);class Cg extends Ig{constructor(e){if(super(e),this.inputSpec=[new kf({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Cp(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=gf(e)).length)throw new Cp("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Cp("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new kf({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Cr((()=>{let t=mf(e);if(4!==t.shape.length)throw new Cp(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,s=n[0];let a,r;"channelsFirst"===this.dataFormat?(a=2,r=3):(a=1,r=2);const i=n[a],o=n[r],l=this.kernelSize[0],u=this.kernelSize[1],c=this.strides[0],h=this.strides[1],p=[s,bg(i,c,l,this.padding),bg(o,h,u,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=Wo(t,[0,2,3,1]));let d=fi(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=Wo(d,[0,3,1,2])),null!=this.bias&&(d=Ld(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=gf(e)).slice();let n,s,a;"channelsFirst"===this.dataFormat?(n=1,s=2,a=3):(n=3,s=1,a=2);const r=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=bg(t[s],o,r,this.padding),t[a]=bg(t[a],l,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Cg.className="Conv2DTranspose",Nr(Cg);class Sg extends Ng{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new Cp("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Cp("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new Cp(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=lf(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=ug(t.depthwiseRegularizer),this.depthwiseConstraint=sd(t.depthwiseConstraint),this.pointwiseInitializer=lf(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=ug(t.pointwiseRegularizer),this.pointwiseConstraint=sd(t.pointwiseConstraint)}build(e){if((e=gf(e)).length{let t;if(e=mf(e),1===this.rank)throw new Sp("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=Wo(e,[0,2,3,1])),t=wo(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Ld(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=Wo(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=of(this.depthwiseInitializer),e.pointwiseInitializer=of(this.pointwiseInitializer),e.depthwiseRegularizer=og(this.depthwiseRegularizer),e.pointwiseRegularizer=og(this.pointwiseRegularizer),e.depthwiseConstraint=td(this.depthwiseConstraint),e.pointwiseConstraint=td(this.pointwiseConstraint),e}}Sg.className="SeparableConv";class Tg extends Sg{constructor(e){super(2,e)}}Tg.className="SeparableConv2D",Nr(Tg);class Eg extends Ng{constructor(e){super(1,e),Eg.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!Gp(e.kernelSize,"number",1,1))throw new Cp(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Eg.className="Conv1D",Nr(Eg);class Ag extends Cf{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return Cr((()=>{if(e=mf(e),"channelsLast"===this.dataFormat){const t=Td(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Td(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Td(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Td(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Ag.className="Cropping2D",Nr(Ag);class Rg extends Cf{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,cd(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,Up(rd,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return Cr((()=>{let t=mf(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=Wo(t,[0,2,3,1]);const e=this.size[0]*n[2],s=this.size[1]*n[3],a="nearest"===this.interpolation?t.resizeNearestNeighbor([e,s]):t.resizeBilinear([e,s]);return Wo(a,[0,3,1,2])}{const e=this.size[0]*n[1],s=this.size[1]*n[2];return"nearest"===this.interpolation?t.resizeNearestNeighbor([e,s]):t.resizeBilinear([e,s])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Rg.className="UpSampling2D",Nr(Rg);class Fg extends vg{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=lf(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=sd(e.depthwiseConstraint),this.depthwiseRegularizer=ug(e.depthwiseRegularizer)}build(e){if((e=gf(e)).length<4)throw new Cp(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new Cp(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return Cr((()=>{let t=function(e,t,n=[1,1],s="valid",a,r){return Cr((()=>{null==a&&(a="channelsLast"),cd(a);let i=xg(e,a);if(4!==e.rank)throw new Cp(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new Cp(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=gi(i,t,n,"same"===s?"same":"valid","NHWC",r),"channelsFirst"===a&&(i=Wo(i,[0,3,1,2])),i}))}(e=mf(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=Ld(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=gf(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],s="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=yg(t,this.kernelSize[0],this.padding,this.strides[0]),r=yg(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],s,a,r]:[e[0],a,r,s]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=of(this.depthwiseInitializer),e.depthwiseRegularizer=og(this.depthwiseRegularizer),e.depthwiseConstraint=td(this.depthwiseRegularizer),e}}function Dg(e,t,n,s){if(Array.isArray(e)){if(null!=t||null!=n)throw new Cp("When inputs is an array, neither initialState or constants should be provided");null!=s&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:n=a(n)}}function _g(e,t,n,s=!1,a,r,i=!1,o=!1){return Cr((()=>{const l=t.shape.length;if(l<3)throw new Cp(`Input should be at least 3D, but is ${l}D.`);const u=[1,0].concat(Nd(2,l));if(t=Wo(t,u),null!=r)throw new Sp("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=a&&((a=a.asType("bool").asType("float32")).rank===l-1&&(a=Ii(a,-1)),a=Wo(a,u)),s&&(t=bo(t,0),null!=a&&(a=bo(a,0)));const c=[];let h,p=n;const d=t.shape[0],f=Lo(t);let m,g;null!=a&&(m=Lo(a));for(let t=0;te(n,p)));if(null==a)h=s[0],p=s[1];else{const e=Cr((()=>{const e=m[t],n=lo(e).sub(e);return{output:s[0].mul(e).add(p[0].mul(n)),newStates:p.map(((t,a)=>s[1][a].mul(e).add(t.mul(n))))}}));h=e.output,p=e.newStates}o&&c.push(h)}return o&&(g=Fo(c,1)),[h,g,p]}))}Fg.className="DepthwiseConv2D",Nr(Fg);class Og extends Cf{constructor(e){let t;if(super(e),null==e.cell)throw new Cp("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Ug({cells:e.cell}):e.cell,null==t.stateSize)throw new Cp("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new kf({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){return null==this.states_?Nd(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null)):this.states_}setStates(e){this.states_=e}computeOutputShape(e){df(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let s;if(s=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const s of t)n.push([e[0],s]);return[s].concat(n)}return s}computeMask(e,t){return Cr((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;ne.shape[e.shape.length-1])),a))throw new Cp(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map((e=>new kf({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){Cr((()=>{if(!this.stateful)throw new Ip("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Cp("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>io([n,e]))):this.states_=[io([n,this.cell.stateSize])];else if(null==e)Sr(this.states_),null!=this.keptStates&&(Sr(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>io([n,e]))):this.states_[0]=io([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Cp(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):Sr(this.states_);for(let t=0;tTr(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const a=Dg(e,n,s,this.numConstants);e=a.inputs,n=a.initialState,s=a.constants;let r=[],i=[];if(null!=n){t.initialState=n,r=r.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new kf({shape:e.shape}));i=i.concat(this.stateSpec)}if(null!=s&&(t.constants=s,r=r.concat(s),this.numConstants=s.length),r[0]instanceof vf){const n=[e].concat(r),s=this.inputSpec.concat(i),a=this.inputSpec;this.inputSpec=s;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return Cr((()=>{const n=null==t?null:t.mask,s=null==t?null:t.training;let a=null==t?null:t.initialState;e=mf(e),null==a&&(a=this.stateful?this.states_:this.getInitialState(e));const r=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==r)throw new Cp(`RNN Layer has ${r} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const i={training:s},o=_g(((e,t)=>{const n=this.cell.call([e].concat(t),i);return[n[0],n.slice(1)]}),e,a,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],c=o[2];this.stateful&&this.resetStates(c,s);const h=this.returnSequences?u:l;return this.returnState?[h].concat(c):h}))}getInitialState(e){return Cr((()=>{let t=io(e.shape);return t=zi(t,[1,2]),t=$d(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Rd(t,[1,e]):t)):this.cell.stateSize>1?[Rd(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===Og.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){const s=Pf(t.cell,n);return new e(Object.assign(t,{cell:s}))}}Og.className="RNN",Nr(Og);class Mg extends Cf{}class Lg extends Mg{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Hp(this.units,"units"),this.activation=sg(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=lf(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=lf(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=lf(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=ug(e.kernelRegularizer),this.recurrentRegularizer=ug(e.recurrentRegularizer),this.biasRegularizer=ug(e.biasRegularizer),this.kernelConstraint=sd(e.kernelConstraint),this.recurrentConstraint=sd(e.recurrentConstraint),this.biasConstraint=sd(e.biasConstraint),this.dropout=kd([1,vd([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=kd([1,vd([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=gf(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return Cr((()=>{if(2!==(e=e).length)throw new Cp(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const s=null!=t.training&&t.training;let a;0lo(e),rate:this.dropout,training:s})),0lo(n),rate:this.recurrentDropout,training:s}));const r=this.dropoutMask,i=this.recurrentDropoutMask;a=Dd(null!=r?Mi(e,r):e,this.kernel.read()),null!=this.bias&&(a=Ld(a,this.bias.read())),null!=i&&(n=Mi(n,i));let o=Or(a,Dd(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:tg(this.activation),useBias:this.useBias,kernelInitializer:of(this.kernelInitializer),recurrentInitializer:of(this.recurrentInitializer),biasInitializer:of(this.biasInitializer),kernelRegularizer:og(this.kernelRegularizer),recurrentRegularizer:og(this.recurrentRegularizer),biasRegularizer:og(this.biasRegularizer),activityRegularizer:og(this.activityRegularizer),kernelConstraint:td(this.kernelConstraint),recurrentConstraint:td(this.recurrentConstraint),biasConstraint:td(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}Lg.className="SimpleRNNCell",Nr(Lg);class zg extends Og{constructor(e){e.cell=new Lg(e),super(e)}call(e,t){return Cr((()=>{null!=this.cell.dropoutMask&&(Sr(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Sr(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:a})}))}static fromConfig(e,t){return new e(t)}}zg.className="SimpleRNN",Nr(zg);class Bg extends Mg{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new Cp("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Hp(this.units,"units"),this.activation=sg(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=sg(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=lf(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=lf(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=lf(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=ug(e.kernelRegularizer),this.recurrentRegularizer=ug(e.recurrentRegularizer),this.biasRegularizer=ug(e.biasRegularizer),this.kernelConstraint=sd(e.kernelConstraint),this.recurrentConstraint=sd(e.recurrentConstraint),this.biasConstraint=sd(e.biasConstraint),this.dropout=kd([1,vd([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=kd([1,vd([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=gf(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return Cr((()=>{if(2!==(e=e).length)throw new Cp(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let s=e[1];e=e[0],0lo(e),rate:this.dropout,training:n,count:3})),0lo(s),rate:this.recurrentDropout,training:n,count:3}));const a=this.dropoutMask,r=this.recurrentDropoutMask;let i,o,l;0{null!=this.cell.dropoutMask&&(Sr(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Sr(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Pg.className="GRU",Nr(Pg);class Wg extends Mg{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Hp(this.units,"units"),this.activation=sg(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=sg(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=lf(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=lf(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=lf(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=ug(e.kernelRegularizer),this.recurrentRegularizer=ug(e.recurrentRegularizer),this.biasRegularizer=ug(e.biasRegularizer),this.kernelConstraint=sd(e.kernelConstraint),this.recurrentConstraint=sd(e.recurrentConstraint),this.biasConstraint=sd(e.biasConstraint),this.dropout=kd([1,vd([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=kd([1,vd([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=gf(e))[e.length-1];let s;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;s=new((t=class extends Vd{apply(t,s){const a=e.apply([n]),r=(new Gd).apply([n]),i=e.apply([2*n]);return Ad(Ad(a,r),i)}}).className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return Cr((()=>{const n=null!=t.training&&t.training;if(3!==(e=e).length)throw new Cp(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1];const a=e[2];e=e[0],0lo(e),rate:this.dropout,training:n,count:4})),0lo(s),rate:this.recurrentDropout,training:n,count:4}));const r=this.dropoutMask,i=this.recurrentDropoutMask;let o,l,u,c;0{null!=this.cell.dropoutMask&&(Sr(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Sr(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Vg.className="LSTM",Nr(Vg);class Ug extends Mg{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return Cr((()=>{let n=(e=e).slice(1);const s=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?s.push(n.splice(0,e.stateSize.length)):s.push(n.splice(0,1));s.reverse();const a=[];let r;for(let i=0;i{fd(`RNNCell_${s}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign({},e,t)}static fromConfig(e,t,n={}){const s=[];for(const e of t.cells)s.push(Pf(e,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return xf(e)}setWeights(e){const t=[];for(const n of this.cells){const s=n.weights.length,a=e.splice(s);for(let e=0;ezd(t(),n),i=()=>Bd(r,t,s);return!a||a<=1?Tr(i().clone()):Array(a).fill(void 0).map(i).map((e=>Tr(e.clone())))}Ug.className="StackedRNNCells",Nr(Ug);var Hg,jg;class Kg extends Og{constructor(e){if(e.unroll)throw new Sp("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Sp("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new kf({ndim:5})]}call(e,t){return Cr((()=>{if(null!=this.cell.dropoutMask&&(Sr(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Sr(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Cp("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,s=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:a})}))}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return Cr((()=>{const{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),a=io([s[0],...s.slice(2)]);return Array.isArray(t)?Array(t.length).fill(a):[a]}))}resetStates(e,t=!1){Cr((()=>{if(!this.stateful)throw new Ip("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),a=[s[0],...s.slice(2)];if(null==n[0])throw new Cp("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>io(a))):this.states_=[io(a)];else if(null==e)Sr(this.states_),null!=this.keptStates&&(Sr(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>io(a))):this.states_[0]=io(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Cp(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):Sr(this.states_);for(let t=0;tTr(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:s,padding:a,strides:r,dilationRate:i}=this.cell,o="channelsFirst"===t,l=e[o?3:2],u=e[o?4:3],c=yg(l,s[0],a,r[0],i[0]),h=yg(u,s[1],a,r[1],i[1]);return[...e.slice(0,2),...o?[n,c,h]:[c,h,n]]}}Kg.className="ConvRNN2D";class qg extends Wg{constructor(e){const{filters:t,kernelSize:n,strides:s,padding:a,dataFormat:r,dilationRate:i}=e;super(Object.assign({},e,{units:t})),this.filters=t,Hp(this.filters,"filters"),this.kernelSize=gg(n,2,"kernelSize"),this.kernelSize.forEach((e=>Hp(e,"kernelSize"))),this.strides=gg(s||1,2,"strides"),this.strides.forEach((e=>Hp(e,"strides"))),this.padding=a||"valid",hd(this.padding),this.dataFormat=r||"channelsLast",cd(this.dataFormat),this.dilationRate=gg(i||1,2,"dilationRate"),this.dilationRate.forEach((e=>Hp(e,"dilationRate")))}build(e){var t;e=gf(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new Cp(`The channel dimension of the input should be defined. Found ${e[n]}`);const s=e[n],a=this.kernelSize.concat([s,4*this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const r=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",r,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,s=this.filters;e=new((t=class extends Vd{apply(e,t){return Ed([n.apply([s]),oo([s]),n.apply([2*s])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return Cr((()=>{if(3!==e.length)throw new Cp(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,s=e[0],a=e[1],r=e[2];0lo(s),rate:this.dropout,training:n,count:4}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?Mi(t[n],e):e;let l=o(s,i,0),u=o(s,i,1),c=o(s,i,2),h=o(s,i,3);0lo(a),rate:this.recurrentDropout,training:n,count:4}));const p=this.recurrentDropoutMask;let d=o(a,p,0),f=o(a,p,1),m=o(a,p,2),g=o(a,p,3);const[y,b,x,w]=Eo(this.kernel.read(),4,3),[k,v,N,I]=this.useBias?Eo(this.bias.read(),4):[null,null,null,null];l=this.inputConv(l,y,k,this.padding),u=this.inputConv(u,b,v,this.padding),c=this.inputConv(c,x,N,this.padding),h=this.inputConv(h,w,I,this.padding);const[$,C,S,T]=Eo(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,$),f=this.recurrentConv(f,C),m=this.recurrentConv(m,S),g=this.recurrentConv(g,T);const E=this.recurrentActivation.apply(Or(l,d)),A=this.recurrentActivation.apply(Or(u,f)),R=Or(Mi(A,r),Mi(E,this.activation.apply(Or(c,m)))),F=Mi(this.recurrentActivation.apply(Or(h,g)),this.activation.apply(R));return[F,F,R]}))}getConfig(){const e=super.getConfig(),{units:t}=e,n=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(s=Object.getOwnPropertySymbols(e);a{this.invokeCallHook(e,t);const n=mf(e);if(0zd(n,this.rate,s,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Yg.className="Dropout",Nr(Yg);class Jg extends Yg{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Jg.className="SpatialDropout1D",Nr(Jg);class Zg extends Cf{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Hp(this.units,"units"),this.activation=sg(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=lf(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=lf(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=sd(e.kernelConstraint),this.biasConstraint=sd(e.biasConstraint),this.kernelRegularizer=ug(e.kernelRegularizer),this.biasRegularizer=ug(e.biasRegularizer),this.activityRegularizer=ug(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=gf(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=gf(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return Cr((()=>{this.invokeCallHook(e,t);const n=mf(e),s=Kp(this.activation.getClassName());let a;return null!=s?a=Dd(n,this.kernel.read(),s,this.bias?this.bias.read():null):(a=Dd(n,this.kernel.read()),null!=this.bias&&(a=Ld(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a}))}getConfig(){const e={units:this.units,activation:tg(this.activation),useBias:this.useBias,kernelInitializer:of(this.kernelInitializer),biasInitializer:of(this.biasInitializer),kernelRegularizer:og(this.kernelRegularizer),biasRegularizer:og(this.biasRegularizer),activityRegularizer:og(this.activityRegularizer),kernelConstraint:td(this.kernelConstraint),biasConstraint:td(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Zg.className="Dense",Nr(Zg);class Qg extends Cf{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=gf(e);for(const t of e.slice(1))if(null==t)throw new Cp(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],xd(e,1)]}call(e,t){return Cr((()=>{this.invokeCallHook(e,t);let n=mf(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t{this.invokeCallHook(e,t);const n=mf(e);return this.activation.apply(n)}))}getConfig(){const e={activation:tg(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}ey.className="Activation",Nr(ey);class ty extends Cf{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return Cr((()=>{return e=mf(e),t=e,n=this.n,Cr((()=>{if(2!==t.shape.length)throw new Cp(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Rd($d(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}ty.className="RepeatVector",Nr(ty);class ny extends Cf{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e{this.invokeCallHook(e,t);const n=mf(e),s=n.shape,a=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return n.reshape(a)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}ny.className="Reshape",Nr(ny);class sy extends Cf{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=Nd(1,e.dims.length+1);if(!_(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new kf({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=gf(e)).slice();return this.dims.forEach(((n,s)=>{t[s+1]=e[n]})),t}call(e,t){return Wo(mf(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}sy.className="Permute",Nr(sy);class ay extends Cf{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=mf(e);return Lr(ao(n,this.maskValue),-1)}call(e,t){return Cr((()=>{this.invokeCallHook(e,t);const n=mf(e),s=Lr(ao(n,this.maskValue),-1,!0);return n.mul(s.asType(n.dtype))}))}}ay.className="Masking",Nr(ay);class ry extends Cf{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Dp(e.inputLength))}this.inputDim=e.inputDim,Hp(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Hp(this.outputDim,"outputDim"),this.embeddingsInitializer=lf(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=ug(e.embeddingsRegularizer),this.activityRegularizer=ug(e.activityRegularizer),this.embeddingsConstraint=sd(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return Cr((()=>this.maskZero?(e=mf(e),ao(e,Po(e))):null))}computeOutputShape(e){if(e=gf(e),null==this.inputLength)return[...e,this.outputDim];const t=Dp(this.inputLength);if(t.length!==e.length-1)throw new Cp(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s{this.invokeCallHook(e,t);let n=mf(e);return"int32"!==n.dtype&&(n=Id(n,"int32")),_d(this.embeddings.read(),n.as1D()).reshape(gf(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:of(this.embeddingsInitializer),embeddingsRegularizer:og(this.embeddingsRegularizer),activityRegularizer:og(this.activityRegularizer),embeddingsConstraint:td(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}ry.className="Embedding",Nr(ry);class iy extends Cf{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Sp}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length1)throw new Cp(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let t=1;te.length));-1===e.indexOf(null)&&1===Wp(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Cr((()=>{if(e=e,this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const s=vd(n);for(let n of e){const e=n.rank;for(let t=0;t1){const a=Nd(1,e).concat([0]);t.push(Wo(s,a)),n=!0}else t.push(s)}let s=this.mergeFunction(t);const a=s.rank;if(n)if(null==a){const e=s.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));s=Wo(s.reshape([-1,t]),[1,0]).reshape(n)}else if(a>1){const e=[a-1].concat(Nd(0,a-1));s=Wo(s,e)}return s}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==(e=e)[0]?null:e[0].slice(1);for(let n=1;n{if(null==t)return null;if(!Array.isArray(t))throw new Cp("`mask` should be an Array");if(!Array.isArray(e))throw new Cp("`inputs` should be an Array");if(t.length!==e.length)throw new Cp(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every((e=>null==e)))return null;let n=(t=t.map((e=>null==e?e:Ii(e,0))))[0];for(let e=1;e{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0];for(let n=1;n{let t=e[0];for(let n=1;n1)throw new Cp("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Cr((()=>Ed(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new Cp("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[s]||null==e[s]){n[s]=null;break}n[s]+=e[s]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new Cp("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Cp("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new Cp(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return Cr((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const s=[];for(let n=0;n"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Sp("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new Cp(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(2!==e.length)throw new Cp(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],s=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>dy(t,e[n].shape.length))):[dy(this.axes,n.shape.length),dy(this.axes,s.shape.length)],this.normalize&&(n=Wf(n,t[0]),s=Wf(s,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Sp("batchDot is not implemented for tensors of 4D or higher rank yet");if(E(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),E(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`)),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new Sp("batchDot is not implemented for complex64-type Tensors yet.");const s=e.shape.length,a=t.shape.length;null==n&&(n=[s-1,a-2]);const r=n;return Cr((()=>{let n,i;if(s>a){n=s-a;const e=[];for(let t=0;ts){n=a-s;const t=[];for(let e=0;e0){let e;e=s>a?s+a-3:s-1;const t=[];for(let s=e;s"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Sp("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);const a=t.concat(n);return 1===a.length&&a.push(1),a}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}fy.className="Dot",Nr(fy);class my extends Cf{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return Cr((()=>{this.invokeCallHook(e,t);const n=mf(e);return Bd((()=>Fd(n.shape,0,this.stddev).add(n)),(()=>n),t.training||!1)}))}}my.className="GaussianNoise",Nr(my);class gy extends Cf{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return Cr((()=>{this.invokeCallHook(e,t);const n=mf(e);return this.rate>0&&this.rate<1?Bd((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return n.mul(Fd(n.shape,1,e))}),(()=>n),t.training||!1):n}))}}gy.className="GaussianDropout",Nr(gy);class yy extends Cf{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||mf(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return Cr((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e);return Bd((()=>{const t=mf(e),s=-1.7580993408473766;let a=Ri(go(n),this.rate);a=Id(a,"float32");const r=((1-this.rate)*(1+this.rate*s**2))**-.5,i=-r*s*this.rate;return t.mul(a).add(a.add(-1).mul(s)).mul(r).add(i)}),(()=>mf(e)),t.training||!1)}return e}))}}function by(e,t,n,s,a,r=.001){let i;if(2===e.rank)i=ni(e,t,n,s,a,r);else if(3===e.rank)i=si(e,t,n,s,a,r);else{if(4!==e.rank)throw new Sp(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=ai(e,t,n,s,a,r)}return i}yy.className="AlphaDropout",Nr(yy);class xy extends Cf{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=lf(e.betaInitializer||"zeros"),this.gammaInitializer=lf(e.gammaInitializer||"ones"),this.movingMeanInitializer=lf(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=lf(e.movingVarianceInitializer||"ones"),this.betaConstraint=sd(e.betaConstraint),this.gammaConstraint=sd(e.gammaConstraint),this.betaRegularizer=ug(e.betaRegularizer),this.gammaRegularizer=ug(e.gammaRegularizer)}build(e){e=gf(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Cp(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new kf({ndim:e.length,axes:{[t]:n}})];const s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return Cr((()=>{const n=null!=t.training&&t.training,s=mf(e),a=s.shape,r=a.length,i=Nd(0,r),o=this.axis>=0?this.axis:this.axis+r;i.splice(o,1);const l=Ep(1,r);l[o]=a[o];const u=i.slice();u.sort();const c=!_(u,Nd(0,r).slice(0,r-1));if(!n)return(()=>{if(c){const e=this.movingMean.read().reshape(l),t=this.movingVariance.read().reshape(l),n=this.center?this.beta.read().reshape(l):null,a=this.scale?this.gamma.read().reshape(l):null;return by(s,e,t,n,a,this.epsilon)}return by(s,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,p,d]=function(e,t,n,s,a=.001){return _(s.slice().sort(),Nd(0,e.rank-1))?function(e,t,n,s,a=.001){return Cr((()=>{const r=no(e,s),i=r.mean,o=r.variance;return[by(e,i,o,n,t,a),i,o]}))}(e,t,n,s,a):function(e,t,n,s,a=.001){return Cr((()=>{const r=no(e,s),i=r.mean,o=r.variance,l=[];for(const t of Nd(0,e.rank))-1!==s.indexOf(t)?l.push(1):l.push(e.shape[t]);const u=i.reshape(l),c=o.reshape(l),h=null==t?null:t.reshape(l),p=null==n?null:n.reshape(l);return[by(e,u,c,p,h,a),i,o]}))}(e,t,n,s,a)}(s,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(e,t,n)=>{Cr((()=>{const s=1-n,a=e.read(),r=a.sub(t).mul(s);e.write(a.sub(r))}))};return(()=>{f(this.movingMean,p,this.momentum),f(this.movingVariance,d,this.momentum)})(),h}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:of(this.betaInitializer),gammaInitializer:of(this.gammaInitializer),movingMeanInitializer:of(this.movingMeanInitializer),movingVarianceInitializer:of(this.movingVarianceInitializer),betaRegularizer:og(this.betaRegularizer),gammaRegularizer:og(this.gammaRegularizer),betaConstraint:td(this.betaConstraint),gammaConstraint:td(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}xy.className="BatchNormalization",Nr(xy);class wy extends Cf{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=lf(e.betaInitializer||"zeros"),this.gammaInitializer=lf(e.gammaInitializer||"ones"),this.betaRegularizer=ug(e.betaRegularizer),this.gammaRegularizer=ug(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=gf(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==Wp(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t]));this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,!0):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,!0):this.beta=null,this.built=!0}call(e,t){const n=mf(e),s=n.shape,a=s.length;return Cr((()=>{let{mean:e,variance:t}=no(n,this.axis,!0);const r=Ep(1,a);for(const e of this.axis)r[e]=s[e];const i=e=>null!=e&&e.shape.length!==a&&this.axis!==[a-1]?e.reshape(r):e;let o=i(this.gamma.read()),l=i(this.beta.read());const u=[],c=[];for(let e=0;e=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return Cr((()=>{return t=mf(e),n=this.padding,s=this.dataFormat,Cr((()=>{if(4!==t.rank)throw new Cp(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new Cp("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==s&&(s="channelsLast"),"channelsLast"!==s&&"channelsFirst"!==s)throw new Cp(`Unknown data format: ${s}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===s?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],uo(t,e)}));var t,n,s}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}function vy(e,t,n,s,a,r){return Cr((()=>{let i;cd(a),pd(r),hd(s),null==n&&(n=[1,1]),null==s&&(s="valid"),null==a&&(a="channelsLast"),null==r&&(r="max"),e=xg(e,a);const o="same"===s?"same":"valid";return i="max"===r?Wi(e,t,n,o):Qr(e,t,n,o),"channelsFirst"===a&&(i=Wo(i,[0,3,1,2])),i}))}function Ny(e,t,n,s,a,r){return Cr((()=>{let i;cd(a),pd(r),hd(s),null==n&&(n=[1,1,1]),null==s&&(s="valid"),null==a&&(a="channelsLast"),null==r&&(r="max"),e=wg(e,a);const o="same"===s?"same":"valid";return i="max"===r?Vi(e,t,n,o):ei(e,t,n,o),"channelsFirst"===a&&(i=Wo(i,[0,4,1,2,3])),i}))}ky.className="ZeroPadding2D",Nr(ky);class Iy extends Cf{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new Cp(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(Hp(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new Cp(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}Hp(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,hd(this.padding),this.inputSpec=[new kf({ndim:3})]}computeOutputShape(e){const t=yg((e=gf(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Cr((()=>{this.invokeCallHook(e,t),e=$d(mf(e),2);const n=this.poolingFunction(mf(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Ro(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class $y extends Iy{constructor(e){super(e)}poolingFunction(e,t,n,s,a){return cd(a),hd(s),vy(e,t,n,s,a,"max")}}$y.className="MaxPooling1D",Nr($y);class Cy extends Iy{constructor(e){super(e)}poolingFunction(e,t,n,s,a){return cd(a),hd(s),vy(e,t,n,s,a,"avg")}}Cy.className="AveragePooling1D",Nr(Cy);class Sy extends Cf{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new Cp(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Hp(this.poolSize,"poolSize"),Hp(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,cd(this.dataFormat),hd(this.padding),this.inputSpec=[new kf({ndim:4})]}computeOutputShape(e){e=gf(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=yg(t,this.poolSize[0],this.padding,this.strides[0]),n=yg(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return Cr((()=>(this.invokeCallHook(e,t),this.poolingFunction(mf(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Ty extends Sy{constructor(e){super(e)}poolingFunction(e,t,n,s,a){return cd(a),hd(s),vy(e,t,n,s,a,"max")}}Ty.className="MaxPooling2D",Nr(Ty);class Ey extends Sy{constructor(e){super(e)}poolingFunction(e,t,n,s,a){return cd(a),hd(s),vy(e,t,n,s,a,"avg")}}Ey.className="AveragePooling2D",Nr(Ey);class Ay extends Cf{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new Cp(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Hp(this.poolSize,"poolSize"),Hp(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,cd(this.dataFormat),hd(this.padding),this.inputSpec=[new kf({ndim:5})]}computeOutputShape(e){e=gf(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],s="channelsFirst"===this.dataFormat?e[4]:e[3];return t=yg(t,this.poolSize[0],this.padding,this.strides[0]),n=yg(n,this.poolSize[1],this.padding,this.strides[1]),s=yg(s,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return Cr((()=>(this.invokeCallHook(e,t),this.poolingFunction(mf(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Ry extends Ay{constructor(e){super(e)}poolingFunction(e,t,n,s,a){return cd(a),hd(s),Ny(e,t,n,s,a,"max")}}Ry.className="MaxPooling3D",Nr(Ry);class Fy extends Ay{constructor(e){super(e)}poolingFunction(e,t,n,s,a){return cd(a),hd(s),Ny(e,t,n,s,a,"avg")}}Fy.className="AveragePooling3D",Nr(Fy);class Dy extends Cf{constructor(e){super(e),this.inputSpec=[new kf({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Sp}}class _y extends Dy{constructor(e){super(e||{})}call(e,t){return Cr((()=>{const t=mf(e);return Gi(t,1)}))}}_y.className="GlobalAveragePooling1D",Nr(_y);class Oy extends Dy{constructor(e){super(e||{})}call(e,t){return Cr((()=>{const t=mf(e);return Oi(t,1)}))}}Oy.className="GlobalMaxPooling1D",Nr(Oy);class My extends Cf{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,cd(this.dataFormat),this.inputSpec=[new kf({ndim:4})]}computeOutputShape(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Sp}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Ly extends My{call(e,t){return Cr((()=>{const t=mf(e);return"channelsLast"===this.dataFormat?Gi(t,[1,2]):Gi(t,[2,3])}))}}Ly.className="GlobalAveragePooling2D",Nr(Ly);class zy extends My{call(e,t){return Cr((()=>{const t=mf(e);return"channelsLast"===this.dataFormat?Oi(t,[1,2]):Oi(t,[2,3])}))}}zy.className="GlobalMaxPooling2D",Nr(zy);class By extends Cf{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const s=Pf(t.layer,n);delete t.layer;const a={layer:s};return Object.assign(a,t),new e(a)}}class Py extends By{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=gf(e)).length<3)throw new Cp(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=gf(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return Cr((()=>_g(((e,n)=>[mf(this.layer.call(e,t)),[]]),e=mf(e),[],!1,null,null,!1,!0)[1]))}}Py.className="TimeDistributed",Nr(Py);class Wy extends By{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Pf(n),t.goBackwards=!0!==t.goBackwards;const s={};var a;if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=Pf(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,a=this.mergeMode,Up(ld,"BidirectionalMergeMode",a),e.weights)throw new Sp("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,s,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),a=a,this.returnState?(s=a.slice(1),t=a[0]):t=a[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(s).concat(s.slice()):[t].concat(s).concat(s.slice()):Fp(n)}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const a=Dg(e,n,s,this.numConstants);if(e=a.inputs,n=a.initialState,s=a.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==s)return super.apply(e,t);const r=[],i=[];if(null!=n){const e=n.length;if(e%2>0)throw new Cp("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,r.push(...n);const s=n.map((e=>new kf({shape:e.shape})));this.forwardLayer.stateSpec=s.slice(0,e/2),this.backwardLayer.stateSpec=s.slice(e/2),i.push(...s)}if(null!=s)throw new Sp("Support for constants in Bidirectional layers is not implemented yet.");const o=r[0]instanceof vf;for(const e of r)if(e instanceof vf!==o)throw new Cp("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(r),s=this.inputSpec.concat(i),a=this.inputSpec;this.inputSpec=s;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return Cr((()=>{const n=t.initialState;let s,a,r,i;if(null==n)s=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{const r=n.slice(0,n.length/2),i=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:r})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:i}))}return this.returnState&&(Array.isArray(s)&&(r=s.slice(1).concat(a.slice(1))),s=s[0],a=a[0]),this.returnSequences&&(a=bo(a,1)),"concat"===this.mergeMode?i=Ed([s,a]):"sum"===this.mergeMode?i=Or(s,a):"ave"===this.mergeMode?i=Mi(.5,Or(s,a)):"mul"===this.mergeMode?i=Mi(s,a):null==this.mergeMode&&(i=[s,a]),this.returnState?null==this.mergeMode?i.concat(r):[i].concat(r):i}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){fd(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),fd(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=Pf(t.layer);if(delete t.layer,null!=t.numConstants)throw new Sp("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}Wy.className="Bidirectional",Nr(Wy),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"}(Hg||(Hg={})),function(e){let t;!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}(jg||(jg={}));const Vy={};function Uy(e){return Vy[e]}function Gy(e,t,n,s,a){const r=t.inputParams[e];if(r&&void 0!==r.inputIndexStart){const e=r.inputIndexStart,i=0===r.inputIndexEnd?void 0:void 0===r.inputIndexEnd?e+1:r.inputIndexEnd;if("tensor"===r.type)return Hy(t.inputNames[r.inputIndexStart],n,s,a);if("tensors"===r.type)return t.inputNames.slice(e,i).map((e=>Hy(e,n,s,a)));const o=Hy(t.inputNames.slice(e)[0],n,s,a),l=o.dataSync();return"number"===r.type?l[0]:ee(o.shape,l)}const i=t.attrParams[e];return i&&i.value}function Hy(e,t,n,s){const[a,r]=qy(e);if(null!=s){const e=s.getHashTableHandleByName(a);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[Ky(a,e)]));return void 0!==i?t[Ky(a,i)][r]:void 0}function jy(e,t){const[n,s]=qy(e);return[Ky(n,t&&t.currentContextId),s]}function Ky(e,t){return t?`${e}-${t}`:e}function qy(e){const t=e.split(":");return 1===t.length?[e,0]:[t[0],Number(t[t.length-1])]}function Xy(e,t,n){let s=Gy("pad",e,t,n);if("explicit"===s){s=Gy("explicitPaddings",e,t,n);const a=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)a[e][0]=s[2*e],a[e][1]=s[2*e+1];return a}return s}function Yy(e){return e.kept?e:Ka(e)}const Jy=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Zy=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Qy=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}],eb=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number"}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],tb=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],nb=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],sb=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],ab=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],rb=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}],ib=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}],ob=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],lb=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],ub=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],cb=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],hb=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],pb=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],db=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]}];class fb{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[r,i,o,l,u,c,h,m,f,p,g,y,b,x,w,k,d].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}transformGraph(e,t={}){const n=e.node,s=[],a=[],r=[],i=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?s.push(e[t.name]):"Const"===t.op?a.push(e[t.name]):null!=t.input&&0!==t.input.length||r.push(e[t.name]),e)),{});let o=[];const l=[];let u={},c={};null!=t&&(u=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const h=Object.keys(i);h.forEach((e=>{const t=i[e];t.inputNames.forEach((e=>{const[n]=jy(e);t.inputs.push(i[n]),i[n].children.push(t)}))})),0===Object.keys(c).length?h.forEach((e=>{const t=i[e];0===t.children.length&&l.push(t)})):Object.keys(c).forEach((e=>{const[t]=jy(e),n=i[t];null!=n&&(n.signatureKey=c[e],l.push(n))})),Object.keys(u).length>0?Object.keys(u).forEach((e=>{const[t]=jy(e),n=i[t];n&&(n.signatureKey=u[e],o.push(n))})):o=s;let p={};null!=e.library&&null!=e.library.function&&(p=e.library.function.reduce(((e,t)=>(e[t.signature.name]=this.mapFunction(t),e)),{}));const d={nodes:i,inputs:o,outputs:l,weights:a,placeholders:s,signature:t,functions:p};return r.length>0&&(d.initNodes=r),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=Uy(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map((e=>e.startsWith("^")?e.substr(1):e)),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr};return null!=t.inputs&&(n.inputParams=t.inputs.reduce(((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e)),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce(((t,n)=>{const s=n.type;let a;switch(n.type){case"string":a=gb(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=gb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=Cb(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Cb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=bb(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=bb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=$b(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=$b(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=yb(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=yb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=Tb(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Tb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=Ib(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Ib(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Sb(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Sb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":a=kb(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=kb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":a=vb(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=vb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=wb(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=wb(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:a,type:s},t}),{})),n}mapFunction(e){const t=e.nodeDef,n=[];let s={};null!=t&&(s=t.reduce(((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e)),{}));const a=[],r=[];e.signature.inputArg.forEach((e=>{const[t]=jy(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:xb(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,a.push(n),s[t]=n})),Object.keys(s).forEach((e=>{const t=s[e];t.inputNames.forEach((e=>{const[n]=jy(e);t.inputs.push(s[n]),s[n].children.push(t)}))}));const i=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=jy(i[e.name]),a=s[t];null!=a&&(a.defaultOutput=n,r.push(a))}));const o=this.mapArgsToSignature(e);return{nodes:s,inputs:a,outputs:r,weights:n,placeholders:[],signature:o}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce(((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e)),{}),outputs:e.signature.outputArg.reduce(((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t)),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function mb(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=ue().global;if(void 0!==t.atob)return t.atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function gb(e,t,n,s=!1){const a=e[t];return null!=a?mb(a.s,s):n}function yb(e,t,n){const s=e[t];return s?s.b:n}function bb(e,t,n){const s=e[t]||{},a=null!=s.i?s.i:null!=s.f?s.f:n;return"number"==typeof a?a:parseInt(a,10)}function xb(e){switch("string"==typeof e&&(e=Hg[e]),e){case Hg.DT_FLOAT:return"float32";case Hg.DT_INT32:case Hg.DT_INT64:case Hg.DT_INT8:case Hg.DT_UINT8:return"int32";case Hg.DT_BOOL:return"bool";case Hg.DT_DOUBLE:return"float32";case Hg.DT_STRING:return"string";default:return null}}function wb(e,t,n){const s=e[t];return s&&s.func?s.func.name:n}function kb(e,t,n){const s=e[t];return s&&s.type?xb(s.type):n}function vb(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map((e=>xb(e))):n}function Nb(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function Ib(e,t,n){const s=e[t];return s&&s.shape?Nb(s.shape):n}function $b(e,t,n){const s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map((e=>"number"==typeof e?e:parseInt(e,10))):n}function Cb(e,t,n,s=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map((e=>mb(e,s))):n}function Sb(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map((e=>Nb(e))):n}function Tb(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n}class Eb{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map((e=>this.getInput(e))),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(((e,t)=>(e[t]=this.getAttr(t),e)),{}))}getInput(e){return Hy(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return Hy(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return bb(this.node.rawAttrs,e,t);if(null!=n.s)return gb(this.node.rawAttrs,e,t);if(null!=n.b)return yb(this.node.rawAttrs,e,t);if(null!=n.shape)return Ib(this.node.rawAttrs,e,t);if(null!=n.type)return kb(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return $b(this.node.rawAttrs,e,t);if(null!=n.list.s)return Cb(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Sb(this.node.rawAttrs,e,t);if(null!=n.list.b)return Tb(this.node.rawAttrs,e,t);if(null!=n.list.type)return vb(this.node.rawAttrs,e,t)}return t}}const Ab=la({addN_:function(e){E(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),E(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>ia(e,`tensors${t}`,"addN"))),n=t[0];t.forEach((e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((e=>{if(!_(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const s=t;return Zs.runKernel(be,s)}});function Rb(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){E(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let s=0;sn+` Shapes ${e} and ${t} must match`))}}}function Fb(e){return"number"!=typeof e&&!e.some((e=>e<0))}function Db(e,t,n){let s=_b(e,n);const a=!Fb(s);if(a&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(a&&t.forEach((e=>{s=_b(e.shape,s)})),!Fb(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function _b(e,t){if("number"==typeof e)return t;if("number"==typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let s=0;s=0&&r>=0&&a!==r)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[s]=a>=0?a:r}return n}class Ob{constructor(e,t,n,s,a,r,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=a,this.dynamicSize=r,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=Fr(0),Tr(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()})),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map((e=>this.read(e)))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),Rb(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Tr(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach(((e,n)=>this.write(e,t[n])))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,Lo(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const s=e.map((e=>(n+=e,n)));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const a=0===n?0:t.size/n,r=[];Cr((()=>{t=Zr(t,[1,n,a]);for(let n=0;n{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);Rb(t,e.shape,"TensorList shape mismatch: "),Tr(e)})),this.idTensor=Fr(0),this.maxNumElements=s,Tr(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Mb([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.id)||t.dispose()})),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Rb(e,this.elementShape,"TensorList shape mismatch: ");const s=Db(this.elementShape,this.tensors,e);return Cr((()=>{const e=this.tensors.map((e=>Zr(e,s)));return Fo(e,0)}))}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=Db(this.elementShape,this.tensors,e),s=this.tensors.pop();return Rb(s.shape,e,"TensorList shape mismatch: "),Zr(s,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Rb(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Tr(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);Rb(this.tensors[e].shape,t,"TensorList shape mismatch: ");const s=Db(this.elementShape,this.tensors,t);return Zr(this.tensors[e],s)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Rb(this.elementShape,t.shape,"TensorList shape mismatch: "),Tr(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Rb(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const s=Db(this.elementShape,this.tensors,n);return 0===e.length?ha([],[0].concat(s)):Cr((()=>{const t=e.map((e=>Zr(this.tensors[e],s)));return Fo(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Rb(this.elementShape,t,"TensorList shape mismatch: ");const n=Db(this.elementShape,this.tensors,t);return 0===this.size()?ha([],[0].concat(n)):Cr((()=>{const e=this.tensors.map((e=>Zr(e,n)));return ii(e,0)}))}}const Lb=la({maxPoolWithArgmax_:function(e,t,n,s,a=!1){const r={x:ia(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:a},o=Zs.runKernel(Kt,r,i);return{result:o[0],indexes:o[1]}}});function zb(e,t,n){const[s,a]=Gy("fusedOps",e,t,n),r="biasadd"===s,i="prelu"===a,o="fusedbatchnorm"===s,l=Gy("numArgs",e,t,n);if(r){if(i&&2!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(o)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");const u=Gy("strides",e,t,n),c=Xy(e,t,n),h=Gy("dataFormat",e,t,n).toUpperCase(),p=Gy("dilations",e,t,n),[d,f]=Gy("args",e,t,n);return{stride:u,pad:c,dataFormat:h,dilations:p,biasArg:d,preluArg:f,activationFunc:a,leakyreluAlpha:Gy("leakyreluAlpha",e,t,n)}}function Bb(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const s={start:e,stop:t,num:n};return Zs.runKernel(Dt,{},s)}const Pb=la({multinomial_:function(e,t,n,s=!1){const a=ia(e,"logits","multinomial"),r=a.size,i=a.rank;if(r<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${r}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();const o={logits:1===i?Zr(a,[1,-1]):a},l={numSamples:t,seed:n,normalized:s},u=Zs.runKernel(Qt,o,l);return 1===i?Zr(u,[u.size]):u}}),Wb=async function(e){const t=ia(e,"condition","whereAsync","bool"),n=await t.data(),s=Wu(t.shape,n);return e!==t&&t.dispose(),s};function Vb(e,t,n){return{boxes:Gy("boxes",e,t,n),scores:Gy("scores",e,t,n),maxOutputSize:Gy("maxOutputSize",e,t,n),iouThreshold:Gy("iouThreshold",e,t,n),scoreThreshold:Gy("scoreThreshold",e,t,n),softNmsSigma:Gy("softNmsSigma",e,t,n)}}class Ub{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Fr(0),this.tensorMap=new Map,Tr(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Fr(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),Cr((()=>{const e=Lo(t),s=n.length,a=e.length;E(s===a,(()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${a} elements.`));for(let t=0;t{const e=[];for(let s=0;s2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const a=e.rank>0?e.shape[0]:1,r=e.rank>1?e.shape[1]:1;if(n.length!==r)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${r}.`);const i=t.size;if(0!==t.rank&&(1!==t.rank||i!==a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,r,n,i);const o={sparseIndices:a,sparseValues:r,defaultValue:i},l={outputShape:n};return Zs.runKernel(Gn,o,l)}}),Hb=la({bincount_:function(e,t,n){const s=ia(e,"x","bincount"),a=ia(t,"weights","bincount");E("int32"===s.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`)),E(n>=0,(()=>`size must be non-negative, but got ${n}.`)),E(a.size===s.size||0===a.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${a.shape}.`));const r={x:s,weights:a},i={size:n};return Zs.runKernel(_e,r,i)}}),jb=la({denseBincount_:function(e,t,n,s=!1){const a=ia(e,"x","denseBincount"),r=ia(t,"weights","denseBincount");E("int32"===a.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`)),E(a.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`)),E(n>=0,(()=>`size must be non-negative, but got ${n}.`)),E(r.size===a.size||0===r.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${r.shape}.`));const i={x:a,weights:r},o={size:n,binaryOutput:s};return Zs.runKernel(Je,i,o)}}),Kb=la({scatterND_:function(e,t,n){const s=ia(e,"indices","scatterND","int32"),a=ia(t,"updates","scatterND");mu(a,s,n);const r={indices:s,updates:a},i={shape:n};return Zs.runKernel(Sn,r,i)}}),qb=la({gatherND_:function(e,t){const n=ia(t,"indices","gatherND","int32"),s={params:ia(e,"x","gatherND"),indices:n};return Zs.runKernel(kt,s)}});function Xb(e,t,n,s){const a=((e,t,n)=>{switch(e.category){case"arithmetic":return Cr((()=>((e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[Or(Gy("a",e,t,n),Gy("b",e,t,n))];case"AddN":return[Ab(Gy("tensors",e,t,n))];case"FloorMod":case"Mod":return[pp(Gy("a",e,t,n),Gy("b",e,t,n))];case"Mul":return[Mi(Gy("a",e,t,n),Gy("b",e,t,n))];case"RealDiv":case"Div":return[bi(Gy("a",e,t,n),Gy("b",e,t,n))];case"DivNoNan":return[ep(Gy("a",e,t,n),Gy("b",e,t,n))];case"FloorDiv":return[yi(Gy("a",e,t,n),Gy("b",e,t,n))];case"Sub":return[Li(Gy("a",e,t,n),Gy("b",e,t,n))];case"Minimum":return[ji(Gy("a",e,t,n),Gy("b",e,t,n))];case"Maximum":return[Ui(Gy("a",e,t,n),Gy("b",e,t,n))];case"Pow":return[Dl(Gy("a",e,t,n),Gy("b",e,t,n))];case"SquaredDifference":return[Wl(Gy("a",e,t,n),Gy("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return Cr((()=>((e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[_r(Gy("x",e,t,n))];case"Acos":return[Uh(Gy("x",e,t,n))];case"Acosh":return[Gh(Gy("x",e,t,n))];case"Asin":return[jh(Gy("x",e,t,n))];case"Asinh":return[Kh(Gy("x",e,t,n))];case"Atan":return[qh(Gy("x",e,t,n))];case"Atan2":return[Xh(Gy("x",e,t,n),Gy("y",e,t,n))];case"Atanh":return[Yh(Gy("x",e,t,n))];case"Ceil":return[Jh(Gy("x",e,t,n))];case"Complex":return[ua(Gy("real",e,t,n),Gy("imag",e,t,n))];case"Cos":return[Fh(Gy("x",e,t,n))];case"Cosh":return[_h(Gy("x",e,t,n))];case"Elu":return[xi(Gy("x",e,t,n))];case"Erf":return[np(Gy("x",e,t,n))];case"Exp":return[_i(Gy("x",e,t,n))];case"Expm1":return[sp(Gy("x",e,t,n))];case"Floor":return[Ti(Gy("x",e,t,n))];case"Log":return[Di(Gy("x",e,t,n))];case"Log1p":return[Vl(Gy("x",e,t,n))];case"Imag":return[Uo(Gy("x",e,t,n))];case"Neg":return[so(Gy("x",e,t,n))];case"Reciprocal":return[mp(Gy("x",e,t,n))];case"Real":return[Go(Gy("x",e,t,n))];case"Relu":return[yo(Gy("x",e,t,n))];case"Round":return[gp(Gy("x",e,t,n))];case"Selu":return[xo(Gy("x",e,t,n))];case"Sigmoid":return[ko(Gy("x",e,t,n))];case"Sin":return[bc(Gy("x",e,t,n))];case"Sign":return[yp(Gy("x",e,t,n))];case"Sinh":return[wc(Gy("x",e,t,n))];case"Softplus":return[To(Gy("x",e,t,n))];case"Sqrt":return[Ao(Gy("x",e,t,n))];case"Square":return[to(Gy("x",e,t,n))];case"Tanh":return[Do(Gy("x",e,t,n))];case"Tan":return[xp(Gy("x",e,t,n))];case"ClipByValue":return[ri(Gy("x",e,t,n),Gy("clipValueMin",e,t,n),Gy("clipValueMax",e,t,n))];case"Relu6":return[Yo(Gy("x",e,t,n))];case"Rsqrt":return[Dc(Hy(e.inputNames[0],t,n))];case"Prod":return[fp(Gy("x",e,t,n),Gy("axes",e,t,n))];case"LeakyRelu":return[Fi(Gy("x",e,t,n),Gy("alpha",e,t,n))];case"Prelu":return[co(Gy("x",e,t,n),Gy("alpha",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return(async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=Gy("thenBranch",e,t,n),a=Gy("elseBranch",e,t,n),r=Gy("cond",e,t,n),i=Gy("args",e,t,n);return(await r.data())[0]?n.functionMap[s].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[a].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const s=Gy("body",e,t,n),a=Gy("cond",e,t,n),r=Gy("args",e,t,n),i=await n.functionMap[a].executeFunctionAsync(r,n.tensorArrayMap,n.tensorListMap),o=r.map((e=>e.id));let l=await i[0].data();i.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||e.dispose()}));let u=r;for(;l[0];){const e=u;u=await n.functionMap[s].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);const t=u.map((e=>e.id));e.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}));const r=await n.functionMap[a].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await r[0].data(),r.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return u}case"LoopCond":return[Yy(Gy("pred",e,t,n))];case"Switch":{const s=Gy("pred",e,t,n);let a=Gy("data",e,t,n);return a.kept||(a=Yy(a)),(await s.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const s=e.inputNames.find((e=>void 0!==Hy(e,t,n)));return s?[Yy(Hy(s,t,n))]:void 0}case"Enter":{const s=Gy("frameName",e,t,n),a=Gy("tensor",e,t,n);return n.enterFrame(s),[Yy(a)]}case"Exit":{const s=Gy("tensor",e,t,n);return n.exitFrame(),[Yy(s)]}case"NextIteration":{const s=Gy("tensor",e,t,n);return n.nextIteration(),[Yy(s)]}case"TensorArrayV3":{const s=Gy("size",e,t,n),a=Gy("dtype",e,t,n),r=Gy("elementShape",e,t,n),i=Gy("dynamicSize",e,t,n),o=Gy("clearAfterRead",e,t,n),l=Gy("identicalElementShapes",e,t,n),u=Gy("name",e,t,n),c=new Ob(u,a,s,r,l,i,o);return n.addTensorArray(c),[c.idTensor,Fr(1)]}case"TensorArrayWriteV3":{const s=Gy("tensorArrayId",e,t,n),a=Gy("index",e,t,n),r=Gy("tensor",e,t,n),i=n.getTensorArray(s.id);return i.write(a,r),[i.idTensor]}case"TensorArrayReadV3":{const s=Gy("tensorArrayId",e,t,n),a=Gy("index",e,t,n);return[n.getTensorArray(s.id).read(a)]}case"TensorArrayGatherV3":{const s=Gy("tensorArrayId",e,t,n),a=Gy("indices",e,t,n),r=Gy("dtype",e,t,n);return[n.getTensorArray(s.id).gather(a,r)]}case"TensorArrayScatterV3":{const s=Gy("tensorArrayId",e,t,n),a=Gy("indices",e,t,n),r=Gy("tensor",e,t,n),i=n.getTensorArray(s.id);return i.scatter(a,r),[i.idTensor]}case"TensorArrayConcatV3":{const s=Gy("tensorArrayId",e,t,n),a=n.getTensorArray(s.id),r=Gy("dtype",e,t,n);return[a.concat(r)]}case"TensorArraySplitV3":{const s=Gy("tensorArrayId",e,t,n),a=Gy("tensor",e,t,n),r=Gy("lengths",e,t,n),i=n.getTensorArray(s.id);return i.split(r,a),[i.idTensor]}case"TensorArraySizeV3":{const s=Gy("tensorArrayId",e,t,n);return[Fr(n.getTensorArray(s.id).size(),"int32")]}case"TensorArrayCloseV3":{const s=Gy("tensorArrayId",e,t,n),a=n.getTensorArray(s.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const s=Gy("tensorListId",e,t,n),a=Gy("index",e,t,n),r=Gy("tensor",e,t,n),i=n.getTensorList(s.id);return i.setItem(a,r),[i.idTensor]}case"TensorListGetItem":{const s=Gy("tensorListId",e,t,n),a=Gy("index",e,t,n),r=Gy("elementShape",e,t,n),i=Gy("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(a,r,i)]}case"TensorListScatterV2":case"TensorListScatter":{const s=Gy("indices",e,t,n),a=function(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const a=Math.max(...t);if(null!=s&&-1!==s&&a>=s)throw new Error(`Max index must be < array size (${a} vs. ${s})`);const r=new Mb([],n,e.dtype,s),i=Lo(e,0);return t.forEach(((e,t)=>{r.setItem(e,i[t])})),r}(Gy("tensor",e,t,n),s,Gy("elementShape",e,t,n),Gy("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const s=Gy("elementShape",e,t,n),a=Gy("elementDType",e,t,n);let r;r="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=function(e,t,n){return new Mb([],e,t,n)}(s,a,Gy(r,e,t,n));return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const s=Gy("tensorListId",e,t,n),a=Gy("indices",e,t,n),r=Gy("elementShape",e,t,n),i=Gy("elementDType",e,t,n);return[n.getTensorList(s.id).gather(a,i,r)]}case"TensorListStack":{const s=Gy("tensorListId",e,t,n),a=Gy("elementShape",e,t,n),r=Gy("elementDType",e,t,n),i=Gy("numElements",e,t,n);return[n.getTensorList(s.id).stack(a,r,i)]}case"TensorListFromTensor":{const s=function(e,t,n){const s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);Rb(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=Lo(e);return new Mb(a,t,s)}(Gy("tensor",e,t,n),Gy("elementShape",e,t,n),Gy("elementDType",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListConcat":{const s=Gy("tensorListId",e,t,n),a=n.getTensorList(s.id),r=Gy("dtype",e,t,n),i=Gy("elementShape",e,t,n);return[a.concat(r,i)]}case"TensorListPushBack":{const s=Gy("tensorListId",e,t,n),a=Gy("tensor",e,t,n),r=n.getTensorList(s.id);return r.pushBack(a),[r.idTensor]}case"TensorListPopBack":{const s=Gy("tensorListId",e,t,n),a=Gy("elementShape",e,t,n),r=Gy("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(a,r)]}case"TensorListSplit":{const s=Gy("tensor",e,t,n),a=Gy("elementShape",e,t,n),r=function(e,t,n){let s=0;const a=t.map((e=>(s+=e,s)));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${s}, and tensor's shape is: ${e.shape}`);const r=_b(e.shape.slice(1),n),i=0===s?0:e.size/s,o=Cr((()=>{const n=[];e=Zr(e,[1,s,i]);for(let s=0;s((e,t,n)=>{switch(e.op){case"Conv1D":{const s=Gy("stride",e,t,n),a=Gy("pad",e,t,n),r=Gy("dataFormat",e,t,n).toUpperCase(),i=Gy("dilation",e,t,n);return[pi(Gy("x",e,t,n),Gy("filter",e,t,n),s,a,r,i)]}case"Conv2D":{const s=Gy("strides",e,t,n),a=Xy(e,t,n),r=Gy("dataFormat",e,t,n).toUpperCase(),i=Gy("dilations",e,t,n);return[hi(Gy("x",e,t,n),Gy("filter",e,t,n),[s[1],s[2]],a,r,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:s,pad:a,dataFormat:r,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:c}=zb(e,t,n);return[nl({x:Gy("x",e,t,n),filter:Gy("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:r,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:a,dataFormat:r,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:c}=zb(e,t,n);return[rl({x:Gy("x",e,t,n),filter:Gy("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:r,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=Gy("outputShape",e,t,n),a=Gy("strides",e,t,n),r=Xy(e,t,n);return[fi(Gy("x",e,t,n),Gy("filter",e,t,n),s,[a[1],a[2]],r)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const s=Gy("strides",e,t,n),a=Xy(e,t,n),r=Gy("dilations",e,t,n),i=Gy("dataFormat",e,t,n).toUpperCase();return[gi(Gy("input",e,t,n),Gy("filter",e,t,n),[s[1],s[2]],a,i,[r[1],r[2]])]}case"Conv3D":{const s=Gy("strides",e,t,n),a=Gy("pad",e,t,n),r=Gy("dataFormat",e,t,n).toUpperCase(),i=Gy("dilations",e,t,n);return[mi(Gy("x",e,t,n),Gy("filter",e,t,n),[s[1],s[2],s[3]],a,r,[i[1],i[2],i[3]])]}case"AvgPool":{const s=Gy("strides",e,t,n),a=Gy("pad",e,t,n),r=Gy("kernelSize",e,t,n);return[Qr(Gy("x",e,t,n),[r[1],r[2]],[s[1],s[2]],a)]}case"MaxPool":{const s=Gy("strides",e,t,n),a=Gy("pad",e,t,n),r=Gy("kernelSize",e,t,n);return[Wi(Gy("x",e,t,n),[r[1],r[2]],[s[1],s[2]],a)]}case"MaxPoolWithArgmax":{const s=Gy("strides",e,t,n),a=Gy("pad",e,t,n),r=Gy("kernelSize",e,t,n),i=Gy("includeBatchInIndex",e,t,n),{result:o,indexes:l}=Lb(Gy("x",e,t,n),[r[1],r[2]],[s[1],s[2]],a,i);return[o,l]}case"AvgPool3D":{const s=Gy("strides",e,t,n),a=Gy("pad",e,t,n),r=Gy("kernelSize",e,t,n);return[ei(Gy("x",e,t,n),[r[1],r[2],r[3]],[s[1],s[2],s[3]],a)]}case"MaxPool3D":{const s=Gy("strides",e,t,n),a=Gy("pad",e,t,n),r=Gy("kernelSize",e,t,n);return[Vi(Gy("x",e,t,n),[r[1],r[2],r[3]],[s[1],s[2],s[3]],a)]}case"Dilation2D":{const s=Gy("strides",e,t,n),a=Gy("pad",e,t,n),r=Gy("dilations",e,t,n),i=s[1],o=s[2],l=r[1],u=r[2];return[Qh(Gy("x",e,t,n),Gy("filter",e,t,n),[i,o],a,[l,u],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return Cr((()=>((e,t,n)=>{switch(e.op){case"Fill":{const s=Gy("shape",e,t,n),a=Gy("dtype",e,t,n);return[Si(s,Gy("value",e,t,n),a)]}case"LinSpace":return[Bb(Gy("start",e,t,n),Gy("stop",e,t,n),Gy("num",e,t,n))];case"Multinomial":{const s=Gy("logits",e,t,n),a=Gy("numSamples",e,t,n),r=Gy("seed",e,t,n);return[Pb(s,a,r)]}case"OneHot":{const s=Gy("indices",e,t,n),a=Gy("depth",e,t,n),r=Gy("onValue",e,t,n),i=Gy("offValue",e,t,n);return[ro(s,a,r,i)]}case"Ones":return[oo(Gy("shape",e,t,n),Gy("dtype",e,t,n))];case"OnesLike":return[lo(Gy("x",e,t,n))];case"RandomUniform":return[go(Gy("shape",e,t,n),Gy("minval",e,t,n),Gy("maxval",e,t,n),Gy("dtype",e,t,n))];case"Range":return[Rl(Gy("start",e,t,n),Gy("stop",e,t,n),Gy("step",e,t,n),Gy("dtype",e,t,n))];case"TruncatedNormal":{const s=Gy("shape",e,t,n),a=Gy("mean",e,t,n),r=Gy("stdDev",e,t,n),i=Gy("seed",e,t,n);return[Mo(s,a,r,Gy("dtype",e,t,n),i)]}case"Zeros":return[io(Gy("shape",e,t,n),Gy("dtype",e,t,n))];case"ZerosLike":return[Po(Gy("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"dynamic":return(async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:a,maxOutputSize:r,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=Vb(e,t,n),u=await Gl.nonMaxSuppressionWithScoreAsync(s,a,r,i,o,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:s,scores:a,maxOutputSize:r,iouThreshold:i,scoreThreshold:o}=Vb(e,t,n),l=Gy("padToMaxOutputSize",e,t,n),u=await Gl.nonMaxSuppressionPaddedAsync(s,a,r,i,o,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:s,scores:a,maxOutputSize:r,iouThreshold:i,scoreThreshold:o}=Vb(e,t,n);return[await Gl.nonMaxSuppressionAsync(s,a,r,i,o)]}case"Where":{const s=ja(Gy("condition",e,t,n),"bool"),a=[await Wb(s)];return s.dispose(),a}case"ListDiff":return async function(e,t){const n=ia(e,"x","setdiff1d"),s=ia(t,"y","setdiff1d");E(n.dtype===s.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`)),E(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),E(1===s.rank,(()=>`y should be 1D tensor, but got y (${s.shape}).`));const a=await n.data(),r=await s.data(),i=new Set(r);let o=0;for(let e=0;e((e,t,n)=>{switch(e.op){case"TopKV2":{const s=Gy("x",e,t,n),a=Gy("k",e,t,n),r=Gy("sorted",e,t,n),i=wp(s,a,r);return[i.values,i.indices]}case"Unique":{const s=Gy("x",e,t,n),a=kp(s);return[a.values,a.indices]}case"UniqueV2":{const s=Gy("x",e,t,n),a=Gy("axis",e,t,n),r=kp(s,a);return[r.values,r.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return Cr((()=>((e,t,n)=>{switch(e.op){case"ResizeBilinear":{const s=Gy("images",e,t,n),a=Gy("size",e,t,n),r=Gy("alignCorners",e,t,n),i=Gy("halfPixelCenters",e,t,n);return[Gl.resizeBilinear(s,[a[0],a[1]],r,i)]}case"ResizeNearestNeighbor":{const s=Gy("images",e,t,n),a=Gy("size",e,t,n),r=Gy("alignCorners",e,t,n),i=Gy("halfPixelCenters",e,t,n);return[Gl.resizeNearestNeighbor(s,[a[0],a[1]],r,i)]}case"CropAndResize":{const s=Gy("image",e,t,n),a=Gy("boxes",e,t,n),r=Gy("boxInd",e,t,n),i=Gy("cropSize",e,t,n),o=Gy("method",e,t,n),l=Gy("extrapolationValue",e,t,n);return[Gl.cropAndResize(s,a,r,i,o,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return Cr((()=>((e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=Gy("default",e,t,n);return[Hy(e.name,t,n)||s];case"Placeholder":return[Hy(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[Yy(Gy("x",e,t,n))];case"IdentityN":return Gy("x",e,t,n).map((e=>Yy(e)));case"Snapshot":return[Yy(Gy("x",e,t,n))];case"Shape":return[_o(Gy("x",e,t,n).shape,"int32")];case"ShapeN":return Gy("x",e,t,n).map((e=>_o(e.shape)));case"Size":return[Fr(Gy("x",e,t,n).size,"int32")];case"Rank":return[Fr(Gy("x",e,t,n).rank,"int32")];case"NoOp":return[Fr(1)];case"Print":const a=Gy("x",e,t,n),r=Gy("data",e,t,n),i=Gy("message",e,t,n),o=Gy("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let e=0;e((e,t,n)=>{switch(e.op){case"Equal":return[Ni(Gy("a",e,t,n),Gy("b",e,t,n))];case"NotEqual":return[ao(Gy("a",e,t,n),Gy("b",e,t,n))];case"Greater":return[Ai(Gy("a",e,t,n),Gy("b",e,t,n))];case"GreaterEqual":return[Ri(Gy("a",e,t,n),Gy("b",e,t,n))];case"Less":return[Zc(Gy("a",e,t,n),Gy("b",e,t,n))];case"LessEqual":return[Al(Gy("a",e,t,n),Gy("b",e,t,n))];case"LogicalAnd":return[Pi(Gy("a",e,t,n),Gy("b",e,t,n))];case"LogicalNot":return[Sh(Gy("a",e,t,n))];case"LogicalOr":return[up(Gy("a",e,t,n),Gy("b",e,t,n))];case"Select":case"SelectV2":return[Bo(Gy("condition",e,t,n),Gy("a",e,t,n),Gy("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return Cr((()=>((e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[il(Gy("a",e,t,n),Gy("b",e,t,n),Gy("transposeA",e,t,n),Gy("transposeB",e,t,n))];case"Transpose":return[Wo(Gy("x",e,t,n),Gy("perm",e,t,n))];case"_FusedMatMul":const[s,a]=Gy("fusedOps",e,t,n),r="biasadd"===s,i="prelu"===a,o=Gy("numArgs",e,t,n),l=Gy("leakyreluAlpha",e,t,n);if(r){if(i&&2!==o)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==o)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[u,c]=Gy("args",e,t,n);return[ol({a:Gy("a",e,t,n),b:Gy("b",e,t,n),transposeA:Gy("transposeA",e,t,n),transposeB:Gy("transposeB",e,t,n),bias:u,activation:a,preluActivationWeights:c,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return Cr((()=>((e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[ti(Gy("x",e,t,n),Gy("mean",e,t,n),Gy("variance",e,t,n),Gy("offset",e,t,n),Gy("scale",e,t,n),Gy("epsilon",e,t,n))];case"LRN":return[op(Gy("x",e,t,n),Gy("radius",e,t,n),Gy("bias",e,t,n),Gy("alpha",e,t,n),Gy("beta",e,t,n))];case"Softmax":return[So(Gy("x",e,t,n))];case"LogSoftmax":return[Bi(Gy("x",e,t,n))];case"SparseToDense":return[Gb(Gy("sparseIndices",e,t,n),Gy("outputShape",e,t,n),Gy("sparseValues",e,t,n),Gy("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return Cr((()=>((e,t,n)=>{switch(e.op){case"Max":{const s=Gy("axis",e,t,n),a=Gy("keepDims",e,t,n);return[Oi(Gy("x",e,t,n),s,a)]}case"Mean":{const s=Gy("axis",e,t,n),a=Gy("keepDims",e,t,n);return[Gi(Gy("x",e,t,n),s,a)]}case"Min":{const s=Gy("axis",e,t,n),a=Gy("keepDims",e,t,n);return[Hi(Gy("x",e,t,n),s,a)]}case"Sum":{const s=Gy("axis",e,t,n),a=Gy("keepDims",e,t,n);return[zi(Gy("x",e,t,n),s,a)]}case"All":{const s=Gy("axis",e,t,n),a=Gy("keepDims",e,t,n);return[Mr(Gy("x",e,t,n),s,a)]}case"Any":{const s=Gy("axis",e,t,n),a=Gy("keepDims",e,t,n);return[Lr(Gy("x",e,t,n),s,a)]}case"ArgMax":{const s=Gy("axis",e,t,n);return[zr(Gy("x",e,t,n),s)]}case"ArgMin":{const s=Gy("axis",e,t,n);return[Hh(Gy("x",e,t,n),s)]}case"Prod":{const s=Gy("axis",e,t,n),a=Gy("keepDims",e,t,n);return[fp(Gy("x",e,t,n),s,a)]}case"Cumsum":{const s=Gy("axis",e,t,n),a=Gy("exclusive",e,t,n),r=Gy("reverse",e,t,n);return[vc(Gy("x",e,t,n),s,a,r)]}case"Bincount":const s=Gy("x",e,t,n),a=Gy("weights",e,t,n),r=Gy("size",e,t,n);return[Hb(s,a,r)];case"DenseBincount":{const s=Gy("x",e,t,n),a=Gy("weights",e,t,n),r=Gy("size",e,t,n),i=Gy("binaryOutput",e,t,n);return[jb(s,a,r,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return Cr((()=>((e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{const s=Gy("n",e,t,n),a=Gy("axis",e,t,n);let r=Gy("tensors",e,t,n);return r=r.slice(0,s),[ii(r,a)]}case"Gather":{const s=Gy("x",e,t,n),a=Gy("indices",e,t,n);return[Ei(s,ja(a,"int32"),0)]}case"GatherV2":{const s=Gy("axis",e,t,n),a=Gy("batchDims",e,t,n),r=Gy("x",e,t,n),i=Gy("indices",e,t,n);return[Ei(r,ja(i,"int32"),s,a)]}case"Reverse":{const s=Gy("dims",e,t,n),a=[];for(let e=0;e{const s=Gy("axis",e,t,n),a=Gy("tensors",e,t,n),r=a[0].shape,i=Ro(a[0]).shape,o=a.map((e=>{const t=_(e.shape,r);if(!t&&!_(Ro(e).shape,i))throw new Error("the input tensors shape does not match");return t?e:Zr(e,r)}));return[Fo(o,s)]}));case"Unpack":{const s=Gy("axis",e,t,n),a=Gy("tensor",e,t,n);return Lo(a,s)}case"Tile":{const s=Gy("reps",e,t,n);return[$i(Gy("x",e,t,n),s)]}case"Split":case"SplitV":{const s=Gy("axis",e,t,n),a=Gy("numOrSizeSplits",e,t,n),r=Gy("x",e,t,n);return Eo(r,a,s)}case"ScatterNd":{const s=Gy("indices",e,t,n),a=Gy("values",e,t,n),r=Gy("shape",e,t,n);return[Kb(s,a,r)]}case"GatherNd":{const s=Gy("x",e,t,n),a=Gy("indices",e,t,n);return[qb(s,a)]}case"SparseToDense":{const s=Gy("sparseIndices",e,t,n),a=Gy("outputShape",e,t,n),r=Gy("sparseValues",e,t,n),i=Gy("defaultValue",e,t,n);return[Gb(s,r,a,r.dtype===i.dtype?i:ja(i,r.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return Cr((()=>((e,t,n)=>{switch(e.op){case"FFT":return[Ho(Gy("x",e,t,n))];case"IFFT":return[Ko(Gy("x",e,t,n))];case"RFFT":return[jo(Gy("x",e,t,n))];case"IRFFT":return[qo(Gy("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return Cr((()=>((e,t,n)=>{switch(e.op){case"Cast":return[ja(Gy("x",e,t,n),Gy("dtype",e,t,n))];case"ExpandDims":{const s=Gy("axis",e,t,n);return[Ii(Gy("x",e,t,n),s)]}case"Squeeze":{const s=Gy("axis",e,t,n);return[Ro(Gy("x",e,t,n),s)]}case"Reshape":return[Zr(Gy("x",e,t,n),Gy("shape",e,t,n))];case"MirrorPad":return[hp(Gy("x",e,t,n),Gy("padding",e,t,n),Gy("mode",e,t,n))];case"PadV2":case"Pad":return[uo(Gy("x",e,t,n),Gy("padding",e,t,n),Gy("constantValue",e,t,n))];case"SpaceToBatchND":{const s=Gy("blockShape",e,t,n),a=Gy("paddings",e,t,n);return[rc(Gy("x",e,t,n),s,a)]}case"BatchToSpaceND":{const s=Gy("blockShape",e,t,n),a=Gy("crops",e,t,n);return[Bh(Gy("x",e,t,n),s,a)]}case"DepthToSpace":{const s=Gy("blockSize",e,t,n),a=Gy("dataFormat",e,t,n).toUpperCase();return[Zh(Gy("x",e,t,n),s,a)]}case"BroadcastTo":return[zo(Gy("x",e,t,n),Gy("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"hash_table":return(async(e,t,n,s)=>{switch(e.op){case"HashTable":case"HashTableV2":{const a=Gy("keyDType",e,t,n),r=Gy("valueDType",e,t,n),i=new Ub(a,r);return s.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{const a=Gy("tableHandle",e,t,n,s),r=Gy("keys",e,t,n),i=Gy("values",e,t,n),o=s.getHashTableById(a.id);return[await o.import(r,i)]}case"LookupTableFind":case"LookupTableFindV2":{const a=Gy("tableHandle",e,t,n,s),r=Gy("keys",e,t,n),i=Gy("defaultValue",e,t,n),o=s.getHashTableById(a.id);return[await o.find(r,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=Gy("tableHandle",e,t,n,s);return[s.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,s);case"custom":const a=Uy(e.op);if(a&&a.customExecutor)return a.customExecutor(new Eb(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return oe(a)?a.then((e=>[].concat(e))):[].concat(a)}class Yb{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`)).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function Jb(e,t,n,s){const a=new Set,r=[];let i=null,o=null;const l=new Set,u=Object.keys(e).map((e=>qy(e)[0]));let c=[];null!=s&&(c=s.map((e=>qy(e.name)[0])));const h=[...t];for(;h.length>0;){const e=h.pop();(tx(e)||nx(e)||sx(e))&&null==i&&(i=e,o=i.children.map((e=>e.name)).filter((e=>a.has(e)))),a.add(e.name),null==n[e.name]&&-1===u.indexOf(e.name)&&-1===c.indexOf(e.name)&&(0!==e.inputs.length?e.inputs.forEach((e=>{l.has(e.name)||(l.add(e.name),h.push(e))})):r.push(e.name))}return{inputs:e,outputs:t,usedNodes:a,missingInputs:r,dynamicNode:i,syncInputs:o}}const Zb=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],Qb=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],ex=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function tx(e){return Zb.indexOf(e.op)>=0}function nx(e){return Qb.indexOf(e.op)>=0}function sx(e){return ex.indexOf(e.op)>=0}class ax{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach((t=>{this._functionExecutorMap[t]=new ax(e.functions[t],this)}))}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map((t=>e[t].map((e=>e.id))));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get outputs(){return this._outputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get inputNodes(){return this._inputs.map((e=>e.signatureKey||e.name))}get outputNodes(){return this._outputs.map((e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t}))}get functions(){return Object.keys(this._functions).reduce(((e,t)=>(e[t]=this._functions[t].signature,e)),{})}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),s=t.map((e=>e.name)).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){const n=Jb(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:a,syncInputs:r}=n;if(null!=a)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${r}]`);if(s.length>0){const n=t.map((e=>e.name)),a=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${a}]. Missing the following inputs: [${s}]`)}return function(e,t,n){const{usedNodes:s,inputs:a}=n,r=[],i=Object.keys(a).map((e=>qy(e)[0])).map((t=>e.nodes[t])),o=e.initNodes;i.forEach((e=>{s.has(e.name)&&r.push(e)})),e.weights.forEach((e=>{s.has(e.name)&&r.push(e)})),null!=o&&o.forEach((e=>{s.has(e.name)&&r.push(e)}));const l=new Set,u=[];for(;r.length>0;){const e=r.pop();l.add(e.name),t[e.name]||u.push(e),e.children.forEach((e=>{!l.has(e.name)&&s.has(e.name)&&e.inputs.every((e=>l.has(e.name)))&&r.push(e)}))}return u}(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const s=n.map((e=>this.graph.nodes[qy(e)[0]])),a=t.map((e=>qy(e)[0]));let r=a.map((e=>this.graph.nodes[e]));0===r.length&&(r=this._outputs);const i=this.getCompilationKey(s,r);let o=this.compiledMap.get(i);null==o&&(o=this.compile(e,r),this.compiledMap.set(i,o));const l={},u={};return Cr((()=>{const n=new Yb(this.weightMap,l,u,this.functionExecutorMap),s=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,a]=qy(t),r=[];r[a]=e[t],s[n]=r}));const r=this.getFrozenTensorIds(s),i={};for(let e=0;eHy(e,s,n)))}))}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map((t=>e[t])).map((e=>e.map((e=>e.id)))));return new Set(t)}checkTensorForDisposal(e,t,n,s,a,r,i){"control"!==t.category&&-1===r.indexOf(e)&&(n[e].forEach((e=>{null!=e&&(i[e.id]=(i[e.id]||0)+t.children.length)})),t.inputs.forEach((e=>{if("control"!==e.category){const t=function(e,t,n){return t[Ky(e,n.currentContextId)]}(e.name,n,s);null!=t&&t.forEach((e=>{if(e&&!a.has(e.id)){const t=i[e.id];1===t?(e.dispose(),delete i[e.id]):null!=t&&i[e.id]--}}))}})))}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,s={},a={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));const r=new Yb(this.weightMap,s,a,this.functionExecutorMap),i=await this.executeWithControlFlow(e,r,t,n),o=t.map((e=>Hy(e,i,r))),l=o.map((e=>e.id)),u=Object.keys(e).map((t=>e[t].id)),c=new Set([...l,...u,...this.weightIds]);return Object.keys(i).forEach((e=>{i[e].forEach((e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()}))})),null==this.parent&&r.dispose(c),o}async executeFunctionAsync(e,t,n){const s=e.reduce(((e,t,n)=>(e[this.inputs[n].name]=t,e)),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){const a=Object.keys(e),r=a.map((e=>this.graph.nodes[qy(e)[0]])),i=n.map((e=>qy(e)[0]));let o=i.map((e=>this.graph.nodes[e]));0===o.length&&(o=this._outputs);const{usedNodes:l,missingInputs:u,dynamicNode:c,syncInputs:h}=Jb(e,o,this.weightMap,this._initNodes),p=[...r,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),d=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,s]=qy(t),a=[];a[s]=e[t],d[n]=a}));const f={},m=this.getFrozenTensorIds(d),g={};for(;p.length>0;){const e=this.processStack(r,p,t,d,g,m,i,f,l);await Promise.all(e)}null!=c||s||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const y=o.filter((e=>!tx(e)&&!Hy(e.name,d,t))).map((e=>e.name));if(y.length>0){let e="";throw null!=c&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${a}]. Consider providing the following inputs: [${u}]. ${e}`)}return d}processStack(e,t,n,s,a,r,i,o,l){const u=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&Gy("isConstant",e.node,s,n)&&([c]=jy(e.node.name,n)),null==s[e.node.name]){const h=Xb(e.node,s,n,this._resourceManager);c||([c]=jy(e.node.name,n));const p=n.currentContext;oe(h)?u.push(h.then((u=>(s[c]=u,n.currentContext=p,this.checkTensorForDisposal(c,e.node,s,n,r,i,o),this.processChildNodes(e.node,t,n,s,a,l),u)))):(s[c]=h,this.checkTensorForDisposal(c,e.node,s,n,r,i,o),this.processChildNodes(e.node,t,n,s,a,l))}else this.processChildNodes(e.node,t,n,s,a,l)}return u}processChildNodes(e,t,n,s,a,r){e.children.forEach((e=>{const[i]=jy(e.name,n);!a[i]&&r.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!Hy(e,s,n)))&&(a[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!Hy(e,s,n)))&&(a[i]=!0,t.push({contexts:n.currentContext,node:e})))}))}dispose(){Object.keys(this.weightMap).forEach((e=>this.weightMap[e].forEach((e=>e.dispose()))))}checkInputShapeAndType(e){Object.keys(e).forEach((t=>{const n=e[t],[s]=qy(t),a=this.graph.nodes[s];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value;E(e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t)),(()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}a.attrParams.dtype&&a.attrParams.dtype.value&&E(n.dtype===a.attrParams.dtype.value,(()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){const t={};for(const n in e)null!=this._signature&&null!=this._signature.inputs&&null!=this._signature.inputs[n]?t[this._signature.inputs[n].name]=e[n]:t[n]=e[n];return t}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=qy(e);return null==this.graph.nodes[t]}));if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map((e=>null!=this._signature&&null!=this._signature.outputs&&null!=this._signature.outputs[e]?this._signature.outputs[e].name:e),{})}checkOutputs(e){e.forEach((e=>{const[t]=qy(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class rx{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}class ix{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",null==t&&(this.loadOptions={}),this.resourceManager=new rx}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=nr(e,this.loadOptions);else{const s=(t=e,n=this.loadOptions,wa.getLoadHandlers(t,n));if(0===s.length)s.push(nr(e,this.loadOptions));else if(s.length>1)throw new Error(`Found more than one (${s.length}) load handlers for URL '${[e]}'`);this.handler=s[0]}var t,n}async load(){if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n;n=null!=this.artifacts.userDefinedMetadata&&null!=this.artifacts.userDefinedMetadata.signature?this.artifacts.userDefinedMetadata.signature:this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const s=function(e,t){const n={};let s,a=0;for(const r of t){const t=r.name,i=r.dtype,o=r.shape,l=D(o);let u;if("quantization"in r){const n=r.quantization;if("uint8"===n.dtype||"uint16"===n.dtype){if(!("min"in n)||!("scale"in n))throw new Error(`Weight ${r.name} with quantization ${n.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==n.dtype)throw new Error(`Weight ${r.name} has unknown quantization dtype ${n.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==i)throw new Error(`Weight ${r.name} is quantized with ${n.dtype} which only supports weights of type float32 not ${i}.`)}const o=pa[n.dtype],c=e.slice(a,a+l*o),h="uint8"===n.dtype?new Uint8Array(c):new Uint16Array(c);if("float32"===i)if("uint8"===n.dtype||"uint16"===n.dtype){u=new Float32Array(h.length);for(let e=0;e1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof Ds||Array.isArray(e)))return e;if((e=Array.isArray(e)?e:[e]).length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce(((t,n,s)=>(t[n]=e[s],t)),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce(((t,n)=>(t[n]=[e[n]],t)),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}}function ox(e,t,n=new Map,s=new Set){if(null==e)return null;if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const a=t(e);if(a.recurse&&null!==a.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(a.recurse){if(hx(e)){const a=Array.isArray(e)?[]:{};s.add(e);for(const r in e){const i=ox(e[r],t,n,s);a[r]=i}return s.delete(e),a}throw new Error(`Can't recurse into non-iterable type: ${e}`)}return n.set(e,a.value),a.value}function lx(e,t=cx){return ux(e,t)}function ux(e,t,n=new Set){const s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");const a=t(e);if(a.recurse&&null!==a.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(a.recurse){if(hx(s)){const a=Array.isArray(s)?[]:{};n.add(s);for(const r in s){const s=ux(e.map((e=>e[r])),t,n);a[r]=s}return n.delete(s),a}throw new Error(`Can't recurse into non-iterable type: ${s}`)}return a.value}function cx(e){return null===e?null:hx(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}function hx(e){return null!=e&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||"object"==typeof e&&!(e instanceof Ds))}function px(e){return ox(e,dx)}function dx(e){return e instanceof Ds?{value:e.clone(),recurse:!1}:hx(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class fx{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,null==e)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return 0===this.length()}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class mx extends fx{constructor(){super(mx.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=2*this.capacity,t=new Array(e),n=this.length();for(let e=0;e!0===e))}rowMajorBatch(e,t=!0){return new vx(this,e,t)}columnMajorBatch(e,t=!0,n=cx){return this.rowMajorBatch(e,t).map((e=>lx(e,n)))}concatenate(e,t){return new Ex(new yx([this,e]),t)}take(e){return e<0||null==e?this:new kx(this,e)}skip(e){return e<0||null==e?this:new wx(this,e)}prefetch(e){return new Fx(this,e)}shuffle(e,t){return new Dx(this,e,t)}serial(){return new xx(this)}}class yx extends gx{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:px(e),done:!1}}}class bx extends gx{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class xx extends gx{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){return this.upstream.next()}}class wx extends gx{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;this.count++ Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class vx extends gx{constructor(e,t,n=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){const e=[];for(;e.length0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class Nx extends gx{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Sr(e.value)}}}class Ix extends gx{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=js(e.value),n=this.transform(e.value),s=js(n);for(const e of t)Hs(e,s)||e.dispose();return{value:n,done:!1}}}class $x extends gx{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class Cx extends gx{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=js(e.value),n=await this.transform(e.value),s=js(n);for(const e of t)Hs(e,s)||e.dispose();return{value:n,done:!1}}}class Sx extends gx{constructor(){super(),this.outputQueue=new mx,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;0===this.outputQueue.length();)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class Tx extends Sx{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=js(e.value),n=this.transform(e.value),s=js(n);this.outputQueue.pushAll(n);for(const e of t)Hs(e,s)||e.dispose();return!0}}class Ex extends gx{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,null==this.iterator){const e=await this.moreIterators.next();if(e.done)return{value:null,done:!0};this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var Ax,Rx;(Rx=Ax||(Ax={}))[Rx.FAIL=0]="FAIL",Rx[Rx.SHORTEST=1]="SHORTEST",Rx[Rx.LONGEST=2]="LONGEST";class Fx extends gx{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new fx(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class Dx extends Fx{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=ho.alea(n||bs().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(!t.done)return this.refill(),t;this.upstreamExhausted=!0}return{value:null,done:!0}}}class _x{constructor(){this.size=null}batch(e,t=!0){const n=this;let s;return E(e>0,(()=>`batchSize needs to be positive, but it is\n ${e}`)),s=this.size===1/0||null==this.size?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),Ox((async()=>(await n.iterator()).columnMajorBatch(e,t,Mx)),s)}concatenate(e){const t=this;let n;return n=this.size===1/0||e.size===1/0?1/0:null!=this.size&&null!=e.size?this.size+e.size:null,Ox((async()=>(await t.iterator()).concatenate(await e.iterator())),n)}filter(e){const t=this;let n;return n=this.size===1/0?1/0:null,Ox((async()=>(await t.iterator()).filter((t=>Cr((()=>e(t)))))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return Ox((async()=>(await t.iterator()).map((t=>Cr((()=>e(t)))))),this.size)}mapAsync(e){const t=this;return Ox((async()=>(await t.iterator()).mapAsync(e)),this.size)}prefetch(e){if(null==e)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return Ox((async()=>(await t.iterator()).prefetch(e)),this.size)}repeat(e){const t=this;let n;return n=null!=this.size&&e>0?this.size*e:0===e?0:null!=this.size&&(void 0===e||e<0)?1/0:null,Ox((async()=>{return n=(a=async()=>({value:await t.iterator(),done:!1}),new bx(a)).take(e),new Ex(n,s);var n,s,a}),n)}skip(e){const t=this;let n;return n=null!=this.size&&e>=0&&this.size>=e?this.size-e:null!=this.size&&(this.size(await t.iterator()).skip(e)),n)}shuffle(e,t,n=!0){if(null==e||e<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const s=this,a=ho.alea(t||bs().toString());return Ox((async()=>{let t=a.int32();return n&&(t+=a.int32()),(await s.iterator()).shuffle(e,t.toString())}),this.size)}take(e){const t=this;let n;return n=null!=this.size&&this.size>e?e:null!=this.size&&this.size<=e?this.size:null,Ox((async()=>(await t.iterator()).take(e)),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}function Ox(e,t=null){return new class extends _x{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function Mx(e){if(null===e)return null;return null==(t=e[0])||null===(n=t)||"object"!=typeof n&&"function"!=typeof n||Array.isArray(t)||"object"==typeof t&&t instanceof Ds||H(t)?{value:function(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ds?Fo(e):ha(e)}(e),recurse:!1}:{value:null,recurse:!0};var t,n}function Lx(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&E("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}_x.MAX_BUFFER_SIZE=1e4,Symbol("out"),Symbol("field"),Symbol("quote"),Symbol("quoteafterquote"),Symbol("quoteinquote");const zx=Wu;class Bx extends I{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new N(this,Ir())}nextDataId(){return Bx.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,ue().get("IS_NODE")&&$u("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================"));const s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if("string"===t&&null!=n&&n.length>0&&K(n[0])){const a=n.map((e=>xs(e)));s=this.write(a,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){this.data.get(e).refCount++}decRef(e){this.data.has(e)&&this.data.get(e).refCount--}move(e,t,n,s,a){this.data.set(e,{values:t,dtype:s,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);return"complex64"===t?Su(this.readSync(n.real.dataId),this.readSync(n.imag.dataId)):this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map((e=>ws(e)))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ha(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return Ir().makeTensorFromDataId(s,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=bs();return e(),{kernelMs:bs()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Lx([e],"where");const t=this.readSync(e.dataId);return zx(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function Px(e,t,n){return({inputs:s,attrs:a,backend:r})=>{const{x:i}=s;if(Lx(i,e),"string"===i.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=r,l=o.data.get(i.dataId).values,u=D(i.shape),c=n||i.dtype,h=U(c,u);for(let e=0;e{const{x:i}=s;if(Lx(i,e),"string"===i.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=r,l=o.data.get(i.dataId).values,u=n||i.dtype,c=t(l,u,a);return o.makeTensorInfo(i.shape,u,c)}}Bx.nextDataId=0,Ar("cpu",(()=>new Bx),1);const Vx=Px(ot,(e=>e>=0?e:Math.exp(e)-1)),Ux={kernelName:ot,backendName:"cpu",kernelFunc:Vx};function Gx(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const Hx={kernelName:It,backendName:"cpu",kernelFunc:Gx};function jx(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{alpha:r}=s;Lx([a],"leakyRelu");const i=D(a.shape),o=n.data.get(a.dataId).values,l=V("float32",i);for(let e=0;e{const i=vi(t,n),o=i.length,l=Z(i),u=V(r,D(i)),c=t.length,h=n.length,p=Z(t),d=Z(n),f=wi(t,i),m=wi(n,i);if(f.length+m.length===0)for(let t=0;tr[e]=0));const i=re(r,c,p),g=n.slice(-h);m.forEach((e=>g[e]=0));const y=re(g,h,d);u[t]=e(s[i],a[y])}return[u,i]}}const Xx=qx(((e,t)=>e<0?t*e:e));function Yx(e){const{inputs:t,backend:n}=e,{x:s,alpha:a}=t;Lx([s,a],"prelu");const r=n.data.get(s.dataId).values,i=n.data.get(a.dataId).values,[o,l]=Xx(s.shape,a.shape,r,i,s.dtype);return n.makeTensorInfo(l,s.dtype,o)}const Jx={kernelName:pn,backendName:"cpu",kernelFunc:Yx},Zx=Px(yn,(e=>Math.max(0,e))),Qx={kernelName:yn,backendName:"cpu",kernelFunc:Zx},ew=Px(Nn,(e=>Math.min(Math.max(0,e),6))),tw={kernelName:Nn,backendName:"cpu",kernelFunc:ew};function nw(e,t,n,s,a){if("linear"===n)return Gx({inputs:{x:t},backend:e});if("relu"===n)return Zx({inputs:{x:t},backend:e});if("elu"===n)return Vx({inputs:{x:t},backend:e});if("relu6"===n)return ew({inputs:{x:t},backend:e});if("prelu"===n)return Yx({inputs:{x:t,alpha:s},backend:e});if("leakyrelu"===n)return jx({inputs:{x:t},backend:e,attrs:{alpha:a}});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function sw(e){const{inputs:t,backend:n}=e,{real:s,imag:a}=t,r=n.data.get(s.dataId).values,i=n.data.get(a.dataId).values,o=n.makeTensorInfo(s.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",r),imag:n.makeTensorInfo(a.shape,"float32",i)},o}const aw={kernelName:ze,backendName:"cpu",kernelFunc:sw};function rw(e,t,n="float32"){if("complex64"===n)return sw({inputs:{real:rw(e,t,"float32"),imag:rw(e,t,"float32")},backend:e});const s=ne(D(t),n);return e.makeTensorInfo(t,n,s)}function iw(e){const{inputs:t,backend:n}=e,{input:s}=t,a=n.data.get(s.dataId).complexTensorInfos.real,r=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,r)}const ow={kernelName:mn,backendName:"cpu",kernelFunc:iw};function lw(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{dtype:r}=s;if("complex64"===r){if("complex64"===a.dtype)return Gx({inputs:{x:a},backend:n});const e=rw(n,a.shape,a.dtype),t=lw({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),s=sw({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),s}if("complex64"===a.dtype){const e=iw({inputs:{input:a},backend:n}),t=lw({inputs:{x:e},backend:n,attrs:{dtype:r}});return n.disposeIntermediateTensorInfo(e),t}if(!G(a.dtype,r)){const e=Gx({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:r}}if("int32"===r){const e=n.data.get(a.dataId).values,t=Int32Array.from(e);return n.makeTensorInfo(a.shape,"int32",t)}if("bool"===r){const e=n.data.get(a.dataId).values,t=ys([0],a.dtype),[s,r]=qx(((e,t)=>e!==t?1:0))(a.shape,[],e,t,"bool");return n.makeTensorInfo(r,"bool",s)}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${r}`)}const uw={kernelName:Oe,backendName:"cpu",kernelFunc:lw};function cw(e,t,n,s){return null==n?({inputs:n,backend:a})=>{const{a:r,b:i}=n,o=a;Lx([r,i],e);const l=o.data.get(r.dataId).values,u=o.data.get(i.dataId).values,c=s||r.dtype,[h,p]=t(r.shape,i.shape,l,u,c);return o.makeTensorInfo(p,c,h)}:({inputs:e,backend:a})=>{const{a:r,b:i}=e,o=a;if("complex64"===r.dtype||"complex64"===i.dtype){const e=lw({inputs:{x:r},backend:o,attrs:{dtype:"complex64"}}),t=o.data.get(e.dataId),s=t.complexTensorInfos.real,a=t.complexTensorInfos.imag,l=o.data.get(s.dataId).values,u=o.data.get(a.dataId).values,c=lw({inputs:{x:i},backend:o,attrs:{dtype:"complex64"}}),h=o.data.get(c.dataId),p=h.complexTensorInfos.real,d=h.complexTensorInfos.imag,f=o.data.get(p.dataId).values,m=o.data.get(d.dataId).values,[g,y,b]=n(r.shape,i.shape,l,u,f,m),x=o.makeTensorInfo(b,"float32",g),w=o.makeTensorInfo(b,"float32",y),k=sw({inputs:{real:x,imag:w},backend:o});return o.disposeIntermediateTensorInfo(e),o.disposeIntermediateTensorInfo(c),o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(w),k}{const e=o.data.get(r.dataId).values,n=o.data.get(i.dataId).values,a=s||r.dtype,[l,u]=t(r.shape,i.shape,e,n,a);return o.makeTensorInfo(u,a,l)}}}function hw(e){return(t,n,s,a,r,i)=>{const o=vi(t,n),l=D(o),u=o.length,c=Z(o),h=V("float32",l),p=V("float32",l),d=wi(t,o),f=wi(n,o),m=Su(s,a),g=Su(r,i),y=t.length,b=Z(t),x=n.length,w=Z(n);if(d.length+f.length===0)for(let t=0;ts[e]=0));const a=re(s,y,b),r=n.slice(-x);f.forEach((e=>r[e]=0));const i=re(r,x,w),o=e(m[2*a],m[2*a+1],g[2*i],g[2*i+1]);h[t]=o.real,p[t]=o.imag}return[h,p,o]}}const pw=qx(((e,t)=>e+t)),dw=hw(((e,t,n,s)=>({real:e+n,imag:t+s}))),fw=cw(ye,pw,dw),mw={kernelName:ye,backendName:"cpu",kernelFunc:fw};function gw(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{shape:r}=s,i=D(a.shape),o=B(r,i),l=D(o);E(i===l,(()=>`The new shape (${o}) has ${l} elements and the old shape (${a.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(a.dataId);const u=n.data.get(a.dataId);if(null!=u.complexTensorInfos){const e=u.complexTensorInfos.real,t=u.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:a.dataId,shape:o,dtype:a.dtype}}const yw={kernelName:bn,backendName:"cpu",kernelFunc:gw};function bw(e){const{inputs:t,backend:n,attrs:s}=e,{a,b:r}=t,{transposeA:i,transposeB:o}=s;Lx([a,r],"matMul");const l=a.shape.length,u=r.shape.length,c=i?a.shape[l-2]:a.shape[l-1],h=o?r.shape[u-1]:r.shape[u-2],p=i?a.shape[l-1]:a.shape[l-2],d=o?r.shape[u-2]:r.shape[u-1],f=a.shape.slice(0,-2),m=r.shape.slice(0,-2),g=D(f),y=D(m);E(l>=2&&u>=2&&(g===y||1===g||1===y),(()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${m}).`));const b=(g>y?a.shape.slice(0,-2):r.shape.slice(0,-2)).concat([p,d]);E(c===h,(()=>`Error in matMul: inner shapes (${c}) and (${h}) of Tensors with shapes ${a.shape} and ${r.shape} and transposeA=${i} and transposeB=${o} must match.`));const x=o?[y,d,h]:[y,h,d],w=gw({inputs:{x:a},backend:n,attrs:{shape:i?[g,c,p]:[g,p,c]}}),k=gw({inputs:{x:r},backend:n,attrs:{shape:x}}),v=i?w.shape[1]:w.shape[2],N=i?w.shape[2]:w.shape[1],I=o?k.shape[1]:k.shape[2],$=Math.max(g,y),C=n.data.get(w.dataId).values,S=n.data.get(k.dataId).values,T=Z(w.shape),A=Z(k.shape),[R,F,_]=i?[T[0],1,T[1]]:[T[0],T[1],1],[O,M,L]=o?[1,A[1],A[0]]:[A[1],1,A[0]],z=N*I,B=Ha([$,N,I],w.dtype),P=B.values,W=n.blockSize;for(let e=0;e<$;e++)for(let t=0;t{const{x:t}=e.inputs,n=e.backend;Lx(t,"abs");let s=new Float32Array(D(t.shape));return s=kw(n.data.get(t.dataId).values),n.makeOutput(s,t.shape,"float32")}},Nw=Px(me,(e=>Math.acos(e))),Iw={kernelName:me,backendName:"cpu",kernelFunc:Nw},$w=Px(ge,(e=>Math.acosh(e))),Cw={kernelName:ge,backendName:"cpu",kernelFunc:$w},Sw={kernelName:be,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,s=t;Lx(t,"addN");const a=s.map((e=>n.data.get(e.dataId).values)),r=Ha(s[0].shape,s[0].dtype),i=r.values;for(let e=0;en&&(n=a,s=e)}p[e]=s}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}},_w={kernelName:ve,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r}=s;Lx(a,"argMin");let i=P(r,a.shape);const o=Zi(i,a.shape.length);let l=a;const u=[];null!=o&&(l=Ew({inputs:{x:a},backend:n,attrs:{perm:o}}),u.push(l),i=eo(i.length,l.shape.length)),i=[i[0]],Ji("argMin",i,l.shape.length);const[c,h]=Xi(l.shape,i),p=ne(D(c),"int32"),d=D(h),f=n.data.get(l.dataId).values;for(let e=0;en.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}},Ow=Px(Ne,(e=>Math.asin(e))),Mw={kernelName:Ne,backendName:"cpu",kernelFunc:Ow},Lw=Px(Ie,(e=>Math.asinh(e))),zw={kernelName:Ie,backendName:"cpu",kernelFunc:Lw},Bw=Px($e,(e=>Math.atan(e))),Pw={kernelName:$e,backendName:"cpu",kernelFunc:Bw},Ww=qx(((e,t)=>Math.atan2(e,t))),Vw=cw(Se,Ww),Uw={kernelName:Se,backendName:"cpu",kernelFunc:Vw},Gw=Px(Ce,(e=>Math.atanh(e))),Hw={kernelName:Ce,backendName:"cpu",kernelFunc:Gw};function jw(e,t,n,s,a,r){const i=a.strideHeight,o=a.strideWidth,l=a.dilationHeight,u=a.dilationWidth,c=a.effectiveFilterHeight,h=a.effectiveFilterWidth,p=a.padInfo.top,d=a.padInfo.left,f="max"===r?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Ha(a.outShape,n),g=m.values,y=a.outShape[1]*a.outShape[2]*a.outShape[3],b=a.outShape[2]*a.outShape[3],x=a.outShape[3];for(let t=0;ty?y=i:"avg"===r&&(b+=i,w++)}if(isNaN(y))break}g[N+n*x+t]="avg"===r?b/w:y}}}return m}function Kw(e,t,n,s,a=!1,r=!1){const i=Ha(s.outShape,"int32"),o=s.strideHeight,l=s.strideWidth,u=s.dilationHeight,c=s.dilationWidth,h=s.effectiveFilterHeight,p=s.effectiveFilterWidth,d=s.padInfo.top,f=s.padInfo.left,m=Ha(t,n,e);for(let e=0;ew&&(w=u,k=a?r?((e*s.inHeight+n)*s.inWidth+o)*s.inChannels+t:(n*s.inWidth+o)*s.inChannels+t:i*p+l)}}i.set(k,e,n,o,t)}}return i}function qw(e,t,n,s,a,r){const i=a.strideDepth,o=a.strideHeight,l=a.strideWidth,u=a.dilationDepth,c=a.dilationHeight,h=a.dilationWidth,p=a.effectiveFilterDepth,d=a.effectiveFilterHeight,f=a.effectiveFilterWidth,m=a.padInfo.front,g=a.padInfo.top,y=a.padInfo.left,b="max"===r?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Ha(a.outShape,n),w=x.values,k=a.outShape[1]*a.outShape[2]*a.outShape[3]*a.outShape[4],v=a.outShape[2]*a.outShape[3]*a.outShape[4],N=a.outShape[3]*a.outShape[4],I=a.outShape[4];for(let t=0;tv?v=a:"avg"===r&&(N+=a,$++),isNaN(v))break}if(isNaN(v))break}if(isNaN(v))break}w[g+t]="avg"===r?N/$:v}}}}return x}const Xw={kernelName:Te,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t;Lx(a,"avgPool");const{filterSize:r,strides:i,pad:o,dimRoundingMode:l}=s;E(Yr(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Pr(a.shape,r,i,1,o,l);let c;if(1===u.filterWidth&&1===u.filterHeight&&_(u.inShape,u.outShape))c=Gx({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=Z(a.shape),s=jw(e,a.shape,a.dtype,t,u,"avg");c=n.makeTensorInfo(u.outShape,a.dtype,s.values)}return c}},Yw={kernelName:Ae,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{filterSize:r,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s;Lx(a,"avgPool3d");const c=Wr(a.shape,r,i,1,o,l,u),h=qw(n.data.get(a.dataId).values,a.shape,a.dtype,Z(a.shape),c,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}},Jw={kernelName:Re,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,input:r}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=s;Lx([a,r],"avgPool3DGrad");const c=Wr(r.shape,i,o,1,l,u),h=c.strideDepth,p=c.strideHeight,d=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,x=c.dilationWidth,w=c.effectiveFilterDepth,k=c.effectiveFilterHeight,v=c.effectiveFilterWidth,N=w-1-c.padInfo.front,I=v-1-c.padInfo.left,$=k-1-c.padInfo.top,C=Ha(r.shape,"float32"),S=1/(f*m*g),T=n.bufferSync(a);for(let e=0;e=c.outDepth||Math.floor(s)!==s))for(let n=0;n=c.outHeight||Math.floor(a)!==a))for(let n=0;n=c.outWidth||Math.floor(r)!==r||(l+=T.get(e,s,a,r,t))}}}C.set(l*S,e,n,s,a,t)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}},Zw={kernelName:Ee,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,input:r}=t,i=r;Lx([a,r],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=Pr(i.shape,o,l,1,u),h=c.strideHeight,p=c.strideWidth,d=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,x=b-1-c.padInfo.left,w=y-1-c.padInfo.top,k=Ha(i.shape,"float32"),v=1/(d*f),N=n.data.get(a.dataId).values,I=Ha(a.shape,"float32",N);for(let e=0;e=c.outHeight||Math.floor(s)!==s))for(let n=0;n=c.outWidth||Math.floor(a)!==a||(i+=I.get(e,s,a,t))}}k.set(i*v,e,n,s,t)}return n.makeTensorInfo(k.shape,k.dtype,k.values)}},Qw={kernelName:xt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,scale:r,offset:i,mean:o,variance:l}=t;E(o.shape.length===l.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),E(null==i||o.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),E(null==r||o.shape.length===r.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),Lx([a,o,l,r,i],"batchNorm");let{varianceEpsilon:u}=s;null==u&&(u=.001);const c=n.data.get(a.dataId).values,h=n.data.get(o.dataId).values,p=n.data.get(l.dataId).values,d=r?n.data.get(r.dataId).values:new Float32Array([1]),f=i?n.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,y=d.length,b=p.length,x=h.length;let w=0,k=0,v=0,N=0;for(let e=0;e=g&&(w=0),k>=x&&(k=0),v>=y&&(v=0),N>=b&&(N=0);return n.makeTensorInfo(a.shape,a.dtype,m)}};function ek(e,t,n,s,a){const r=yr(s,t,n),i=D(n),o=Z(s);if(r){const n=br(t,o);return"string"===a?e.slice(n,n+i):e.subarray(n,n+i)}const l=Ha(s,a,"string"===a?Bu(e):e),u=Ha(n,a);for(let e=0;ee+t[n]));u.set(l.get(...s),...n)}return"string"===a?Pu(u.values):u.values}function tk(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{begin:r,size:i}=s;Lx(a,"slice");const[o,l]=xr(a,r,i);rr(a,o,l);const u=ek(n.data.get(a.dataId).values,o,l,a.shape,a.dtype);return n.makeTensorInfo(l,a.dtype,u)}const nk={kernelName:An,backendName:"cpu",kernelFunc:tk},sk={kernelName:De,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{blockShape:r,crops:i}=s;Lx([a],"batchToSpaceND");const o=r.reduce(((e,t)=>e*t)),l=lu(a.shape,r,o),u=uu(l.length,r.length),c=cu(a.shape,r,o),h=hu(i,r.length),p=pu(c,i,r.length),d=gw({inputs:{x:a},backend:n,attrs:{shape:l}}),f=Ew({inputs:{x:d},backend:n,attrs:{perm:u}}),m=gw({inputs:{x:f},backend:n,attrs:{shape:c}}),g=tk({inputs:{x:m},backend:n,attrs:{begin:h,size:p}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};function ak(e,t,n,s,a){const r=D(s),i=ne(a,n);for(let n=0;n=a||(i[s]+=r>0?t[n]:1)}return i}function rk(e,t,n,s=!1){const a=e.shape[0],r=e.shape[1],i=Ha([a,n],t.dtype);for(let o=0;o=n||(s?i.set(1,o,r):t.size>0?i.set(i.get(o,r)+t.get(o,a),o,r):i.set(i.get(o,r)+1,o,r))}return i}const ik={kernelName:_e,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,weights:r}=t,{size:i}=s,o=ak(n.data.get(a.dataId).values,n.data.get(r.dataId).values,r.dtype,r.shape,i);return n.makeTensorInfo([i],r.dtype,o)}};function ok(e){return(t,n,s)=>{const a=V(n,t.length);for(let n=0;nMath.ceil(e))),uk=Wx(Me,lk),ck={kernelName:Me,backendName:"cpu",kernelFunc:uk},hk=Px(Le,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e{const{x:t}=e.inputs,n=e.backend,s=new Float32Array(D(t.shape)),a=n.data.get(t.dataId),r=a.complexTensorInfos.real,i=a.complexTensorInfos.imag,o=n.data.get(r.dataId).values,l=n.data.get(i.dataId).values;for(let e=0;e{const n=D(e.shape);a.set(e.vals,t),t+=n}))}else{let s=0;e.forEach((e=>{const r="string"===n?Bu(e.vals):e.vals;let i=0;for(let n=0;ne.shape)),r);if(0===D(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>D(e.shape)>0));if(1===o.length)return Gx({inputs:{x:o[0]},backend:n});if(su(o.map((e=>e.shape)),r),"complex64"===o[0].dtype){const e=o.map((e=>iw({inputs:{input:e},backend:n}))),t=o.map((e=>mk({inputs:{input:e},backend:n}))),s=yk({inputs:e,backend:n,attrs:{axis:r}}),a=yk({inputs:t,backend:n,attrs:{axis:r}}),i=sw({inputs:{real:s,imag:a},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),i}const l=o.map((e=>{const t=D(e.shape.slice(r));return gw({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),u=l.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));i=au(l.map((e=>e.shape)),1);const c=1===l[0].shape[0],h=fk(u,i,t[0].dtype,c),p=au(o.map((e=>e.shape)),r),d=n.makeTensorInfo(p,t[0].dtype,h);return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}const bk={kernelName:Pe,backendName:"cpu",kernelFunc:yk};function xk(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,filter:r}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s;Lx([a,r],"conv2d");const h=Jr(l),p=Vr(a.shape,r.shape,i,u,o,c,!1,h),d=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,b=p.padInfo.top,x="channelsLast"===p.dataFormat,w=new Es(p.outShape,a.dtype),k=Z(a.shape),v=Z(r.shape),N=k[0],I=x?k[1]:k[2],$=x?k[2]:1,C=x?1:k[1],S=w.strides[0],T=x?w.strides[1]:w.strides[2],E=x?w.strides[2]:1,A=x?1:w.strides[1],R=n.data.get(a.dataId).values,F=n.data.get(r.dataId).values,D=w.values;for(let e=0;e=p.inHeight)continue;const r=e*v[0],i=t+n*I;for(let e=0;e=p.inWidth)continue;const a=i+s*$;let o=r+e*v[1];for(let e=0;e=u.inDepth)continue;const r=e*$[0],i=t+n*I[1];for(let e=0;e=u.inHeight)continue;const a=r+e*$[1],o=i+s*I[2];for(let e=0;e=u.inWidth)continue;const r=a+e*$[2],i=o+t*u.inChannels;let l=r;for(let e=0;eMath.cos(e))),Sk={kernelName:Ke,backendName:"cpu",kernelFunc:Ck},Tk=Px(qe,(e=>Math.cosh(e))),Ek={kernelName:qe,backendName:"cpu",kernelFunc:Tk},Ak={kernelName:Ye,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{image:a,boxes:r,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=s,[c,h,p,d]=a.shape,f=r.shape[0],[m,g]=o,y=Ha([f,m,g,d],"float32"),b=n.data.get(r.dataId).values,x=n.data.get(i.dataId).values,w=n.data.get(a.dataId).values,k=Z(a.shape),v=Z(y.shape);for(let e=0;e=c)continue;const o=m>1?(a-n)*(h-1)/(m-1):0,f=g>1?(r-s)*(p-1)/(g-1):0;for(let t=0;t1?n*(h-1)+t*o:.5*(n+a)*(h-1);if(c<0||c>h-1)for(let n=0;n1?s*(p-1)+l*f:.5*(s+r)*(p-1);if(c<0||c>p-1){for(let n=0;n1?s*(p-1)+n*f:.5*(s+r)*(p-1);if(a<0||a>p-1){for(let s=0;se+f-t-1:(e,t)=>e+t;for(let e=0;e`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`)),E(r>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${r}`));const o=a.shape[0],l=a.shape[1],u=a.shape[2],c=a.shape[3],h=l*r,p=u*r,d=c/(r*r),f=n.data.get(a.dataId).values,m=new Float32Array(o*h*p*d);let g=0;for(let e=0;e`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`));const d=Vr(a.shape,r.shape,i,p,o,u,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=d,x=b.left,w=b.top,k=d.outChannels/d.inChannels,v=new Es(d.outShape,a.dtype),N=n.data.get(a.dataId).values,I=n.data.get(r.dataId).values,$=v.values;for(let e=0;e=d.inHeight)continue;const r=e*h[0],i=t+n*c[1];for(let e=0;e=d.inWidth)continue;const a=r+e*h[1],o=i+s*d.inChannels;let l=t,u=a;for(let e=0;e{const{x:s,filter:a}=e,{strides:r,pad:i,dilations:o}=n,l=t,u=l.data.get(s.dataId).values,c=s.shape.length,h=l.data.get(a.dataId).values,p=a.shape.length,{batchSize:d,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:w,strideWidth:k,filterHeight:v,filterWidth:N,dilationHeight:I,dilationWidth:$,outShape:C}=Br(s.shape,a.shape,r,i,"NHWC",o),S=D(C),T=C.length,E=U(s.dtype,S);for(let e=0;e=0&&r=0&&dl&&(l=m)}}}E[re([e,t,r,o],T,Z(C))]=l}}}return{dataId:l.write(ys(E,s.dtype),C,s.dtype),shape:C,dtype:s.dtype}}},Pk={kernelName:rt,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:a,dy:r}=e,{strides:i,pad:o,dilations:l}=n,u=t,c=ee(s.shape,u.data.get(s.dataId).values),h=ee(a.shape,u.data.get(a.dataId).values),{batchSize:p,inHeight:d,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:k,filterWidth:v,dilationHeight:N,dilationWidth:I,outShape:$}=Br(s.shape,a.shape,i,o,"NHWC",l);E(r.rank===$.length,(()=>`Error in Dilation2DBackpropFilter, dy must have the same rank as output ${$.length}, but got ${r.rank}`));const C=ee($,u.data.get(r.dataId).values),S=se(a.shape,a.dtype);for(let e=0;e=0&&s=0&&ui&&(i=a,o=t,l=n)}}}S[o][l][r]+=C[e][t][s][r]}}}return{dataId:u.write(ys(S,s.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},Wk={kernelName:at,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:a,dy:r}=e,{strides:i,pad:o,dilations:l}=n,u=t,c=ee(s.shape,u.data.get(s.dataId).values),h=ee(a.shape,u.data.get(a.dataId).values),{batchSize:p,inHeight:d,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:w,filterHeight:k,filterWidth:v,dilationHeight:N,dilationWidth:I,outShape:$}=Br(s.shape,a.shape,i,o,"NHWC",l);E(r.rank===$.length,(()=>`Error in Dilation2DBackpropInput, dy must have the same rank as output ${$.length}, but got ${r.rank}`));const C=ee($,u.data.get(r.dataId).values),S=se(s.shape,s.dtype);for(let e=0;e=0&&s=0&&ui&&(i=a,o=s,l=u)}}}S[e][o][l][r]+=C[e][t][s][r]}}}return{dataId:u.write(ys(S,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},Vk={kernelName:lt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:s,y:a}=t;Lx([s,a],"eluGrad");const r=new Float32Array(D(a.shape)),i=n.data.get(a.dataId).values,o=n.data.get(s.dataId).values;for(let e=0;e=1?o[e]:o[e]*(t+1)}return n.makeTensorInfo(a.shape,"float32",r)}},Uk=qx(((e,t)=>e===t?1:0)),Gk=cw(ct,Uk,null,"bool"),Hk={kernelName:ct,backendName:"cpu",kernelFunc:Gk},jk=xu,Kk=wu,qk=ku,Xk=vu,Yk=Nu,Jk=Iu,Zk=Px(ut,(e=>{const t=Math.sign(e),n=Math.abs(e),s=1/(1+jk*n);return t*(1-((((Jk*s+Yk)*s+Xk)*s+qk)*s+Kk)*s*Math.exp(-n*n))})),Qk={kernelName:ut,backendName:"cpu",kernelFunc:Zk},ev=ok((e=>Math.exp(e))),tv=Wx(ht,ev),nv={kernelName:ht,backendName:"cpu",kernelFunc:tv};function sv(e){const{inputs:t,backend:n,attrs:s}=e,{input:a}=t,{dim:r}=s,i=a.shape.length,o=a.shape.slice();let l=r;return r<0&&(E(-(i+1)<=r,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+r+1),o.splice(l,0,1),gw({inputs:{x:a},backend:n,attrs:{shape:o}})}const av={kernelName:pt,backendName:"cpu",kernelFunc:sv},rv=ok((e=>Math.expm1(e))),iv=Wx(dt,rv),ov={kernelName:dt,backendName:"cpu",kernelFunc:iv},lv=qx(((e,t)=>e*t)),uv=hw(((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n}))),cv=cw(en,lv,uv),hv={kernelName:en,backendName:"cpu",kernelFunc:cv},pv=qx(((e,t)=>e/t)),dv=cw(it,pv),fv={kernelName:it,backendName:"cpu",kernelFunc:dv},mv=qx(((e,t)=>e-t)),gv=hw(((e,t,n,s)=>({real:e-n,imag:t-s}))),yv=cw(Un,mv,gv),bv={kernelName:Un,backendName:"cpu",kernelFunc:yv};function xv(e,t,n){const s=e.shape,a=s[0],r=s[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[a,r],c=D(u),h=V("float32",c),p=V("float32",c);for(let e=0;e{const{image:s}=e,a=n,r=V(s.dtype,D(s.shape)),[i,o,l,u]=s.shape,c=a.data.get(s.dataId).values;for(let e=0;e=0&&pMath.floor(e))),Sv=Wx(yt,Cv),Tv={kernelName:yt,backendName:"cpu",kernelFunc:Sv},Ev=qx(((e,t)=>Math.floor(e/t))),Av=cw(bt,Ev,null,"int32"),Rv={kernelName:bt,backendName:"cpu",kernelFunc:Av},Fv={kernelName:is,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,filter:r,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s;let m=xk({inputs:{x:a,filter:r},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;m=fw({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=nw(n,m,d,o,f),n.disposeIntermediateTensorInfo(e)}return m}},Dv={kernelName:os,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,filter:r,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s;let m=_k({inputs:{x:a,filter:r},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;m=fw({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=nw(n,m,d,o,f),n.disposeIntermediateTensorInfo(e)}return m}},_v={kernelName:kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:s,indices:a}=t,r=D(s.shape),i=a.shape,o=i[i.length-1],[l,u,c,h]=du(s,a);if(0===u)return n.makeTensorInfo(l,s.dtype,[]);const p=Ha([u,c],s.dtype),d=n.data.get(a.dataId).values,f=n.data.get(s.dataId).values;for(let e=0;e=r/c)throw new Error(`Invalid indices: ${t} does not index into ${s.shape}`);for(let t=0;te>t?1:0)),zv=cw(vt,Lv,null,"bool"),Bv={kernelName:vt,backendName:"cpu",kernelFunc:zv},Pv=qx(((e,t)=>e>=t?1:0)),Wv=cw(Nt,Pv,null,"bool"),Vv={kernelName:Nt,backendName:"cpu",kernelFunc:Wv},Uv={kernelName:$t,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t,a=D(s.shape),r=s.shape[s.shape.length-1],i=gw({inputs:{x:s},backend:n,attrs:{shape:[a/r,r]}}),o=xv(i,!0,n),l=gw({inputs:{x:o},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}},Gv=Px(St,(e=>Number.isFinite(e)?1:0),"bool"),Hv={kernelName:St,backendName:"cpu",kernelFunc:Gv},jv=Px(Tt,(e=>Math.abs(e)===1/0?1:0),"bool"),Kv={kernelName:Tt,backendName:"cpu",kernelFunc:jv},qv=Px(Et,(e=>Number.isNaN(e)?1:0),"bool"),Xv={kernelName:Et,backendName:"cpu",kernelFunc:qv},Yv=qx(((e,t)=>ee<=t?1:0)),eN=cw(Ft,Qv,null,"bool"),tN={kernelName:Ft,backendName:"cpu",kernelFunc:eN};function nN(e,t,n){const s=(t-e)/(n-1),a=ne(n,"float32");a[0]=e;for(let e=1;eMath.log(e))),rN=Wx(_t,aN),iN={kernelName:_t,backendName:"cpu",kernelFunc:rN},oN=Px(Ot,(e=>Math.log1p(e))),lN={kernelName:Ot,backendName:"cpu",kernelFunc:oN},uN=qx(((e,t)=>e&&t)),cN=cw(Mt,uN,null,"bool"),hN={kernelName:Mt,backendName:"cpu",kernelFunc:cN},pN=Px(Lt,(e=>e?0:1),"bool"),dN={kernelName:Lt,backendName:"cpu",kernelFunc:pN},fN=qx(((e,t)=>e||t)),mN=cw(zt,fN,null,"bool"),gN={kernelName:zt,backendName:"cpu",kernelFunc:mN},yN={kernelName:Bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{depthRadius:r,bias:i,alpha:o,beta:l}=s;Lx(a,"LRN");const u=a.shape[3],c=u-1,h=n.data.get(a.dataId).values,p=D(a.shape),d=new Float32Array(p);function f(e){const t=e%u;let n=e-t+Math.max(0,t-r);const s=e-t+Math.min(t+r,c);let a=0;for(;n<=s;n++){const e=h[n];a+=e*e}return a}for(let e=0;er&&(r=t)}a[n]=r}return a}function wN(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{reductionIndices:r,keepDims:i}=s,o=n;let l=a.shape;const u=l.length,c=P(r,l);let h=c;const p=Zi(h,u);let d=o.data.get(a.dataId).values;if(null!=p){const e=new Array(u);for(let t=0;tMath.max(e,t))),NN=cw(Vt,vN),IN={kernelName:Vt,backendName:"cpu",kernelFunc:NN},$N={kernelName:Ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t;Lx(a,"maxPool");const{filterSize:r,strides:i,pad:o,dimRoundingMode:l}=s;E(Yr(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Pr(a.shape,r,i,1,o,l);let c;if(1===u.filterWidth&&1===u.filterHeight&&_(u.inShape,u.outShape))c=Gx({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=Z(a.shape),s=jw(e,a.shape,a.dtype,t,u,"max");c=n.makeTensorInfo(u.outShape,a.dtype,s.values)}return c}},CN={kernelName:Ht,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{filterSize:r,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s;Lx(a,"maxPool3d");const c=Wr(a.shape,r,i,1,o,l,u),h=qw(n.data.get(a.dataId).values,a.shape,a.dtype,Z(a.shape),c,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}},SN={kernelName:jt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,input:r}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=s;Lx([a,r],"maxPool3DGrad");const c=Wr(r.shape,i,o,1,l,u),h=function(e,t){const n=Ha(t.outShape,"int32"),s=t.strideDepth,a=t.strideHeight,r=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,c=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.front,d=t.padInfo.top,f=t.padInfo.left;for(let m=0;m=I&&(I=o,$=n*c*h+a*c+i)}}}n.set($,m,y,s,a,g)}}}return n}(n.bufferSync(r),c),p=c.strideDepth,d=c.strideHeight,f=c.strideWidth,m=c.dilationDepth,g=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,x=c.effectiveFilterHeight,w=c.effectiveFilterWidth,k=b-1-c.padInfo.front,v=w-1-c.padInfo.left,N=x-1-c.padInfo.top,I=Ha(r.shape,"float32"),$=n.bufferSync(a);for(let e=0;e=c.outDepth||Math.floor(s)!==s))for(let a=0;a=c.outHeight||Math.floor(r)!==r))for(let i=0;i=c.outWidth||Math.floor(u)!==u)continue;const p=b*x*w-1-h.get(e,s,r,u,t)===n*x*w+a*w+i?1:0;0!==p&&(l+=$.get(e,s,r,u,t)*p)}}}I.set(l,e,n,s,a,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}},TN={kernelName:Gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,input:r,output:i}=t,o=r;Lx([r,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,p=Pr(o.shape,l,u,1,c,h),d=n.data.get(o.dataId).values,f=Ha(p.outShape,o.dtype,Kw(d,o.shape,o.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,b=p.dilationWidth,x=p.effectiveFilterHeight,w=p.effectiveFilterWidth,k=w-1-p.padInfo.left,v=x-1-p.padInfo.top,N=Ha(o.shape,"float32"),I=n.data.get(a.dataId).values,$=Ha(a.shape,"float32",I);for(let e=0;e=p.outHeight||Math.floor(s)!==s))for(let a=0;a=p.outWidth||Math.floor(o)!==o)continue;const l=x*w-1-f.get(e,s,o,t)===n*w+a?1:0;0!==l&&(i+=$.get(e,s,o,t)*l)}}N.set(i,e,n,s,t)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}},EN={kernelName:Kt,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:a,strides:r,pad:i,includeBatchInIndex:o}=t,l=n;Lx(s,"MaxPoolWithArgmax");const u=l.data.get(s.dataId).values,c=Pr(s.shape,a,r,[1,1],i),[h,p]=function(e,t,n,s,a){const r=jw(e,0,n,Z(t),a,"max"),i=Kw(e,t,n,a,!0,s);return[r.values,i.values]}(u,s.shape,s.dtype,o,c),d=l.write(h,c.outShape,s.dtype),f=l.write(p,c.outShape,s.dtype);return[{dataId:d,shape:c.outShape,dtype:s.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};function AN(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r,keepDims:i}=s;let o;Lx(a,"sum"),o="bool"===a.dtype?lw({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):Gx({inputs:{x:a},backend:n});const l=o.shape.length,u=P(r,o.shape),c=Zi(u,l);let h=u,p=o;null!=c&&(p=Ew({inputs:{x:o},backend:n,attrs:{perm:c}}),h=eo(h.length,l)),Ji("sum",h,p.shape.length);const[d,f]=Xi(p.shape,h);let m=rw(n,d,Vs(p.dtype,"int32"));const g=D(f),y=n.data.get(m.dataId).values,b=n.data.get(p.dataId).values;for(let e=0;en.disposeIntermediateTensorInfo(e))),d}},DN={kernelName:Xt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r,keepDims:i}=s;Lx(a,"min");const o=P(r,a.shape);let l=o;const u=Zi(l,a.shape.length);let c=a;null!=u&&(c=Ew({inputs:{x:a},backend:n,attrs:{perm:u}}),l=eo(l.length,a.shape.length)),Ji("min",l,c.shape.length);const[h,p]=Xi(c.shape,l),d=D(p),f=ne(D(h),c.dtype),m=n.data.get(c.dataId).values;for(let e=0;eMath.min(e,t))),ON=cw(Yt,_N),MN={kernelName:Yt,backendName:"cpu",kernelFunc:ON},LN={kernelName:Jt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{paddings:r,mode:i}=s;Lx(a,"mirrorPad");const o=r.map(((e,t)=>e[0]+a.shape[t]+e[1])),l=r.map((e=>e[0])),u=r.map(((e,t)=>e[0]+a.shape[t])),c="reflect"===i?0:1,h=n.data.get(a.dataId).values,p=a.shape.length,d=Z(a.shape),f=D(o),m=o.length,g=Z(o),y=V(a.dtype,f);for(let e=0;e=u[e]&&(t[e]=2*(u[e]-1)-t[e]+c);t=t.map(((e,t)=>e-l[t]));const n=re(t,p,d);y[e]=h[n]}return{dataId:n.write(y,o,a.dtype),shape:o,dtype:a.dtype}}},zN=qx(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),BN=cw(Zt,zN),PN={kernelName:Zt,backendName:"cpu",kernelFunc:BN};function WN(e){const{inputs:t,backend:n,attrs:s}=e,{logits:a}=t,{dim:r}=s,i=a.shape.length;let o=r;if(-1===o&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);const l=P([o],a.shape),u=wN({inputs:{x:a},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),c=Yi(u.shape,l),h=gw({inputs:{x:u},backend:n,attrs:{shape:c}}),p=yv({inputs:{a,b:h},backend:n}),d=tv({inputs:{x:p},backend:n}),f=AN({inputs:{x:d},backend:n,attrs:{axis:l,keepDims:!1}}),m=gw({inputs:{x:f},backend:n,attrs:{shape:c}}),g=dv({inputs:{a:d,b:m},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}const VN={kernelName:Pn,backendName:"cpu",kernelFunc:WN},UN={kernelName:Qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:a}=t,{numSamples:r,seed:i,normalized:o}=s;Lx(a,"multinomial");const l=o?a:WN({inputs:{logits:a},backend:n,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],h=n.data.get(l.dataId).values,p=[u,r],d=ne(D(p),"int32");for(let e=0;ee!==t?1:0)),QN=cw(nn,ZN,null,"bool"),eI={kernelName:nn,backendName:"cpu",kernelFunc:QN},tI={kernelName:ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:a}=t,{depth:r,onValue:i,offValue:o}=s;Lx(a,"oneHot");const l=D(a.shape),u=new Float32Array(l*r);u.fill(o);const c=n.data.get(a.dataId).values;for(let e=0;e=0&&c[e]{A(r,e.shape,"All tensors passed to stack must have matching shapes"),E(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=yk({inputs:t.map((e=>{const t=sv({inputs:{input:e},backend:n,attrs:{dim:a}});return o.push(t),t})),backend:n,attrs:{axis:a}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}const iI={kernelName:un,backendName:"cpu",kernelFunc:rI},oI={kernelName:cn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{paddings:r,constantValue:i}=s;Lx(a,"pad");const o=r.map(((e,t)=>e[0]+a.shape[t]+e[1])),l=r.map((e=>e[0])),u=n.data.get(a.dataId).values,c=D(a.shape),h=a.shape.length,p=Z(a.shape),d=D(o),f=o.length,m=Z(o),g=V(a.dtype,d);0!==i&&g.fill(i);for(let e=0;ee+l[t])),f,m)]=u[e];return{dataId:n.write(g,o,a.dtype),shape:o,dtype:a.dtype}}},lI=qx(((e,t)=>Math.pow(e,t))),uI=cw(hn,lI),cI={kernelName:hn,backendName:"cpu",kernelFunc:uI};function hI(e,t,n,s){const[a,r]=Xi(e,s),i=Vs(t,"int32"),o=ne(D(a),i),l=D(r);for(let e=0;en.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,g,f)}};function dI(e,t,n,s){if(e===t||e1)return ne(0,s);const a=ne(Math.abs(Math.ceil((t-e)/n)),s);t1/e)),gI={kernelName:gn,backendName:"cpu",kernelFunc:mI},yI={kernelName:kn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:a}=t,{alignCorners:r,halfPixelCenters:i,size:o}=s;Lx(a,"resizeBilinear");const l=Z(a.shape),[u,c]=o,[h,p,d,f]=a.shape,m=n.data.get(a.dataId).values,g=new Float32Array(D([h,u,c,f])),y=[r&&u>1?p-1:p,r&&c>1?d-1:d],b=[r&&u>1?u-1:u,r&&c>1?c-1:c];let x=0;const w=y[0]/b[0],k=y[1]/b[1];for(let e=0;e1?u-1:u,i&&d>1?c-1:c],g=[i&&p>1?p-1:p,i&&d>1?d-1:d],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(r.dataId).values;let w=0;for(let e=0;e1?p-1:p,r&&c>1?d-1:d],b=[r&&u>1?u-1:u,r&&c>1?c-1:c],x=y[0]/b[0],w=y[1]/b[1];let k=0;for(let e=0;e1?c-1:c,i&&f>1?h-1:h],b=[i&&d>1?d-1:d,i&&f>1?f-1:f],x=y[0]/b[0],w=y[1]/b[1],k=1/x,v=1/w,N=2*Math.ceil(k)+2,I=2*Math.ceil(v)+2;for(let e=0;e=d)continue;const p=t+u*l[1],m=u*x;if(e===Math.min(c-1,i?Math.round(m):Math.floor(m)))for(let e=0;e=f)continue;const a=p+t*l[2],r=t*w;s===Math.min(h-1,i?Math.round(r):Math.floor(r))&&(o+=g[a+n])}}m[r+n]=o}}}}return n.makeTensorInfo(a.shape,a.dtype,m)}},kI={kernelName:In,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{dims:r}=s;Lx(a,"reverse");const i=a.shape.length,o=P(r,a.shape);if(0===i)return Gx({inputs:{x:a},backend:n});const l=new Es(a.shape,a.dtype),u=n.bufferSync(a);for(let e=0;en[e]=a.shape[e]-1-n[e])),l.set(u.get(...n),...t)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}},vI={kernelName:as,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:a,fillValue:r,center:i}=t,o=n,l=V(s.dtype,D(s.shape)),[u,c,h,p]=s.shape,[d,f]=ou(i,c,h),m=Math.sin(a),g=Math.cos(a),y=o.data.get(s.dataId).values;for(let e=0;e=0&&w=0&&k{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1})),II={kernelName:$n,backendName:"cpu",kernelFunc:NI},$I=ok((e=>1/Math.sqrt(e))),CI=Wx(Cn,$I),SI={kernelName:Cn,backendName:"cpu",kernelFunc:CI};function TI(e,t,n,s,a,r,i,o,l,u){const c=[s/a,a],h=e.values,p=t.values;if(0===s)return Ha(n,t.dtype);const d=Ha(c,t.dtype);d.values.fill(l);for(let e=0;e=s/a)throw new Error(`Invalid indices: ${r} does not index into ${n}`);for(let n=0;n1||1===a.shape.length?1:D(a.shape.slice(1));for(let e=0;ee>=0?FI*e:RI*(Math.exp(e)-1))),_I={kernelName:En,backendName:"cpu",kernelFunc:DI},OI=Px(_n,(e=>1/(1+Math.exp(-e)))),MI={kernelName:_n,backendName:"cpu",kernelFunc:OI},LI=Px(Dn,(e=>e<0?-1:e>0?1:0)),zI={kernelName:Dn,backendName:"cpu",kernelFunc:LI},BI=Px(Rn,(e=>Math.sin(e))),PI={kernelName:Rn,backendName:"cpu",kernelFunc:BI},WI=Px(Fn,(e=>Math.sinh(e))),VI={kernelName:Fn,backendName:"cpu",kernelFunc:WI},UI=Math.log(1.1920928955078125e-7)+2,GI=Px(On,(e=>{const t=e>-UI,n=e{const t=[...c];t[o]=e;const s=tk({inputs:{x:a},backend:n,attrs:{begin:u,size:t}});return u[o]+=e,s}))}},XI=Px(Mn,(e=>Math.sqrt(e))),YI={kernelName:Mn,backendName:"cpu",kernelFunc:XI},JI={kernelName:Vn,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,s=t;Lx(n,"square");const a=s.data.get(n.dataId).values,r=new Float32Array(a.length);for(let e=0;e{const n=e-t;return n*n})),QI=cw(Wn,ZI),e$={kernelName:Wn,backendName:"cpu",kernelFunc:QI},t$=Px(ns,((e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),n$={kernelName:ns,backendName:"cpu",kernelFunc:t$};function s$(e,t,n,s){const a=Ha(e,t.dtype);for(let e=0;e0===e)))w=n.makeTensorInfo(b,a.dtype,[]);else{const e=s$(b,n.bufferSync(x),m,f);w=n.makeTensorInfo(e.shape,e.dtype,e.values)}const k=gw({inputs:{x:w},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(w),k}},r$=Px(jn,(e=>Math.tan(e))),i$={kernelName:jn,backendName:"cpu",kernelFunc:r$},o$=Px(Kn,(e=>Math.tanh(e)));function l$(e,t){const n=new Array(e.rank);for(let s=0;st.value-e.value));const i=t*s,c=l.subarray(i,i+s),h=u.subarray(i,i+s);for(let e=0;et-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return S(0,n,t-1)}(e,t);case"wrap":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=t-1;n+=t*(Math.trunc(-n/e)+1)}else if(n>t-1)if(t<=1)n=0;else{const e=t-1;n-=t*Math.trunc(n/e)}return S(0,n,t-1)}(e,t);case"nearest":return function(e,t){return S(0,e,t-1)}(e,t);case"constant":default:return function(e,t){return e}(e)}}function h$(e,t,n,s,a,r,i,o,l,u,c){return 0<=o&&o{for(let n=0;nn.disposeIntermediateTensorInfo(e))),h}},sI];for(const e of m$)ds(e);const g$={},y$={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function b$(e){if(!(e in g$)){const t=function(e){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=function(e){if("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e);return t.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete g$[e]}),!1),1===e?t.getContext("webgl",y$)||t.getContext("experimental-webgl",y$):t.getContext("webgl2",y$)}(e);if(null===t)return console.log("Could not get context for WebGL version",e),null;g$[e]=t}const t=g$[e];return t.isContextLost()?(delete g$[e],b$(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),g$[e])}var x$,w$,k$;function v$(e,t){return[t,e]}function N$(e){const t=D(e);return M(Math.ceil(t/4))}function I$(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function $$(e,t){const n=e;let s,a,r,i,o,l,u,c,h,p;return 2===ue().getNumber("WEBGL_VERSION")?(s=n.R32F,a=n.R16F,r=n.RGBA16F,i=n.RGBA32F,o=n.RED,u=4,c=1,h=n.HALF_FLOAT,p=n.FLOAT):(s=e.RGBA,a=e.RGBA,r=e.RGBA,i=n.RGBA,o=e.RGBA,u=4,c=4,h=null!=t?t.HALF_FLOAT_OES:null,p=e.FLOAT),l=e.RGBA,{internalFormatFloat:s,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:r,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:p}}function C$(e,t){const n=t();return ue().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}(e,t))}(e),n}function S$(e){return!!(ue().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(x$||(x$={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(w$||(w$={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(k$||(k$={}));const E$=/ERROR: [0-9]+:([0-9]+):/g;function A$(e,t){if(C$(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function R$(e,t,n,s,a,r,i){const o=e.getAttribLocation(t,n);return-1!==o&&(C$(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,s))),C$(e,(()=>e.vertexAttribPointer(o,a,e.FLOAT,!1,r,i))),C$(e,(()=>e.enableVertexAttribArray(o))),!0)}function F$(e,t,n,s){C$(e,(()=>function(e,t,n){(function(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(sn)throw new Error(`textureUnit must be in [gl.TEXTURE0, gl.TEXTURE${n}].`)})(e,n),C$(e,(()=>e.activeTexture(e.TEXTURE0+n))),C$(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,s))),C$(e,(()=>e.uniform1i(n,s)))}function D$(e,t,n){C$(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),C$(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function _$(e,t){C$(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),C$(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function O$(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}(e,t))}function M$(e,t,n){const s=C$(e,(()=>t()));if(null==s)throw new Error(n);return s}function L$(e,t=2){return D(e.slice(0,e.length-t))}function z$(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function B$(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[L$(e),...z$(e)]),t}function P$(e){return e%2==0}function W$(e,t){if(_(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e.slice(-1)[0],s=t.slice(-1)[0];if(n===s)return!0;if(P$(n)&&P$(s)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&P$(e[0])&&P$(t[0])}let V$,U$;function G$(e,t){return null!=e.getExtension(t)}function H$(e){try{if(null!=b$(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function j$(e){const t=$$(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(s),a}function K$(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&E("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))}const q$=ue();function X$(){let e,t,n,s,a,r,i,o,l,u;return 2===ue().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",s="in",a="texture",r="outputColor",i="out vec4 outputColor;",o="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",l="",u="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",s="varying",a="texture2D",r="gl_FragColor",i="",o="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",l="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",u="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:a,output:r,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function Y$(e,t,n="index"){const s=Z(t);return s.map(((t,a)=>`int ${e[a]} = ${n} / ${t}; ${a===s.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${t}`:`index -= ${e[a]} * ${t}`};`)).join("")}function J$(e){const t=Z(e).map((e=>e.toString()));return`\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n }\n`}q$.registerFlag("HAS_WEBGL",(()=>q$.getNumber("WEBGL_VERSION")>0)),q$.registerFlag("WEBGL_VERSION",(()=>H$(2)?2:H$(1)?1:0)),q$.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),q$.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===q$.get("WEBGL_VERSION"))),q$.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),q$.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),q$.registerFlag("WEBGL_PACK",(()=>q$.getBool("HAS_WEBGL"))),q$.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_PACK_CLIP",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>!1)),q$.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_PACK_REDUCE",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_LAZILY_UNPACK",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_CONV_IM2COL",(()=>q$.getBool("WEBGL_PACK"))),q$.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==V$){const t=b$(e);V$=t.getParameter(t.MAX_TEXTURE_SIZE)}return V$}(q$.getNumber("WEBGL_VERSION")))),q$.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==U$){const t=b$(e);U$=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,U$)}(q$.getNumber("WEBGL_VERSION")))),q$.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=q$.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=b$(e);return t=G$(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:G$(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),q$.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>q$.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!ea())),q$.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=b$(e);if(1===e){if(!G$(t,"OES_texture_float"))return!1}else if(!G$(t,"EXT_color_buffer_float"))return!1;return j$(t)}(q$.getNumber("WEBGL_VERSION")))),q$.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!q$.getBool("WEBGL_FORCE_F16_TEXTURES")&&q$.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),q$.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>function(e){if(0===e)return!1;const t=b$(e);if(1!==e){if(G$(t,"EXT_color_buffer_float"))return j$(t);const e="EXT_color_buffer_half_float";if(G$(t,e)){const n=t.getExtension(e);return function(e,t){const n=$$(e,t),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s),e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const r=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(a),r}(t,n)}return!1}return!!G$(t,"OES_texture_float")&&!!G$(t,"WEBGL_color_buffer_float")&&j$(t)}(q$.getNumber("WEBGL_VERSION")))),q$.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=q$.getNumber("WEBGL_VERSION"))&&null!=b$(e).fenceSync;var e})),q$.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>q$.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),q$.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)})),q$.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>ea()&&q$.getBool("IS_CHROME")?1:-1),(e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)}));const Z$="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";class Q${constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=x$.DENSE;const t=N$(e),n=X$();this.outputShape=e,this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${Y$(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${n.output} = result;\n }\n `}}class eC{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=x$.DENSE;const t=N$(e),n=X$();this.outputShape=e,this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${Y$(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${n.output} = result;\n }\n `}}class tC{constructor(e){this.variableNames=["A"],this.outTexUsage=w$.DOWNLOAD;const t=X$();this.outputShape=e,this.userCode=`\n ${Z$}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class nC{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=w$.DOWNLOAD;const t=X$();this.outputShape=e,this.userCode=`\n ${Z$}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${t.output} = encode_float(x);\n }\n `}}class sC{constructor(e,t,n=!1){this.variableNames=["A"];const s=X$(),[a,r]=t;this.outputShape=e;let i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode=`\n ${J$(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / ${r};\n int c = imod(flatIndex, ${r});\n vec2 uv = (vec2(c, r) + halfCR) / vec2(${r}.0, ${a}.0);\n vec4 values = ${s.texture2D}(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n ${s.output} = vec4(${i}, 0., 0., 0.);\n }\n `}}class aC{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=X$(),[a,r]=t;this.outputShape=e;let i="",o="result";n&&(o="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let n=0;n<=1;n++){const o=2*t+n;i+=`\n localCoords = coords;\n if(localCoords[2] + ${n} < ${e[2]}) {\n localCoords[2] += ${n};\n if(localCoords[1] + ${t} < ${e[1]}) {\n localCoords[1] += ${t};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / ${r};\n c = imod(flatIndex, ${r});\n uv = (vec2(c, r) + halfCR) / vec2(${r}.0, ${a}.0);\n values = ${s.texture2D}(A, uv);\n\n if(offset == 0) {\n result[${o}] = values[0];\n } else if(offset == 1) {\n result[${o}] = values[1];\n } else if(offset == 2) {\n result[${o}] = values[2];\n } else {\n result[${o}] = values[3];\n }\n }\n }\n `}this.userCode=`\n ${J$(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n ${i}\n\n ${s.output} = ${o};\n }\n `}}function rC(e,t,n,s,a,r){!function(e,t){const n=ue().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0)throw new Error(`Requested texture size [${e}x${t}] is invalid.`);if(e>n||t>n)throw new Error(`Requested texture size [${e}x${t}] greater than WebGL maximum on this browser / GPU [${n}x${n}].`)}(t,n);const i=function(e){return M$(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),o=e.TEXTURE_2D;return C$(e,(()=>e.bindTexture(o,i))),C$(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),C$(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),C$(e,(()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST))),C$(e,(()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST))),C$(e,(()=>e.texImage2D(o,0,s,t,n,0,a,r,null))),C$(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),i}function iC(e){return e.internalFormatFloat}function oC(e){return e.internalFormatHalfFloat}function lC(e){return e.downloadTextureFormat}function uC(e){return e.internalFormatPackedFloat}function cC(e){return e.internalFormatPackedHalfFloat}class hC{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=ue().getNumber("WEBGL_VERSION");null!=e?(this.gl=e,function(e,t){g$[e]=t}(t,e)):this.gl=b$(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(1===ue().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=T$(this.gl,e),G$(this.gl,t))this.textureHalfFloatExtension=T$(this.gl,t);else if(ue().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),G$(this.gl,s))this.colorBufferHalfFloatExtension=T$(this.gl,s);else if(ue().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",G$(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!G$(this.gl,s))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(s)}this.vertexBuffer=function(e){return function(e,t){const n=M$(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return C$(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),C$(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}(this.gl),this.indexBuffer=function(e){return function(e,t){const n=M$(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return C$(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),C$(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Uint16Array([0,1,2,2,1,3]))}(this.gl),this.framebuffer=function(e){return M$(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=$$(this.gl,this.textureHalfFloatExtension)}get debug(){return ue().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;C$(e,(()=>e.finish())),C$(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),C$(e,(()=>e.deleteFramebuffer(this.framebuffer))),C$(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),C$(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),C$(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[a,r]=v$(t,n);return rC(e,a,r,iC(s),s.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[a,r]=v$(t,n);return rC(e,a,r,oC(s),s.textureFormatFloat,s.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[a,r]=v$(t,n);return rC(e,a,r,lC(s),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){C$(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?C$(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):C$(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),C$(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),function(e,t,n,s,a,r){let i,o,l;C$(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),a instanceof Uint8Array?(i=new Uint8Array(n*s*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*s*4),o=e.FLOAT,l=r.internalFormatPackedFloat),i.set(a),C$(e,(()=>e.texImage2D(e.TEXTURE_2D,0,l,n,s,0,e.RGBA,o,i))),C$(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[a,r]=I$(t,n);return rC(e,a,r,cC(s),e.RGBA,s.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[a,r]=I$(t,n);return rC(e,a,r,uC(s),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(_$(this.gl,this.framebuffer),this.outputTexture=null),C$(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,s){const[a,r]=v$(t,n),i=new Uint8Array(t*n*4);return C$(e,(()=>e.readPixels(0,0,a,r,s.downloadTextureFormat,e.UNSIGNED_BYTE,i))),new Float32Array(i.buffer)}(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,s,a,r){return function(e,t,n,s,a,r,i,o){const l=e,u=new Float32Array(function(e,t){const[n,s]=I$(e,t);return n*s*4}(r,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}(this.gl,e,0,0,0,a,r,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(e,t,n){const s=e,a=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,a),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),a}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=function(e,t,n,s){const a=e.createBuffer();C$(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a)));const r=16*t*n;return C$(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,r,e.STREAM_READ))),C$(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),C$(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),a}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(ue().getBool("WEBGL_FENCE_API_ENABLED")){const s=e,a=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=s.clientWaitSync(a,0,0);return e===s.ALREADY_SIGNALED||e===s.CONDITION_SATISFIED},t=a}else ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n){const s=new Float32Array(t*n*4);return C$(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s))),s}(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl,n=function(e,t){const n=M$(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(C$(e,(()=>e.shaderSource(n,t))),C$(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw function(e,t){const n=E$.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const s=+n[1],a=e.split("\n"),r=a.length.toString().length+2,i=a.map(((e,t)=>L((t+1).toString(),r)+e));let o=0;for(let e=0;ee.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(C$(e,(()=>e.shaderSource(n,t))),C$(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}(e,`${t.version}\n precision highp float;\n ${t.attribute} vec3 clipSpacePos;\n ${t.attribute} vec2 uv;\n ${t.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`)}(t),a=function(e){return M$(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);return C$(t,(()=>t.attachShader(a,s))),C$(t,(()=>t.attachShader(a,n))),function(e,t){if(C$(e,(()=>e.linkProgram(t))),!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}(t,a),this.debug&&A$(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=function(e,t,n){return C$(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),R$(e,t,"clipSpacePos",n,3,20,0)&&R$(e,t,"uv",n,2,20,12)}(t,this.program,this.vertexBuffer)),a}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&C$(this.gl,(()=>this.gl.deleteProgram(e)))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&A$(this.gl,this.program),C$(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return M$(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}(this.gl,e,t):function(e,t,n){return e.getUniformLocation(t,n)}(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),C$(this.gl,(()=>this.gl.getAttribLocation(e,t)))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),F$(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,a]=I$(t,n);this.setOutputMatrixTextureDriver(e,s,a)}setOutputMatrixWriteRegion(e,t,n,s){this.setOutputMatrixWriteRegionDriver(n,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,n,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&A$(this.gl,this.program),O$(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),C$(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),C$(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=T$(this.gl,2===ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await z((()=>this.disposed||this.isQueryAvailable(e,ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),s=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=function(e){let t=0;for(;te.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||z((()=>(this.pollItems(),0===this.itemsToPoll.length)))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),D$(this.gl,e,this.framebuffer),this.debug&&O$(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(D$(this.gl,this.outputTexture,this.framebuffer),this.debug&&O$(this.gl)):_$(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const s=this.gl;D$(s,e,this.framebuffer),this.debug&&O$(s),this.outputTexture=e,C$(s,(()=>s.viewport(0,0,t,n))),C$(s,(()=>s.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),C$(this.gl,(()=>this.gl.scissor(e,t,n,s)))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{getBroadcastDims:pC}=a;function dC(e,t,n,s){const a=[];e.forEach((e=>{const t=D(e.shapeInfo.logicalShape);e.shapeInfo.isUniform?a.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(a.push(`uniform sampler2D ${e.name};`),a.push(`uniform int offset${e.name};`))}));const r=a.join("\n"),i=e.map((e=>function(e,t,n=!1){let s="";s+=n?mC(e):fC(e);const a=e.shapeInfo.logicalShape,r=t.logicalShape;return a.length<=r.length&&(s+=n?function(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),a="get"+s+"AtOutCoords",r=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=pC(e.shapeInfo.logicalShape,t.logicalShape),l=vC(i),u=i-r;let c;const h=["x","y","z","w","u","v"];c=0===r?"":i<2&&o.length>=1?"coords = 0;":o.map((e=>`coords.${h[e+u]} = 0;`)).join("\n");let p="";p=i<2&&r>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${h[t+u]}`)).join(", ");let d="return outputValue;";const f=1===D(e.shapeInfo.logicalShape),m=1===D(t.logicalShape);if(1!==r||f||m){if(f&&!m)d=1===i?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(o.length){const e=r-2,t=r-1;o.indexOf(e)>-1&&o.indexOf(t)>-1?d="return vec4(outputValue.x);":o.indexOf(e)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(t)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${a}() {\n ${l} coords = getOutputCoords();\n ${c}\n vec4 outputValue = get${s}(${p});\n ${d}\n }\n `}(e,t):function(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),a="get"+s+"AtOutCoords",r=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&null==e.shapeInfo.flatOffset&&_(i,r))return`\n float ${a}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const u=vC(l),c=pC(e.shapeInfo.logicalShape,t.logicalShape),h=l-o;let p;const d=["x","y","z","w","u","v"];p=0===o?"":l<2&&c.length>=1?"coords = 0;":c.map((e=>`coords.${d[e+h]} = 0;`)).join("\n");let f="";return f=l<2&&o>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+h]}`)).join(", "),`\n float ${a}() {\n ${u} coords = getOutputCoords();\n ${p}\n return get${s}(${f});\n }\n `}(e,t)),s}(e,t,s))).join("\n"),o=t.texShape,l=X$(),u=function(e){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${e.texture2D}(textureSampler, uv).r;\n }\n `}(l);let c,h,p=function(e){return`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFs} vec2 resultUV;\n ${e.defineOutput}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n ${e.defineSpecialNaN}\n ${e.defineSpecialInf}\n ${e.defineRound}\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n ${gC}\n ${yC}\n ${bC}\n `}(l);return t.isPacked?(c=function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===n[0]?`\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${n[1]}.0);\n }\n `:1===n[1]?`\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${n[0]}.0);\n }\n `:`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${n[0]}, ${n[1]}));\n return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);\n }\n `}(0,t);case 2:return function(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(_(e,t))return`\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));\n }\n `;const s=Math.ceil(e[1]/2);return`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${n[0]}, ${n[1]}));\n\n int index = resTexRC.x * ${n[1]} + resTexRC.y;\n int r = 2 * (index / ${s});\n int c = imod(index, ${s}) * 2;\n\n return ivec2(r, c);\n }\n `}(e,t);case 3:return function(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.x * ${n[1]} + resTexRC.y;\n\n int b = index / ${a};\n index -= b * ${a};\n\n int r = 2 * (index / ${s});\n int c = imod(index, ${s}) * 2;\n\n return ivec3(b, r, c);\n }\n `}(e,t);default:return function(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2);let r=a,i="",o="b, r, c";for(let t=2;te[t])).join(", ")}function $C(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach(((e,n)=>{const s=e.logicalShape,a=t[n],r=a.shape;if(!_(s,r))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${r} must match`);if(e.isUniform&&a.isUniform)return;const i=e.texShape,o=a.isUniform?null:a.texData.texShape;if(!_(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)}))}const{addImpl:CC,bincountImpl:SC,bincountReduceImpl:TC,ceilImpl:EC,concatImpl:AC,expImpl:RC,expm1Impl:FC,floorImpl:DC,gatherV2Impl:_C,greaterImpl:OC,lessImpl:MC,linSpaceImpl:LC,logImpl:zC,maxImpl:BC,maximumImpl:PC,minimumImpl:WC,multiplyImpl:VC,negImpl:UC,prodImpl:GC,rangeImpl:HC,rsqrtImpl:jC,simpleAbsImpl:KC,sliceImpl:qC,stridedSliceImpl:XC,subImpl:YC,tileImpl:JC,topKImpl:ZC,transposeImpl:QC,uniqueImpl:eS}=v;function tS(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function nS(e,t){return 1===t?[e]:tS(e,t)}class sS{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;const t=e.length;if(0===t)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const n=nS("rc",t),s=vC(t),a=function(e,t,n){if(1===e)return`rc > ${t[0]}`;let s="";for(let a=e-2;a= ${t[a]}`,a= ${t};\n bool rEdge = rp1 >= ${n};\n `}(t,e[e.length-1],e[e.length-2],n),i=function(e,t){const n=e.length,s=function(e,t){const n=[];for(let s=0;s<=1;s++)for(let a=0;a<=1;a++){let r=`${0===s?"r":"rp1"}, ${0===a?"c":"cp1"}`;for(let n=2;n= ${e[0]} ? 0. : getA(rc + 1),\n 0, 0`:`getA(${s[0]}),\n cEdge ? 0. : getA(${s[1]}),\n rEdge ? 0. : getA(${s[2]}),\n rEdge || cEdge ? 0. : getA(${s[3]})`}(e,n);this.userCode=`\n void main() {\n ${s} rc = getOutputCoords();\n\n if(${a}) {\n setOutput(vec4(0));\n } else {\n ${r}\n\n setOutput(vec4(${i}));\n }\n }\n `}}}class aS{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\n ${t}\n ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${e>0?"}":""}\n `}var s;this.userCode=`\n ${s=t,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${Y$(["r","c","d"],s)}\n return ivec3(r, c, d);\n }\n `}\n ${J$(e)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${e[1]};\n int cols = ${e[2]};\n\n ${n}\n\n setOutput(result);\n }\n `}}class rS{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const s=oS(t,n),a=lS(e,s,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const r=iS(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=r,this.log();const e=this.freeTextures[a].shift();return this.usedTextures[a].push(e),e}let i;return s===k$.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===k$.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===k$.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===k$.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===k$.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(i),this.numUsedTextures++,this._numBytesAllocated+=r,this.log(),i}releaseTexture(e,t,n,s){if(null==this.freeTextures)return;const a=oS(n,s),r=lS(t,a,s);r in this.freeTextures||(this.freeTextures[r]=[]);const i=iS(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,s),o=ue().get("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==o&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=i):(this.freeTextures[r].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;const l=this.usedTextures[r],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e)}));for(const e in this.usedTextures)this.usedTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function iS(e,t,n,s,a){const r=function(e,t){switch(e){case k$.PACKED_2X2_FLOAT32:return uC(t);case k$.PACKED_2X2_FLOAT16:return cC(t);case k$.UNPACKED_FLOAT32:return iC(t);case k$.UNPACKED_FLOAT16:return oC(t);case k$.PACKED_4X1_UNSIGNED_BYTE:return lC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,s);let i;if(a){const[t,n]=I$(e[0],e[1]);i=t*n}else{const[t,n]=v$(e[0],e[1]);i=t*n}return i*function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}(n,r)}function oS(e,t){if(e===w$.UPLOAD)return k$.PACKED_2X2_FLOAT32;if(e===w$.RENDER||null==e)return function(e){return ue().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?k$.PACKED_2X2_FLOAT32:k$.UNPACKED_FLOAT32:e?k$.PACKED_2X2_FLOAT16:k$.UNPACKED_FLOAT16}(t);if(e===w$.DOWNLOAD||e===w$.PIXELS)return k$.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function lS(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class uS{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=`\n float unaryOperation(float x) {\n ${t}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}const cS="return abs(x);",hS="return x;";class pS{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`\n vec4 unaryOperation(vec4 x) {\n ${t}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}class dS{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=nS("rc",t),s=vC(t),a=function(e,t){if(1===e)return"rc";let n="";for(let s=0;st.push(e)))}const t=this.texData.get(e),{values:n,shape:s,slice:a,dtype:r,complexTensorInfos:i,isPacked:o}=t;if(null!=a){let t;t=o?new pS(s,hS):new uS(s,hS);const n=this.runWebGLProgram(t,[{dataId:e,shape:s,dtype:r}],r),a=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if(!ue().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===ue().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l,u,c=null;if("complex64"!==r&&ue().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);const t=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(t.texture,...N$(s))}if(this.pendingRead.set(e,[]),"complex64"!==r&&await this.gpgpu.createAndWaitForFence(),"complex64"===r){const e=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]);u=Su(e[0],e[1])}else if(null==c)u=this.getValuesFromTexture(e);else{const e=D(s);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}null!=l&&this.disposeIntermediateTensorInfo(l);const h=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach((e=>e(h))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Ir().removeDataId(e,this),this.pendingDeletes--),h}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map((e=>ws(e)))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ha(e.shape,e.dtype,n)}checkNumericalProblems(e){if(null!=e)for(let t=0;t0}async time(e){const t=this.activeTimers,n=[];let s=!1;null==this.programTimersStack?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();const a=F(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),r=F(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,s&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(a);i.kernelMs=function(e){let t=0;for(let n=0;ne.map(((e,t)=>({name:r[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:bs(),endMs:null}}endTimer(e){return ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=bs(),e)}async getQueryTime(e){if(ue().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:s,usage:a,isPacked:r,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),null!=t&&(this.numBytesInGPU-=this.computeBytes(s,n),this.textureManager.releaseTexture(t,s,a,r)));const u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}getCPUBackend(){return ue().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Ir().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=128){const n=this.getCPUBackend();return ue().getBool("IS_TEST")||this.warnedAboutCPUBackend||null!=n||(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),null!=n&&e.every((e=>null==this.texData.get(e.dataId).texture&&D(e.shape)0&&K(n[0])){const a=n.map((e=>xs(e)));s=this.write(a,e,t)}else s=this.write(n,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,n){const{dataId:s}=this.makeTensorInfo(e,t,n);return Ir().makeTensorFromDataId(s,e,t,this)}unpackTensor(e){const t=new dS(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new sS(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[L$(e.shape),...z$(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},a=[L$(t),...z$(t)],r=new aS(a,n),i=this.runWebGLProgram(r,[s],e.dtype,null,!0);return{dataId:i.dataId,shape:t,dtype:i.dtype}}decode(e){const t=this.texData.get(e),{isPacked:n,shape:s,dtype:a}=t,r=B$(s);let i;return i=n?new eC(r):new Q$(r),{dtype:a,shape:s,dataId:this.runWebGLProgram(i,[{shape:r,dtype:a,dataId:e}],a,null,!0).dataId}}runWebGLProgram(e,t,n,s,a=!1){const r=this.makeTensorInfo(e.outputShape,n),i=this.texData.get(r.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===x$.DENSE){const t=N$(e.outputShape);i.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(i.usage=e.outTexUsage),0===D(r.shape))return i.values=V(r.dtype,0),r;const o=[],l=t.map((t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&D(t.shape)<=ue().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}else if(!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),o.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!W$(n.shape,t.shape)){const e=t,s=t.shape;t.shape=n.shape,t=this.packedReshape(t,s),o.push(t),n=this.texData.get(t.dataId),e.shape=s}return this.uploadToGPU(t.dataId),{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(r.dataId);const u={shape:r.shape,texData:i,isUniform:!1},c=function(e,t,n){let s="";t.concat(n).forEach((e=>{const t=null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0,n=e.isUniform?"uniform":e.texData.texShape;s+=`${e.shape}_${n}_${t}`}));const a=e.userCode;let r=e.constructor.name;return r+="_"+s+"_"+a,r}(e,l,u),h=this.getAndSaveBinary(c,(()=>function(e,t,n,s){const a=t.userCode,r=n.map(((e,n)=>{const s={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(s.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:s}})),i=r.map((e=>e.shapeInfo)),o={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},l=dC(r,o,a,t.packedInputs),u=e.createProgram(l);let c=null;const h=e.getUniformLocation(u,"NAN",!1);1===ue().getNumber("WEBGL_VERSION")&&(c=e.getUniformLocation(u,"INFINITY",!1));const p={};for(let n=0;n{const a=t.program.variableNames[s],r=t.uniformLocations[a],i=t.uniformLocations[`offset${a}`];if(null!=r)if(n.isUniform)if(D(n.shape)<2)e.gl.uniform1f(r,n.uniformValues[0]);else{let t=n.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(r,t)}else null!=n.texData.slice&&null!=i&&e.gl.uniform1i(i,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture,r,s)})),null!=a&&a(e,t.webGLProgram),e.executeProgram()}(this.gpgpu,h,l,u,s),o.forEach((e=>this.disposeIntermediateTensorInfo(e))),p&&(d=this.endTimer(d),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(d)}));const f=ue().get("WEBGL_FLUSH_THRESHOLD");if(f>0){const e=bs();e-this.lastGlFlushTime>f&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!ue().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&!1===a){const e=this.unpackTensor(r);return this.disposeIntermediateTensorInfo(r),e}return r}compileAndRun(e,t,n,s,a=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,s,a)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(ue().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Cr((()=>{if(!ue().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=ue().getBool("DEBUG");ue().set("DEBUG",!1);const t=this.abs(Fr(1e-8)).dataSync()[0];if(ue().set("DEBUG",e),t>0)return 32}return 16}))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:s,values:a,texture:r,usage:i,isPacked:o}=t;if(null!=r)return;const l=null!=this.activeTimers;let u;l&&(u=bs());let c=t.texShape;if(null==c&&(c=function(e,t=!1){let n=ue().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,1===(e=e.map(((t,n)=>n>=e.length-2?T(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=W(e);e=t.newShape}let s=D(e);if(e.length<=1&&s<=n)return[1,s];if(2===e.length&&e[0]<=n&&e[1]<=n)return e;if(3===e.length&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){const t=L$(e);let n=2,a=2;return e.length&&([n,a]=z$(e)),s=t*(n/2)*(a/2),M(s).map((e=>2*e))}return M(s)}(n,o),t.texShape=c),null!=a){const e=B$(n);let r,i=c[1],h=c[0];const p=a instanceof Uint8Array;o?([i,h]=I$(c[0],c[1]),r=new aC(e,[h,i],p)):r=new sC(e,[h,i],p);const d=this.makeTensorInfo([h,i],s);this.texData.get(d.dataId).usage=p?w$.PIXELS:w$.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(d.dataId),i,h,a);const f=!0,m=this.runWebGLProgram(r,[d],s,null,f),g=this.texData.get(m.dataId);t.texture=g.texture,t.texShape=g.texShape,t.isPacked=g.isPacked,t.usage=g.usage,this.disposeIntermediateTensorInfo(d),this.texData.delete(m.dataId),t.values=null,l&&(this.uploadWaitMs+=bs()-u)}else{const e=this.acquireTexture(c,i,s,o);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:s}=n;return this.releaseGPUData(e),null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,s)}computeBytes(e,t){return e[0]*e[1]*j(t)}}gS.nextDataId=0,ta()&&Ar("webgl",(()=>new gS),2);class yS{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=vi(t,n),this.userCode=`\n float binaryOperation(float a, float b) {\n ${e}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `}}class bS{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=vi(t,n);const a=this.outputShape.length;let r="";if(s)if(0===a||1===D(this.outputShape))r="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(r=`\n ${vC(a)} coords = getOutputCoords();\n `,1===a)r+=`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const e=nS("coords",a);r+=`\n bool nextRowOutOfBounds =\n (${e[a-2]} + 1) >= ${this.outputShape[a-2]};\n bool nextColOutOfBounds =\n (${e[a-1]} + 1) >= ${this.outputShape[a-1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `}this.userCode=`\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${e}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${r}\n\n setOutput(result);\n }\n `}}function xS(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const wS={kernelName:It,backendName:"webgl",kernelFunc:xS};function kS(e){const{inputs:t,backend:n}=e,{real:s,imag:a}=t,r=n.makeTensorInfo(s.shape,"complex64"),i=n.texData.get(r.dataId),o=xS({inputs:{x:s},backend:n}),l=xS({inputs:{x:a},backend:n});return i.complexTensorInfos={real:o,imag:l},r}const vS={kernelName:ze,backendName:"webgl",kernelFunc:kS},NS="return (a < 0.) ? b * a : a;",IS="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",$S={kernelName:At,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{alpha:r}=s,i=n.makeTensorInfo([],"float32",gs(r,"float32")),o=ue().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bS(IS,a.shape,i.shape):new yS(NS,a.shape,i.shape),l=n.runWebGLProgram(o,[a,i],a.dtype);return n.disposeIntermediateTensorInfo(i),l}},CS="return (a < 0.) ? b * a : a;",SS="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",TS={kernelName:pn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s,alpha:a}=t,r=ue().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bS(SS,s.shape,a.shape):new yS(CS,s.shape,a.shape);return n.runWebGLProgram(r,[s,a],s.dtype)}};function ES({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:s}){return({inputs:a,backend:r})=>{const{x:i}=a,o=r,l=s||i.dtype;if(o.shouldExecuteOnCPU([i])&&null!=n){const e=o.texData.get(i.dataId),t=n(e.values,l);return o.makeTensorInfo(i.shape,l,t)}let u;return u=ue().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new pS(i.shape,t):new uS(i.shape,e),o.runWebGLProgram(u,[i],l)}}function AS({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:a,dtype:r}){return({inputs:i,backend:o})=>{const{a:l,b:u}=i,c=o;if(s&&"complex64"===l.dtype){const t=c.texData.get(l.dataId),n=c.texData.get(u.dataId),[s,a]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,s]=t,a={dataId:n.dataId,dtype:n.dtype,shape:l.shape},r={dataId:s.dataId,dtype:s.dtype,shape:u.shape},i=new yS(e,l.shape,u.shape);return c.runWebGLProgram(i,[a,r],Vs(n.dtype,s.dtype))})),r=kS({inputs:{real:s,imag:a},backend:c});return c.disposeIntermediateTensorInfo(s),c.disposeIntermediateTensorInfo(a),r}const h=r||Vs(l.dtype,u.dtype);if(c.shouldExecuteOnCPU([l,u])&&null!=a){const e=c.texData.get(l.dataId),t=c.texData.get(u.dataId),[n,s]=a(l.shape,u.shape,e.values,t.values,h),r=c.makeTensorInfo(s,h);return c.texData.get(r.dataId).values=n,r}let p;return p=ue().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new bS(t,l.shape,u.shape,n):new yS(e,l.shape,u.shape),c.runWebGLProgram(p,[l,u],h)}}function RS(e,t=!1){if("linear"===e)return"return x;";if("relu"===e)return t?"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n":"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n";if("elu"===e)return t?"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n":"return (x >= 0.0) ? x : (exp(x) - 1.0);";if("relu6"===e)return t?"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n":"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : min(6.0, x);\n";if("prelu"===e)return t?SS:CS;if("leakyrelu"===e)return t?IS:NS;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}class FS{constructor(e,t,n,s=!1,a=!1,r=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;const u=s?e[1]:e[2],c=Math.ceil(u/2),h=s?"i * 2, rc.y":"rc.y, i * 2",p=a?"rc.z, i * 2":"i * 2, rc.z",d=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";i&&(m=o?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${i}\n }`:l?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${i}\n }`:`vec4 activation(vec4 x) {\n ${i}\n }`,g="result = activation(result);");const y=r?"result += getBiasAtOutCoords();":"";r&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]`The new shape (${l}) has ${u} elements and the old shape (${a.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`));const c=i.texData.get(a.dataId);return!c.isPacked||W$(a.shape,l)||null!==c.texture&&W$(c.shape,l)?(i.incRef(a.dataId),{dataId:a.dataId,shape:l,dtype:a.dtype}):function(e,t,n){const s=[L$(e.shape),...z$(e.shape)],a={dtype:e.dtype,shape:s,dataId:e.dataId},r=[L$(t),...z$(t)],i=new aS(r,s),o=n.runWebGLProgram(i,[a],e.dtype,null,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}(a,l,i)}const zS={kernelName:bn,backendName:"webgl",kernelFunc:LS};class BS{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:a,outSize:r}=e;this.outputShape=[s,r];const i=4*Math.floor(n/4),o=n%4;let l="sumValue += dot(values, ones);";if(null!=t){const e=1/t;l=`sumValue += dot(values * ${O(e)?e.toPrecision(2):e}, ones);`}let u="";a%n>0&&(u=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return 0.0;\n }\n `),this.userCode=`\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${u}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${i}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${l}\n }\n\n int inIdx = inOffset + ${i};\n if (${1===o}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${l}\n } else if (${2===o}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${l}\n } else if (${3===o}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${l}\n }\n setOutput(sumValue);\n }\n `}}class PS{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:a,outSize:r}=e;this.outputShape=[s,r];let i="0.0",o="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 1e-20",o="min"):"max"===t&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?l="sumValue":"prod"===t?l="prodValue":"all"===t?l="allValue":"any"===t&&(l="anyValue");const u=4*Math.floor(n/4),c=n%4;let h=`\n if (${"sum"===t}) {\n sumValue += dot(values, ones);\n } else if (${"prod"===t}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${o}(values, minMaxValue);\n }\n `,p="vec4";"all"===t?(i="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===t&&(i="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");let d="";a%n>0&&(d=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${i};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${d}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n vec4 minMaxValue = vec4(${i});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${u}; i += 4) {\n int inIdx = inOffset + i;\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${h}\n }\n\n int inIdx = inOffset + ${u};\n if (${1===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${h}\n } else if (${2===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${h}\n } else if (${3===c}) {\n ${p} values = ${p}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${h}\n }\n setOutput(${l});\n }\n `}}function WS(e,t,n,s){const a=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],s=iu(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}(e.shape);let r=e;for(let i=0;i6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let t=0;t6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=vC(this.rank),a=tS("rc",this.rank),r=new Array(this.rank);for(let e=0;e=2&&c>=2&&(y===b||1===y||1===b),(()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`));const x=(y>b?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([d,f]);E(h===p,(()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`));const w=n?[y,h,d]:[y,d,h],k=s?[b,f,p]:[b,p,f],v=LS({inputs:{x:e},backend:a,attrs:{shape:w}}),N=LS({inputs:{x:t},backend:a,attrs:{shape:k}}),I=[v,N],$=Math.max(y,b),C=n?v.shape[1]:v.shape[2],S=null!=r,T=null!=i,A="leakyrelu"===l,R=null!=l?RS(l,!0):null;let F;if((1===d||1===f)&&C>1e3&&!1===(S||T||A||null!=R)){let e=v,t=N;n&&(e=KS({inputs:{x:v},backend:a,attrs:{perm:[0,2,1]}}),I.push(e)),s&&(t=KS({inputs:{x:N},backend:a,attrs:{perm:[0,2,1]}}),I.push(t));const r=1===f;let i=e;1!==f&&(i=LS({inputs:{x:e},backend:a,attrs:{shape:[$,C,1]}}),I.push(i));const o=1===f?2:1;let l=t;r&&(l=LS({inputs:{x:t},backend:a,attrs:{shape:[$,1,C]}}),I.push(l));const u=OS({inputs:{a:i,b:l},backend:a});F=HS({inputs:{x:u},backend:a,attrs:{axis:o,keepDims:!0}}),I.push(u)}else{const l=Vs(e.dtype,t.dtype),u=new FS(w,k,[$,d,f],n,s,S,R,T,A),c=[v,N];if(null!=r&&c.push(r),T&&c.push(i),A){const e=a.makeTensorInfo([],"float32",gs(o,"float32"));c.push(e),I.push(e)}F=a.runWebGLProgram(u,c,l)}const _=LS({inputs:{x:F},backend:a,attrs:{shape:x}});I.push(F);for(const e of I)a.disposeIntermediateTensorInfo(e);return _}const YS={kernelName:rs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a,b:r,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=s;return XS({a,b:r,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},JS="return abs(x);",ZS={kernelName:fe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])&&"complex64"!==s.dtype){const e=n.texData.get(s.dataId),t=KC(e.values);return n.makeTensorInfo(s.shape,s.dtype,t)}let a;return a=ue().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new pS(s.shape,JS):new uS(s.shape,JS),n.runWebGLProgram(a,[s],s.dtype)}},QS=ES({opSnippet:"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),eT={kernelName:me,backendName:"webgl",kernelFunc:QS},tT=ES({opSnippet:"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),nT={kernelName:ge,backendName:"webgl",kernelFunc:tT},sT="return a + b;",aT=AS({opSnippet:sT,packedOpSnippet:sT,supportsComplex:!0,cpuKernelImpl:CC}),rT={kernelName:ye,backendName:"webgl",kernelFunc:aT};class iT{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`float v${e} = get${e}AtOutCoords();`)}));const s=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n float result = ${s};\n setOutput(result);\n }\n `}}class oT{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`vec4 v${e} = get${e}AtOutCoords();`)}));const s=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n void main() {\n ${n.join("\n ")}\n\n vec4 result = ${s};\n setOutput(result);\n }\n `}}const lT={kernelName:be,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s}=t,a=n;if(1===a.length)return xS({inputs:{x:a[0]},backend:s});if(a.length>ue().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(a.length/2),n=e({inputs:a.slice(0,t),backend:s}),r=e({inputs:a.slice(t),backend:s});return e({inputs:[n,r],backend:s})}const r=a.map((e=>e.dtype)).reduce(((e,t)=>Vs(e,t))),i=a.map((e=>e.shape)),o=ue().getBool("WEBGL_PACK")?new oT(a[0].shape,i):new iT(a[0].shape,i);return s.runWebGLProgram(o,a,r)}},uT={kernelName:xe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r,keepDims:i}=s,o=a.shape.length,l=P(r,a.shape);let u=l;const c=Zi(u,o);let h=a;null!=c&&(h=KS({inputs:{x:a},backend:n,attrs:{perm:c}}),u=eo(u.length,o)),Ji("all",u,o);const[p,d]=Xi(h.shape,u),f=LS({inputs:{x:h},backend:n,attrs:{shape:[-1,D(d)]}}),m=WS(f,f.dtype,"all",n);let g;return g=LS(i?{inputs:{x:m},backend:n,attrs:{shape:Yi(p,l)}}:{inputs:{x:m},backend:n,attrs:{shape:p}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}},cT={kernelName:we,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r,keepDims:i}=s,o=a.shape.length,l=P(r,a.shape);let u=l;const c=Zi(u,o);let h=a;null!=c&&(h=KS({inputs:{x:a},backend:n,attrs:{perm:c}}),u=eo(u.length,o)),Ji("any",u,o);const[p,d]=Xi(h.shape,u),f=LS({inputs:{x:h},backend:n,attrs:{shape:[-1,D(d)]}}),m=WS(f,f.dtype,"any",n);let g;return g=LS(i?{inputs:{x:m},backend:n,attrs:{shape:Yi(p,l)}}:{inputs:{x:m},backend:n,attrs:{shape:p}}),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),null!=c&&n.disposeIntermediateTensorInfo(h),g}};class hT{constructor(e,t,n){this.variableNames=["A"];const{windowSize:s,batchSize:a,outSize:r}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,r];const i="max"===t?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${s};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${s}; i++) {\n int inIdx = ${o};\n float candidate = getA(batch, inIdx);\n if (candidate ${i} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}}class pT{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,E(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const a=e[e.length-1],r=Math.ceil(a/t);this.outputShape=e.slice(0,-1),r>1&&this.outputShape.push(r),s||this.variableNames.push("bestIndicesA");const i=this.outputShape,o=i.length,l=vC(o),u=nS("coords",o);let c,h;if(1===r){h=o+1;const e=vC(h);c=`\n ${e} sourceLocR = ${e}(${u.join()}, 0);\n ++${u[o-1]};\n ${e} sourceLocG = ${e}(${u.join()}, 0);\n ++${u[o-2]};\n ${e} sourceLocA = ${e}(${u.join()}, 0);\n --${u[o-1]};\n ${e} sourceLocB = ${e}(${u.join()}, 0);\n --${u[o-2]};`}else h=o,c=`\n ${l} sourceLocR = coords;\n ++${u[o-1]};\n ${l} sourceLocG = coords;\n ++${u[o-2]};\n ${l} sourceLocA = coords;\n --${u[o-1]};\n ${l} sourceLocB = coords;\n --${u[o-2]};`;const p=["x","y","z","w","u","v"].slice(0,h),d="."+p[h-1],f=p.map((e=>"int "+e)),m=nS("sourceLocR",h-1).concat("inIdx.r"),g=nS("sourceLocG",h-1).concat("inIdx.g"),y=nS("sourceLocB",h-1).concat("inIdx.b"),b=nS("sourceLocA",h-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",w=s?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\n getBestIndicesAChannel(${g.join()}),\n getBestIndicesAChannel(${y.join()}),\n getBestIndicesAChannel(${b.join()})));`,k=`vec4(\n getAChannel(${m.join()}),\n hasNextCol ? getAChannel(${g.join()}) : 0.,\n hasNextRow ? getAChannel(${y.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,v=s?"":`\n float getBestIndicesAChannel(${f.join()}) {\n return getChannel(getBestIndicesA(${p.join()}),\n vec2(${p.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${f.join()}) {\n return getChannel(getA(${p.join()}),\n vec2(${p.slice(-2).join()}));\n }\n ${v}\n void main() {\n ${l} coords = getOutputCoords();\n bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};\n bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};\n ${c}\n ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},\n sourceLocB${d}, sourceLocA${d}) * ${t};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${k};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${w}\n vec4 candidate = ${k};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `}}function dT(e,t,n,s=null){let a=t.shape[0],r=t.shape[1];null!=s&&(a=s.shape[0],r=s.shape[1]);const i=iu(r),o={windowSize:i,inSize:r,batchSize:a,outSize:Math.ceil(r/i)},l=new hT(o,n,null==s),u=[t];null!=s&&u.push(s);const c=e.runWebGLProgram(l,u,"int32");if(1===c.shape[1])return c;const h=dT(e,t,n,c);return e.disposeIntermediateTensorInfo(c),h}function fT(e,t,n,s=null){const a=null!=s?s.shape:t.shape,r=iu(a[a.length-1]),i=new pT(a,r,n,null==s),o=null==s?[t]:[t,s],l=e.runWebGLProgram(i,o,"int32");if(l.shape.length===t.shape.length){const s=fT(e,t,n,l);return e.disposeIntermediateTensorInfo(l),s}return l}function mT(e,t,n,s){const a=[n];if(Ji("arg"+s.charAt(0).toUpperCase()+s.slice(1),a,t.shape.length),!ue().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],[r,i]=Xi(t.shape,a),o=D(i),l=LS({inputs:{x:t},backend:e,attrs:{shape:[-1,o]}});n.push(l);const u=dT(e,l,s);n.push(u);const c=LS({inputs:{x:u},backend:e,attrs:{shape:r}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),c}return fT(e,t,s)}const gT={kernelName:ke,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r}=s;let i=P(r,a.shape);const o=Zi(i,a.shape.length);let l=a;const u=[];null!=o&&(l=KS({inputs:{x:a},backend:n,attrs:{perm:o}}),u.push(l),i=eo(i.length,l.shape.length)),Ji("argMax",[i[0]],l.shape.length);const c=mT(n,l,i[0],"max");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},yT={kernelName:ve,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r}=s;let i=P(r,a.shape);const o=Zi(i,a.shape.length);let l=a;const u=[];null!=o&&(l=KS({inputs:{x:a},backend:n,attrs:{perm:o}}),u.push(l),i=eo(i.length,l.shape.length)),Ji("argMin",[i[0]],l.shape.length);const c=mT(n,l,i[0],"min");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},bT=ES({opSnippet:"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),xT={kernelName:Ne,backendName:"webgl",kernelFunc:bT},wT=ES({opSnippet:"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));"}),kT={kernelName:Ie,backendName:"webgl",kernelFunc:wT},vT=ES({opSnippet:"if (isnan(x)) return x;\n return atan(x);\n"}),NT={kernelName:$e,backendName:"webgl",kernelFunc:vT},IT=AS({opSnippet:"\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",packedOpSnippet:"\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),$T={kernelName:Se,backendName:"webgl",kernelFunc:IT},CT=ES({opSnippet:"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),ST={kernelName:Ce,backendName:"webgl",kernelFunc:CT};class TT{constructor(e,t,n,s=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const r=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec2 strides = ivec2(${i}, ${o});\n const ivec2 pads = ivec2(${p}, ${d});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${l}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${h};\n wC += ${u}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${s?a?m:g:`wR * ${h} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / count");const x=4*Math.floor(r/4),w=r%4,k=`\n if (${f}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${i}, ${o});\n const ivec2 pads = ivec2(${p}, ${d});\n const float initializationValue = ${y};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${y});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${l}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${x}; wC += 4) {\n int xC = xCCorner + wC * ${u};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n getValue(batch, xR, xC + 2 * ${u}, d),\n getValue(batch, xR, xC + 3 * ${u}, d)\n );\n\n ${k}\n }\n\n int xC = xCCorner + ${x};\n if (${1===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${k}\n } else if (${2===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n initializationValue,\n initializationValue\n );\n\n ${k}\n } else if (${3===w}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${u}, d),\n getValue(batch, xR, xC + 2 * ${u}, d),\n initializationValue\n );\n\n ${k}\n }\n }\n setOutput(${b});\n }\n `}}class ET{constructor(e,t,n,s=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const r=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,c=e.dilationHeight,h=e.dilationWidth,p=e.effectiveFilterDepth,d=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const b="avg"===t;let x="0.0";if(b||(x="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec3 strides =\n ivec3(${i}, ${o}, ${l});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < ${p};\n wD += ${u}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${d};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${f};\n wC += ${h}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${s?a?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${d} * ${f} +\n wR * ${f} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(w="avgValue / count");const k=4*Math.floor(r/4),v=r%4,N=`\n if (${b}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec3 strides =\n ivec3(${i}, ${o}, ${l});\n const ivec3 pads = ivec3(${m}, ${g}, ${y});\n const float initializationValue = ${x};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4(${x});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${p};\n wD += ${u}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${d};\n wR += ${c}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${k}; wC += 4) {\n int xC = xCCorner + wC * ${h};\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n getValue(batch, xD, xR, xC + 3 * ${h}, ch)\n );\n\n ${N}\n }\n\n int xC = xCCorner + ${k};\n if (${1===v}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${N}\n } else if (${2===v}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n initializationValue,\n initializationValue\n );\n\n ${N}\n } else if (${3===v}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${h}, ch),\n getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n initializationValue\n );\n\n ${N}\n }\n }\n setOutput(${w});\n }\n }\n `}}const AT={kernelName:Te,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t;K$(a,"avgPool");const{filterSize:r,strides:i,pad:o,dimRoundingMode:l}=s;E(Yr(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Pr(a.shape,r,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&_(u.inShape,u.outShape))return xS({inputs:{x:a},backend:n});const c=new TT(u,"avg",!1);return n.runWebGLProgram(c,[a],"float32")}},RT={kernelName:Ae,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{filterSize:r,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s,c=Wr(a.shape,r,i,[1,1,1],o,l,u),h=new ET(c,"avg",!1);return n.runWebGLProgram(h,[a],"float32")}};class FT{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,a=e.strideWidth,r=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,c=l-1-e.padInfo.left,h=1/(t*n);this.userCode=`\n const ivec2 pads = ivec2(${u}, ${c});\n const float avgMultiplier = float(${h});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${o};\n wR += ${r}) {\n float dyR = float(dyRCorner + wR) / ${s}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${l};\n wC+= ${i}) {\n float dyC = float(dyCCorner + wC) / ${a}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `}}class DT{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,a=e.strideDepth,r=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=c-1-e.padInfo.front,f=h-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*s);this.userCode=`\n const ivec3 pads = ivec3(${d}, ${f}, ${m});\n const float avgMultiplier = float(${g});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${c};\n wD += ${o}) {\n float dyD = float(dyDCorner + wD) / ${a}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${h};\n wR += ${l}) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${p};\n wC += ${u}) {\n float dyC = float(dyCCorner + wC) / ${i}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const _T={kernelName:Re,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,input:r}=t,i=r,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,h=Wr(i.shape,o,l,[1,1,1],u,c),p=new DT(h);return n.runWebGLProgram(p,[a],i.dtype)}},OT={kernelName:Ee,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,input:r}=t,i=r;K$([a,r],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=Pr(i.shape,o,l,1,u),h=new FT(c);return n.runWebGLProgram(h,[a],i.dtype)}},MT={kernelName:Fe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a,b:r}=t,{transposeA:i,transposeB:o}=s;return XS({a,b:r,transposeA:i,transposeB:o,backend:n})}};class LT{constructor(e,t,n,s,a,r){this.outputShape=[],this.variableNames=["x","mean","variance"],vi(e,t),vi(e,n);let i="0.0";null!=s&&(vi(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=a&&(vi(e,a),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${i};\n float scale = ${o};\n float inv = scale * inversesqrt(variance + float(${r}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `}}class zT{constructor(e,t,n,s,a,r){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],vi(e,t),vi(e,n);let i="vec4(0.0)";null!=s&&(vi(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=a&&(vi(e,a),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n void main() {\n vec4 offset = ${i};\n vec4 scale = ${o};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${r}));\n\n setOutput((x - mean) * inv + offset);\n }\n `}}const BT={kernelName:xt,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:a,variance:r,offset:i,scale:o}=e;E(a.shape.length===r.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),E(null==i||a.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),E(null==o||a.shape.length===o.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));let{varianceEpsilon:l}=n;null==l&&(l=.001);const u=[s,a,r];let c=null;null!=i&&(c=i.shape,u.push(i));let h=null;null!=o&&(h=o.shape,u.push(o));const p=ue().getBool("WEBGL_PACK_NORMALIZATION")?new zT(s.shape,a.shape,r.shape,c,h,l):new LT(s.shape,a.shape,r.shape,c,h,l);return t.runWebGLProgram(p,u,u[0].dtype)}};class PT{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=vC(this.rank),n=`uniform int start[${this.rank}];`,s=function(e){if(1===e)return"sourceLoc";if(e<=6)return WT.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let a;a=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${e.map(((e,t)=>`sourceLoc.${WT[t]} = start[${t}] + coords.${WT[t]};`)).join("\n")}\n `,this.userCode=`\n ${n}\n void main() {\n ${a}\n setOutput(getSource(${s}));\n }\n `}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{null==this.startLoc&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),null==this.startLoc)||t.gl.uniform1iv(this.startLoc,e)}}}const WT=["x","y","z","w","u","v"];class VT{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=vC(this.rank),n=nS("coords",this.rank),s=nS("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":`vec2(${s.slice(-2).join()})`,r=`getChannel(getSource(${s.join()}), ${a})`,i=`\n result.x = ${r};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${s[this.rank-1]};\n result.y = ${r};\n --${s[this.rank-1]};\n }\n `,o=1===this.rank?"":`\n --${n[this.rank-1]};\n if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n ++${s[this.rank-2]};\n result.z = ${r};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${s[this.rank-1]};\n result.w = ${r};\n }\n }\n `,l=this.rank<=4?`sourceLoc = coords +\n ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${s[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n uniform int start[${this.rank}];\n void main() {\n ${t} coords = getOutputCoords();\n ${t} sourceLoc;\n ${l}\n vec4 result = vec4(0.);\n ${i}\n ${o}\n setOutput(result);\n }\n `}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{null==this.startLoc&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),null==this.startLoc)||t.gl.uniform1iv(this.startLoc,e)}}}function UT(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{begin:r,size:i}=s,[o,l]=xr(a,r,i);if(rr(a,o,l),0===D(l))return n.makeTensorInfo(l,a.dtype,[]);if(n.shouldExecuteOnCPU([a])||"string"===a.dtype){const e=n.texData.get(a.dataId),t=qC(e.values,o,l,a.shape,a.dtype);return n.makeTensorInfo(l,a.dtype,t)}const{isPacked:u}=n.texData.get(a.dataId),c=yr(a.shape,o,l);if(u||!c){const e=ue().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new VT(l):new PT(l),t=e.getCustomSetupFunc(o);return n.runWebGLProgram(e,[a],a.dtype,t)}return n.uploadToGPU(a.dataId),function(e,t,n,s){const a=s.texData.get(e.dataId),r=s.makeTensorInfo(n,e.dtype),i=s.texData.get(r.dataId);Object.assign(i,a),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=br(t,Z(e.shape));a.slice&&(o+=a.slice.flatOffset),i.slice={flatOffset:o,origDataId:a.slice&&a.slice.origDataId||e.dataId};const l=s.dataRefCount.get(i.slice.origDataId)||1;return s.dataRefCount.set(i.slice.origDataId,l+1),r}(a,o,l,n)}const GT={kernelName:An,backendName:"webgl",kernelFunc:UT},HT={kernelName:De,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{blockShape:r,crops:i}=s;E(a.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const o=r.reduce(((e,t)=>e*t)),l=lu(a.shape,r,o),u=uu(l.length,r.length),c=cu(a.shape,r,o),h=hu(i,r.length),p=pu(c,i,r.length),d=[],f=LS({inputs:{x:a},backend:n,attrs:{shape:l}}),m=KS({inputs:{x:f},backend:n,attrs:{perm:u}}),g=LS({inputs:{x:m},backend:n,attrs:{shape:c}}),y=UT({inputs:{x:g},backend:n,attrs:{begin:h,size:p}});return d.push(f),d.push(m),d.push(g),d.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}},jT={kernelName:_e,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,weights:r}=t,{size:i}=s,o=n.readSync(a.dataId),l=n.readSync(r.dataId),u=SC(o,l,r.dtype,r.shape,i);return n.makeTensorInfo([i],r.dtype,u)}},KT=AS({opSnippet:"return float(a != b);",dtype:"bool"}),qT={kernelName:nn,backendName:"webgl",kernelFunc:KT};function XT(e){const{inputs:t,backend:n}=e,{input:s}=t;return xS({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.real},backend:n})}const YT={kernelName:mn,backendName:"webgl",kernelFunc:XT},JT={kernelName:Oe,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s,attrs:a}=t,{x:r}=n,{dtype:i}=a;if("complex64"===i){if("complex64"===r.dtype)return xS({inputs:{x:r},backend:s});const t=io(r.shape),n=e({inputs:{x:r},backend:s,attrs:{dtype:"float32"}}),a=kS({inputs:{real:n,imag:t},backend:s});return t.dispose(),s.disposeIntermediateTensorInfo(n),a}if("complex64"===r.dtype){const t=XT({inputs:{input:r},backend:s}),n=e({inputs:{x:t},backend:s,attrs:{dtype:i}});return s.disposeIntermediateTensorInfo(t),n}if(!G(r.dtype,i)){const e=xS({inputs:{x:r},backend:s});return{dataId:e.dataId,shape:e.shape,dtype:i}}if("int32"===i)return function(e,t){const n=new uS(e.shape,"return float(int(x));"),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}(r,s);if("bool"===i){const e=s.makeTensorInfo([],"bool",V("bool",1)),t=KT({inputs:{a:r,b:e},backend:s});return s.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${i}`)}},ZT="return ceil(x);",QT=ES({opSnippet:ZT,packedOpSnippet:ZT,cpuKernelImpl:EC}),eE={kernelName:Me,backendName:"webgl",kernelFunc:QT};class tE{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}getCustomSetupFunc(e,t){return(n,s)=>{null==this.minLoc&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class nE{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}getCustomSetupFunc(e,t){return(n,s)=>{null==this.minLoc&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}const sE={kernelName:Le,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{clipValueMin:r,clipValueMax:i}=s;let o;o=ue().getBool("WEBGL_PACK_CLIP")?new nE(a.shape):new tE(a.shape);const l=o.getCustomSetupFunc(r,i);return n.runWebGLProgram(o,[a],a.dtype,l)}};class aE{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "}}function rE(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const iE={kernelName:Be,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,a=n.texData.get(s.dataId),r=new aE(s.shape),i=[rE(s,a.complexTensorInfos.real),rE(s,a.complexTensorInfos.imag)];return n.runWebGLProgram(r,i,i[0].dtype)}};class oE{constructor(e){this.outputShape=[],this.outputShape=au(e,1),this.variableNames=e.map(((e,t)=>`T${t}`));const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n`T${t}`));const o=new Array(e.length-1);o[0]=e[0][t];for(let n=1;n= ${o[e-1]}) {\n return getChannel(\n getT${e}(${uE(i,l,t)}),\n vec2(${uE(u,l,t)}));\n }`}const p=o.length,d=o[o.length-1];h+=`\n return getChannel(\n getT${p}(${uE(i,l,d)}),\n vec2(${uE(u,l,d)}));`,this.userCode=`\n float getValue(${i.map((e=>"int "+e))}) {\n ${h}\n }\n\n void main() {\n ${a} coords = getOutputCoords();\n vec4 result = vec4(getValue(${r}), 0., 0., 0.);\n\n ${r[s-1]} = ${r[s-1]} + 1;\n if (${r[s-1]} < ${n[s-1]}) {\n result.g = getValue(${r});\n }\n\n ${r[s-2]} = ${r[s-2]} + 1;\n if (${r[s-2]} < ${n[s-2]}) {\n result.a = getValue(${r});\n }\n\n ${r[s-1]} = ${r[s-1]} - 1;\n if (${r[s-2]} < ${n[s-2]} &&\n ${r[s-1]} < ${n[s-1]}) {\n result.b = getValue(${r});\n }\n setOutput(result);\n }\n `}}function uE(e,t,n){const s=e.indexOf(t);return e.map(((e,t)=>t===s?`${e} - ${n}`:e)).join()}function cE(e){const{inputs:t,backend:n}=e,{input:s}=t;return xS({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.imag},backend:n})}const hE={kernelName:Ct,backendName:"webgl",kernelFunc:cE};function pE(e,t,n){const s=e[0].dtype;if("complex64"===s){const s=e.map((e=>XT({inputs:{input:e},backend:n}))),a=e.map((e=>cE({inputs:{input:e},backend:n}))),r=pE(s,t,n),i=pE(a,t,n),o=kS({inputs:{real:r,imag:i},backend:n});return s.forEach((e=>n.disposeIntermediateTensorInfo(e))),a.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(i),o}if("string"===s){const{tensors2D:a,outShape:r}=dE(e,t,n),i=a.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),o=1===a[0].shape[0],l=AC(i,r,s,o),u=au(e.map((e=>e.shape)),t),c=n.makeTensorInfo(u,s,l);return a.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}if(e.length>ue().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const s=Math.floor(e.length/2),a=pE(e.slice(0,s),t,n),r=pE(e.slice(s),t,n),i=pE([a,r],t,n);return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(r),i}if(ue().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const a=new lE(e.map((e=>e.shape)),t);return n.runWebGLProgram(a,e,s)}const{tensors2D:a,outShape:r}=dE(e,t,n),i=new oE(a.map((e=>e.shape))),o=n.runWebGLProgram(i,a,s);a.forEach((e=>n.disposeIntermediateTensorInfo(e)));const l=LS({inputs:{x:o},attrs:{shape:r},backend:n});return n.disposeIntermediateTensorInfo(o),l}function dE(e,t,n){const s=au(e.map((e=>e.shape)),t);return{tensors2D:e.map((e=>LS({inputs:{x:e},attrs:{shape:[-1,D(e.shape.slice(t))]},backend:n}))),outShape:s}}function fE(e){const{inputs:t,backend:n,attrs:s}=e,{axis:a}=s,r=P(a,t[0].shape)[0],i=au(t.map((e=>e.shape)),r);if(0===D(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>D(e.shape)>0));return 1===o.length?xS({inputs:{x:o[0]},backend:n}):(su(o.map((e=>e.shape)),r),pE(o,r,n))}const mE={kernelName:Pe,backendName:"webgl",kernelFunc:fE};class gE{constructor(e,t=!1,n=null,s=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const r=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,h=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let x="",w="";n&&(x=s?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,w="result = activation(result);");const k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${x}\n\n const ivec2 strides = ivec2(${o}, ${l});\n const ivec2 pads = ivec2(${r}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${b}];\n\n ivec2 xRCCorner =\n ivec2(coords[${g}], coords[${y}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${h}; wR++) {\n int xR = xRCorner + wR * ${u};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${c};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${d}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${m}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${1===f}) {\n\n if (${m}) {\n dotProd +=\n getX(batch, xR, xC, ${d}) *\n getW(wR, wC, ${d}, d2);\n } else {\n dotProd +=\n getX(batch, ${d}, xR, xC) *\n getW(wR, wC, ${d}, d2);\n }\n\n } else if (${2===f}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===f}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2),\n getW(wR, wC, ${d} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1),\n getX(batch, xR, xC, ${d} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC),\n getX(batch, ${d} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${k}\n ${w}\n setOutput(result);\n }\n `}}class yE{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,a=e.strideDepth,r=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.filterDepth,h=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\n const ivec3 strides = ivec3(${a}, ${r}, ${i});\n const ivec3 pads = ivec3(${t}, ${n}, ${s});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < ${c}; wF++) {\n int xF = xFCorner + wF * ${o};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${h}; wR++) {\n int xR = xRCorner + wR * ${l};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p}; wC++) {\n int xC = xCCorner + wC * ${u};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${d}; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (${1===f}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${d}) *\n getW(wF, wR, wC, ${d}, d2);\n } else if (${2===f}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${d}),\n getX(batch, xF, xR, xC, ${d} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${d}, d2),\n getW(wF, wR, wC, ${d} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${3===f}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${d}),\n getX(batch, xF, xR, xC, ${d} + 1),\n getX(batch, xF, xR, xC, ${d} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${d}, d2),\n getW(wF, wR, wC, ${d} + 1, d2),\n getW(wF, wR, wC, ${d} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class bE{constructor(e,t,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;const{filterWidth:s,inChannels:a,strideWidth:r,strideHeight:i,padInfo:o,outWidth:l,dilationWidth:u,dilationHeight:c,dataFormat:h}=n,{left:p,top:d}=o,f=a*s,m=X$(),g="channelsLast"===h,y=g?0:1,b=g?1:2;let x="";for(let n=0;n<=1;n++)for(let s=0;s<=1;s++)x+=`\n blockIndex = rc.y + ${s};\n pos = rc.x + ${n};\n\n if(blockIndex < ${e[1]} && pos < ${e[0]}) {\n offsetY = int(blockIndex / (${l})) * ${i} - ${d};\n d0 = offsetY + ${c} * (pos / ${f});\n\n if(d0 < ${t[y]} && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), ${l}.) * ${r}. - ${p}.);\n d1 = offsetX + ${u} * (int(mod(float(pos), ${f}.) / ${a}.));\n\n if(d1 < ${t[b]} && d1 >= 0) {\n\n ch = int(mod(float(pos), ${a}.));\n\n if (${g}) {\n innerDims = vec2(d1, ch);\n result[${2*n+s}] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*n+s}] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${x}\n\n ${m.output} = result;\n }\n `}}function xE({x:e,filter:t,convInfo:n,backend:s,bias:a=null,preluActivationWeights:r=null,leakyreluAlpha:i=0,activation:o=null}){const l=e.shape,u=s.texData.get(e.dataId),c=n.inChannels,h=l[0]*l[1]*l[2],p=n.outChannels,d="channelsLast"===n.dataFormat;let f;const m=[],g=(1===h||1===p)&&c>1e3,y=l[2]%2!=0&&!!u.isPacked;if(!g&&ue().getBool("WEBGL_LAZILY_UNPACK")&&ue().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&y){const c=d?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),h={dataId:e.dataId,shape:[1,c,n.inChannels],dtype:e.dtype},p=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,E(W$(u.shape,h.shape),(()=>`packed reshape ${u.shape} to ${h.shape} isn't free`));const g=LS({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});m.push(g);const y=XS({a:h,b:g,backend:s,transposeA:!1,transposeB:!1,bias:a,activation:o,preluActivationWeights:r,leakyreluAlpha:i}),b=s.texData.get(y.dataId);E(b.isPacked,(()=>"batchMatMul result is expected to be packed")),u.shape=p,b.shape=n.outShape,f=xS({inputs:{x:y},backend:s}),f.shape=n.outShape,m.push(y)}else{const u=LS({inputs:{x:e},backend:s,attrs:{shape:[1,d?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],n.inChannels]}}),c=LS({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),h=XS({a:u,b:c,transposeA:!1,transposeB:!1,backend:s,bias:a,activation:o,preluActivationWeights:r,leakyreluAlpha:i});f=LS({inputs:{x:h},backend:s,attrs:{shape:n.outShape}}),m.push(u),m.push(c),m.push(h)}for(const e of m)s.disposeIntermediateTensorInfo(e);return f}function wE({x:e,filter:t,convInfo:n,backend:s,bias:a=null,preluActivationWeights:r=null,leakyreluAlpha:i=0,activation:o=null}){const{filterWidth:l,filterHeight:u,inChannels:c,outWidth:h,outHeight:p,dataFormat:d}=n,f="channelsLast"===d,m=l*u*c,g=p*h,y=[m,g],b=[],x=LS({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),w=LS({inputs:{x:t},backend:s,attrs:{shape:[1,m,D(t.shape)/m]}});b.push(x),b.push(w);const k=new bE(y,x.shape,n),v=s.runWebGLProgram(k,[x],"float32"),N=LS({inputs:{x:v},backend:s,attrs:{shape:[1,y[0],y[1]]}});b.push(v),b.push(N);const I=null!=a,$=null!=r,C="leakyrelu"===o,S=o?RS(o,!0):null,T=new FS(N.shape,w.shape,[1,g,n.outChannels],!0,!1,I,S,$,C),E=[N,w];if(a&&E.push(a),$&&E.push(r),C){const e=s.makeTensorInfo([],"float32",gs(i,"float32"));E.push(e),b.push(e)}const A=s.runWebGLProgram(T,E,"float32"),R=LS({inputs:{x:A},backend:s,attrs:{shape:f?[1,p,h,n.outChannels]:[1,n.outChannels,p,h]}});b.push(A);for(const e of b)s.disposeIntermediateTensorInfo(e);return R}const kE={kernelName:We,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,filter:r}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s,h=Jr(l),p=Vr(a.shape,r.shape,i,u,o,c,!1,h);let d;if(1!==p.filterHeight||1!==p.filterWidth||1!==p.dilationHeight||1!==p.dilationWidth||1!==p.strideHeight||1!==p.strideWidth||"SAME"!==p.padInfo.type&&"VALID"!==p.padInfo.type)if(ue().getBool("WEBGL_CONV_IM2COL")&&1===a.shape[0])d=wE({x:a,filter:r,convInfo:p,backend:n});else{const e=new gE(p);d=n.runWebGLProgram(e,[a,r],"float32")}else d=xE({x:a,filter:r,convInfo:p,backend:n});const f=LS({inputs:{x:d},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(d),f}};class vE{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,a=e.padInfo.left,r="channelsLast"===e.dataFormat;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${s};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${a};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n if (${r}) {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class NE{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,a=e.strideWidth,r="channelsLast"===e.dataFormat,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=r?1:2,u=r?2:3,c=r?3:1;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${c}];\n\n ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${s}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${a}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n if (${r}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class IE{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,a=e.padInfo.front,r=e.padInfo.top,i=e.padInfo.left;this.userCode=`\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yF = 0; yF < ${e.outDepth}; yF++) {\n int xF = wF + yF * ${t} - ${a};\n\n if (xF < 0 || xF >= ${e.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${n} - ${r};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${s} - ${i};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class $E{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,a=e.strideDepth,r=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=s-1-e.padInfo.left;this.userCode=`\n const ivec3 pads = ivec3(${o}, ${l}, ${u});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < ${t}; wF++) {\n float dyF = float(dyFCorner + wF) / ${a}.0;\n\n if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${t} - 1 - wF;\n\n for (int wR = 0; wR < ${n}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${n} - 1 - wR;\n\n for (int wC = 0; wC < ${s}; wC++) {\n float dyC = float(dyCCorner + wC) / ${i}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${s} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const CE={kernelName:Ve,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,dy:r}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:c}=s,h=Jr(l),p=Vr(a.shape,c,i,1,o,u,!1,h),d=new vE(p);return n.runWebGLProgram(d,[a,r],"float32")}},SE={kernelName:Ue,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,filter:r}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:c}=s,h=Jr(u),p=Vr(i,r.shape,o,1,l,c,!1,h),d=new NE(p);return n.runWebGLProgram(d,[a,r],"float32")}},TE={kernelName:Ge,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,filter:r}=t,{strides:i,pad:o,dilations:l}=s,u=Ur(a.shape,r.shape,i,l,o),c=new yE(u);return n.runWebGLProgram(c,[a,r],"float32")}},EE={kernelName:He,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,dy:r}=t,{strides:i,pad:o,filterShape:l}=s,u=Ur(a.shape,l,i,1,o),c=new IE(u);return n.runWebGLProgram(c,[a,r],"float32")}},AE={kernelName:je,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,filter:r}=t,{pad:i,strides:o,inputShape:l}=s,u=Ur(l,r.shape,o,1,i),c=new $E(u);return n.runWebGLProgram(c,[a,r],"float32")}},RE=ES({opSnippet:"if (isnan(x)) return x;\n return cos(x);\n"}),FE={kernelName:Ke,backendName:"webgl",kernelFunc:RE},DE=ES({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),_E={kernelName:qe,backendName:"webgl",kernelFunc:DE};class OE{constructor(e,t,n,s,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[r,i,o,l]=e,[u]=t,[c,h]=n;this.outputShape=[u,c,h,l];const p="bilinear"===s?1:0,[d,f]=[i-1+".0",o-1+".0"],[m,g,y]=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[b,x,w]=h>1?[""+(o-1)/(h-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\n const float height_ratio = float(${m});\n const float width_ratio = float(${b});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${r}) {\n return;\n }\n\n float height_scale = ${g};\n float width_scale = ${x};\n\n float in_y = ${y};\n if( in_y < 0.0 || in_y > ${d} ) {\n setOutput(float(${a}));\n return;\n }\n float in_x = ${w};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${a}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${p} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n `}}const ME={kernelName:Ye,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{image:a,boxes:r,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=s,c=new OE(a.shape,r.shape,o,l,u);return n.runWebGLProgram(c,[a,r,i],"float32")}};class LE{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,a=t?"0.0":`getX(${zE(s,"coords")})`,r=e[e.length-1];let i="",o="";t?(i=n?"end != "+(r-1):"end != 0",o=n?"end + 1":"end - 1"):(i=n?`end + pow2 < ${r}`:"end >= pow2",o=n?"end + pow2":"end - pow2"),this.userCode=`\n uniform float index;\n void main() {\n ${vC(s)} coords = getOutputCoords();\n int end = ${BE(s,"coords")};\n float val = ${a};\n int pow2 = int(pow(2.0, index));\n if (${i}) {\n int idx = ${o};\n ${BE(s,"coords")} = idx;\n val += getX(${zE(s,"coords")});\n }\n setOutput(val);\n }\n `}getCustomSetupFunc(e){return(t,n)=>{null==this.index&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}}function zE(e,t){if(1===e)return`${t}`;if(2===e)return`${t}.x, ${t}.y`;if(3===e)return`${t}.x, ${t}.y, ${t}.z`;if(4===e)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function BE(e,t){if(1===e)return`${t}`;if(2===e)return`${t}.y`;if(3===e)return`${t}.z`;if(4===e)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}const PE={kernelName:Xe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r,exclusive:i,reverse:o}=s,l=a.shape.length,u=Zi([r],l);let c=a;null!=u&&(c=KS({inputs:{x:a},backend:n,attrs:{perm:u}}));const h=eo(1,l)[0];if(h!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${a.shape.length-1} but got axis=${r}`);const p=c.shape[h];let d=xS({inputs:{x:c},backend:n});for(let e=0;e<=Math.ceil(Math.log2(p))-1;e++){const t=new LE(c.shape,!1,o),s=t.getCustomSetupFunc(e),a=d;d=n.runWebGLProgram(t,[d],d.dtype,s),n.disposeIntermediateTensorInfo(a)}if(i){const e=new LE(c.shape,i,o),t=d;d=n.runWebGLProgram(e,[d],d.dtype),n.disposeIntermediateTensorInfo(t)}if(null!=u){const e=KS({inputs:{x:d},backend:n,attrs:{perm:Qi(u)}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(c),e}return d}},WE={kernelName:Je,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,weights:r}=t,{size:i,binaryOutput:o}=s;if(1===a.shape.length){const e=n.readSync(a.dataId),t=n.readSync(r.dataId),s=SC(e,t,r.dtype,r.shape,i);return n.makeTensorInfo([i],r.dtype,s)}if(2===a.shape.length){const e=n.bufferSync(a),t=n.bufferSync(r),s=TC(e,t,i,o);return n.makeTensorInfo(s.shape,r.dtype,s.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}};class VE{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${t};\n int offset_h = imod(h, ${t});\n int in_w = w / ${t};\n int offset_w = imod(w, ${t});\n int offset_d = (offset_h * ${t} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `}getHeightCoordString(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"}getWidthCoordString(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"}getDepthCoordString(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"}getOutputDepthSize(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const UE={kernelName:Ze,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{blockSize:r,dataFormat:i}=s;E(r>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${r}`));const o=a.shape[0],l="NHWC"===i?a.shape[1]:a.shape[2],u="NHWC"===i?a.shape[2]:a.shape[3],c="NHWC"===i?a.shape[3]:a.shape[1],h=l*r,p=u*r,d=c/(r*r),f=new VE("NHWC"===i?[o,h,p,d]:[o,d,h,p],r,i);return n.runWebGLProgram(f,[a],a.dtype)}};class GE{constructor(e,t=!1,n=null,s=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const r=e.inHeight,i=e.inWidth,o=e.padInfo.top,l=e.padInfo.left,u=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,p=e.dilationWidth,d=e.filterHeight,f=e.filterWidth,m=e.outChannels/e.inChannels;let g="",y="";n&&(g=s?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,y="result = activation(result);");const b=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${g}\n\n const ivec2 strides = ivec2(${u}, ${c});\n const ivec2 pads = ivec2(${o}, ${l});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${m};\n int q = d2 - d1 * ${m};\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < ${d}; wR++) {\n int xR = xRCorner + wR * ${h};\n\n if (xR < 0 || xR >= ${r}) {\n continue;\n }\n\n for (int wC = 0; wC < ${f}; wC++) {\n int xC = xCCorner + wC * ${p};\n\n if (xC < 0 || xC >= ${i}) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${b}\n ${y}\n setOutput(result);\n }\n `}}class HE{constructor(e,t=!1,n=null,s=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const r=e.inHeight,i=e.inWidth,o=e.padInfo.top,l=e.padInfo.left,u=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,p=e.dilationWidth,d=e.filterHeight,f=e.filterWidth,m=f;let g="int xR; int xC; int xCOffset;";for(let e=0;e= 0 && xR < ${r} && xCOffset >= 0 && xCOffset < ${i}) {\n xTexelR${e}C${n} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= ${i}) {\n xTexelR${e}C${n}.zw = vec2(0.);\n }\n } else {\n xTexelR${e}C${n} = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < ${r} && xCOffset >= 0 && xCOffset < ${i}) {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= ${i}) {\n previous.zw = vec2(0.);\n }\n\n xR${e}C${n} = vec4(previous.zw, xTexelR${e}C${n}.xy);\n } else {\n xR${e}C${n} = vec4(0, 0, xTexelR${e}C${n}.xy);\n }\n `:`\n if(xR >= 0 && xR < ${r} && xC >= 0 && xC < ${i}) {\n xTexelR${e}C${n} = getX(batch, xR, xC, d1);\n } else {\n xTexelR${e}C${n} = vec4(0.);\n }\n\n xR${e}C${n} = xTexelR${e}C${n};\n `,n+1= 0 && xR < ${r} &&\n xCOffset >= 0 && xCOffset < ${i}) {\n xTexelR${e}C${n+2} = getX(batch, xR, xCOffset, d1);\n }\n `,p>1&&(g+=`\n xCOffset -= 2;\n if(xR >= 0 && xR < ${r} &&\n xCOffset >= 0 && xCOffset < ${i}) {\n xTexelR${e}C${n} = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR${e}C${n} = vec4(0.);\n }\n `),g+=`\n xR${e}C${n+1} = vec4(\n xTexelR${e}C${n}.zw, xTexelR${e}C${n+2}.xy);\n `):g+=`\n xCOffset = xC + ${t};\n\n if(xR >= 0 && xR < ${r} &&\n xCOffset >= 0 && xCOffset < ${i}) {\n xTexelR${e}C${n+2} = getX(batch, xR, xCOffset, d1);\n }\n\n xR${e}C${n+1} = xTexelR${e}C${n+2};\n `}}else n= 0 && xR < ${r}) {\n `,l%2==1?(g+=`\n xCOffset = xC + 1 - ${c};\n if(xCOffset >= 0 && xCOffset < ${i}) {\n xTexelR${e}C${n} = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR${e}C${n} = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < ${i}) {\n xTexelR${e}C${n+2} = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR${e}C${n+2} = vec4(0.);\n }\n\n xR${e}C${n} = vec4(\n xTexelR${e}C${n}.zw, xTexelR${e}C${n+2}.zw);\n `,n+1= 0 && xCOffset < ${i}) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR${e}C${n+1} = vec4(xTexelR${e}C${n+2}.xy, final.xy);\n `)):(g+=`\n if(xC >= 0 && xC < ${i}) {\n xTexelR${e}C${n} = getX(batch, xR, xC, d1);\n } else {\n xTexelR${e}C${n} = vec4(0.);\n }\n\n xCOffset = xC + ${c};\n if(xCOffset >= 0 && xCOffset < ${i}) {\n xTexelR${e}C${n+2} = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR${e}C${n+2} = vec4(0.);\n }\n\n xR${e}C${n} = vec4(\n xTexelR${e}C${n}.xy, xTexelR${e}C${n+2}.xy);\n `,n+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'`));const h=Vr(a.shape,r.shape,i,c,o,u,!0);let p;return p=ue().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels==1?new HE(h):new GE(h),n.runWebGLProgram(p,[a,r],"float32")}};class KE{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,a=e.padInfo.left,r=e.outChannels/e.inChannels;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * ${r} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${e.batchSize}; b++) {\n for (int yR = 0; yR < ${e.outHeight}; yR++) {\n int xR = wR + yR * ${t} - ${s};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${e.outWidth}; yC++) {\n int xC = wC + yC * ${n} - ${a};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class qE{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,a=e.strideWidth,r=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`\n const ivec2 pads = ivec2(${r}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${s}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${a}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${o}; dm++) {\n int d2 = d1 * ${o} + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const XE={kernelName:et,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,dy:r}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:c}=s,h=Vr(a.shape,c,i,o,l,u,!0),p=new KE(h);return n.runWebGLProgram(p,[a,r],"float32")}},YE={kernelName:tt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,filter:r}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:c}=s,h=Vr(c,r.shape,i,o,l,u,!0),p=new qE(h);return n.runWebGLProgram(p,[a,r],"float32")}};class JE{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "}}const ZE={kernelName:nt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,a=[...s.shape,...s.shape],r=D(s.shape),i=LS({inputs:{x:s},backend:n,attrs:{shape:[r]}}),o=new JE(r),l=n.runWebGLProgram(o,[i],i.dtype),u=LS({inputs:{x:l},backend:n,attrs:{shape:a}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}};class QE{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:s,strideHeight:a,strideWidth:r,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:c,left:h}=s;this.userCode=`\n const ivec2 strides = ivec2(${a}, ${r});\n const ivec2 pads = ivec2(${c}, ${h});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${i}; h++) {\n int hIn = hBeg + h * ${l};\n\n if (hIn >= 0 && hIn < ${t}) {\n for (int w = 0; w < ${o}; w++) {\n int wIn = wBeg + w * ${u};\n\n if (wIn >= 0 && wIn < ${n}) {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\n }\n `}}const eA={kernelName:st,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,filter:r}=t,{strides:i,pad:o,dilations:l}=s,u=Br(a.shape,r.shape,i,o,"NHWC",l);let c;const h=new QE(u);c=n.runWebGLProgram(h,[a,r],"float32");const p=LS({inputs:{x:c},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(c),p}},tA=ES({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n"}),nA={kernelName:ot,backendName:"webgl",kernelFunc:tA},sA={kernelName:lt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:s,y:a}=t,r=ue().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bS("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",s.shape,a.shape):new yS("return (b >= 1.0) ? a : a * (b + 1.0);",s.shape,a.shape);return n.runWebGLProgram(r,[s,a],s.dtype)}},aA=AS({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool"}),rA={kernelName:ct,backendName:"webgl",kernelFunc:aA},iA=ES({opSnippet:`\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = ${xu};\n float a1 = ${wu};\n float a2 = ${ku};\n float a3 = ${vu};\n float a4 = ${Nu};\n float a5 = ${Iu};\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n`}),oA={kernelName:ut,backendName:"webgl",kernelFunc:iA},lA="return exp(x);",uA=ES({opSnippet:lA,packedOpSnippet:lA,cpuKernelImpl:RC}),cA={kernelName:ht,backendName:"webgl",kernelFunc:uA};function hA(e){const{inputs:t,attrs:n,backend:s}=e,{dim:a}=n,{input:r}=t,i=r.shape.length,o=r.shape.slice();let l=a;return a<0&&(E(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+a+1),o.splice(l,0,1),LS({inputs:{x:r},backend:s,attrs:{shape:o}})}const pA={kernelName:pt,backendName:"webgl",kernelFunc:hA},dA="return exp(x) - 1.0;",fA=ES({opSnippet:dA,packedOpSnippet:dA,cpuKernelImpl:FC}),mA={kernelName:dt,backendName:"webgl",kernelFunc:fA};class gA{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const a=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,r=n?`${s}.0`:"1.0";let i;if("real"===e)i="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);i="return real * expI + imag * expR;"}this.userCode=`\n const float exponentMultiplier = ${a};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${i}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${s});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${s}; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / ${r};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `}}function yA(e,t,n){const s=n.texData.get(e.dataId),a=D(e.shape),r=e.shape[e.shape.length-1],i=LS({inputs:{x:e},backend:n,attrs:{shape:[a/r,r]}}),o=i.shape,l=new gA("real",o,t),u=new gA("imag",o,t),c=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:o},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:o}],h=n.runWebGLProgram(l,c,"float32"),p=n.runWebGLProgram(u,c,"float32"),d=kS({inputs:{real:h,imag:p},backend:n});n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p);const f=LS({inputs:{x:d},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(d),f}const bA={kernelName:ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t;return yA(s,!1,n)}};class xA{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}getCustomSetupFunc(e){return(t,n)=>{null==this.valueLoc&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}function wA(e){const{backend:t,attrs:n}=e,{shape:s,value:a}=n;let{dtype:r}=n;if(r=r||X(a),"string"===r){const e=U(r,D(s));return e.fill(a),t.makeTensorInfo(s,r,e)}{const e=new xA(s,a),n=e.getCustomSetupFunc(a);return t.runWebGLProgram(e,[],r,n)}}const kA={kernelName:mt,backendName:"webgl",kernelFunc:wA};class vA{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${t} - x;\n float outputValue;\n if(coordX >= 0 && coordX < ${t}) {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n `}}const NA={kernelName:gt,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,a=new vA(n.shape);return s.runWebGLProgram(a,[n],n.dtype)}},IA="return floor(x);",$A=ES({opSnippet:IA,packedOpSnippet:IA,cpuKernelImpl:DC}),CA={kernelName:yt,backendName:"webgl",kernelFunc:$A},SA=AS({opSnippet:"\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",packedOpSnippet:"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n",dtype:"int32"}),TA={kernelName:bt,backendName:"webgl",kernelFunc:SA};class EA{constructor(e){this.variableNames=["A"];const t=X$(),[n,s]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);\n\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `}}class AA{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=X$(),[n,s]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${s}.0, ${n}.0);\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${t.output} = result;\n }\n `}}const RA={kernelName:ss,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e;let{pixels:a}=t;const{numChannels:r}=s,i="undefined"!=typeof HTMLVideoElement&&a instanceof HTMLVideoElement,o="undefined"!=typeof HTMLImageElement&&a instanceof HTMLImageElement,[l,u]=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=[u,l],h=[u,l,r];(o||i)&&(null==FA&&(FA=document.createElement("canvas").getContext("2d")),FA.canvas.width=l,FA.canvas.height=u,FA.drawImage(a,0,0,l,u),a=FA.canvas);const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=w$.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),a);const d=ue().getBool("WEBGL_PACK")?new AA(h):new EA(h),f=n.runWebGLProgram(d,[p],"int32");return n.disposeData(p.dataId),f}};let FA;const DA={kernelName:is,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,filter:r,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s,m=Jr(c),g=Vr(a.shape,r.shape,l,h,u,p,!1,m);let y;const b=[];if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(ue().getBool("WEBGL_CONV_IM2COL")&&1===a.shape[0])y=wE({x:a,filter:r,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});else{const e=null!=i,t=null!=o,s="leakyrelu"===d,l=d?RS(d,!1):null,u=new gE(g,e,l,t,s),c=[a,r];if(i&&c.push(i),o&&c.push(o),s){const e=n.makeTensorInfo([],"float32",gs(f,"float32"));c.push(e),b.push(e)}y=n.runWebGLProgram(u,c,"float32")}else y=xE({x:a,filter:r,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});const x=LS({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),x}},_A={kernelName:os,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,filter:r,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:h,activation:p,leakyreluAlpha:d}=s,f=[];let m=c;null==m&&(m=[1,1]),E(Yr(l,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`));const g=Vr(a.shape,r.shape,l,m,u,h,!0),y=ue().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=p?RS(p,y):null,x=[a,r],w=null!=i,k=null!=o,v="leakyrelu"===p;if(w&&x.push(i),k&&x.push(o),v){const e=n.makeTensorInfo([],"float32",gs(d,"float32"));x.push(e),f.push(e)}let N;N=y?new HE(g,w,b,k,v):new GE(g,w,b,k,v);const I=n.runWebGLProgram(N,x,"float32");return f.forEach((e=>n.disposeIntermediateTensorInfo(e))),I}};class OA{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=vC(t.length),a=vC(n.length),r=this.sliceDim>1?"strides[j]":"strides";this.userCode=`\n ${s} strides = ${s}(${this.strides});\n void main() {\n ${a} coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < ${this.sliceDim}; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * ${r};\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n `}}const MA={kernelName:kt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:s,indices:a}=t,r=a.shape,i=r[r.length-1],[o,l,u,c]=du(s,a),h=LS({inputs:{x:a},backend:n,attrs:{shape:[l,i]}}),p=LS({inputs:{x:s},backend:n,attrs:{shape:[D(s.shape)/u,u]}}),d=new OA(i,c,[l,u]),f=n.runWebGLProgram(d,[p,h],p.dtype),m=LS({inputs:{x:f},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),m}};class LA{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=vC(this.rank),s=function(e,t){const n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let t=0;tn.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(l.outputShape,s.dtype,s.values)}const f=new LA(h.shape,d),m=n.runWebGLProgram(f,[h,p],h.dtype);c.push(m);const g=LS({inputs:{x:m},backend:n,attrs:{shape:l.outputShape}});return c.forEach((e=>n.disposeIntermediateTensorInfo(e))),g}},BA=AS({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:OC,dtype:"bool"}),PA={kernelName:vt,backendName:"webgl",kernelFunc:BA},WA=AS({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool"}),VA={kernelName:Nt,backendName:"webgl",kernelFunc:WA},UA={kernelName:$t,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t;return yA(s,!0,n)}},GA=ES({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),HA={kernelName:St,backendName:"webgl",kernelFunc:GA},jA=ES({opSnippet:"return float(isinf(x));",dtype:"bool"}),KA={kernelName:Tt,backendName:"webgl",kernelFunc:jA},qA=ES({opSnippet:"return float(isnan(x));",dtype:"bool"}),XA={kernelName:Et,backendName:"webgl",kernelFunc:qA},YA=AS({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:MC,dtype:"bool"}),JA={kernelName:Rt,backendName:"webgl",kernelFunc:YA},ZA=AS({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",dtype:"bool"}),QA={kernelName:Ft,backendName:"webgl",kernelFunc:ZA},eR={kernelName:Dt,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:a,num:r}=n,i=LC(s,a,r);return t.makeTensorInfo([i.length],"float32",i)}},tR=ES({opSnippet:"if (x < 0.0) return NAN;\n return log(x);",packedOpSnippet:"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",cpuKernelImpl:zC}),nR={kernelName:_t,backendName:"webgl",kernelFunc:tR},sR=ES({opSnippet:"return log(1.0 + x);"}),aR={kernelName:Ot,backendName:"webgl",kernelFunc:sR},rR=AS({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n",dtype:"bool"}),iR={kernelName:Mt,backendName:"webgl",kernelFunc:rR},oR=ES({opSnippet:"return float(!(x >= 1.0));"}),lR={kernelName:Lt,backendName:"webgl",kernelFunc:oR},uR=AS({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n",dtype:"bool"}),cR={kernelName:zt,backendName:"webgl",kernelFunc:uR};class hR{constructor(e,t,n,s,a){this.variableNames=["x"],this.outputShape=[];const r=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${s}) * sum`;o=.5===a?`inversesqrt(${l})`:1===a?`1.0/(${l})`:`exp(log(${l}) * float(-${a}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -${r}; j <= ${r}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${i}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${o};\n setOutput(val);\n }\n `}}class pR{constructor(e,t,n,s,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const r=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${s}) * sum`;o=.5===a?`inversesqrt(${l})`:1===a?`1.0/(${l})`:`exp(log(${l}) * float(-${a}));`,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < ${this.outputShape[3]};\n bool hasNextRow = c < ${this.outputShape[2]};\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - ${r};\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - ${r}; j <= ${r}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * ${o};\n setOutput(result);\n }\n `}}const dR={kernelName:Bt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{depthRadius:r,bias:i,alpha:o,beta:l}=s,u=ue().getBool("WEBGL_PACK_NORMALIZATION")?new pR(a.shape,r,i,o,l):new hR(a.shape,r,i,o,l);return n.runWebGLProgram(u,[a],a.dtype)}};class fR{constructor(e,t,n,s,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=a,this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < ${this.depth}; ++d) {\n int depthBegin = int(max(0.0, float(d - ${t})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${t} + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = ${this.depth};\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float(${s}) * norm + float(${n});\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float(${s})\n * float(${a})\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${a});\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n `}}const mR={kernelName:Pt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:a,y:r,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:c}=s,h=new fR(a.shape,o,l,u,c);return n.runWebGLProgram(h,[a,r,i],a.dtype)}};function gR(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{reductionIndices:r,keepDims:i}=s,o=a.shape.length,l=P(r,a.shape);let u=l;const c=Zi(u,o),h=null!=c,p=n.shouldExecuteOnCPU([a]);let d=a;if(h){if(p){const e=n.texData.get(d.dataId).values,t=new Array(o);for(let e=0;e 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",cpuKernelImpl:PC}),xR={kernelName:Vt,backendName:"webgl",kernelFunc:bR},wR={kernelName:Ut,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t;K$(a,"maxPool");const{filterSize:r,strides:i,pad:o,dimRoundingMode:l}=s;E(Yr(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=Pr(a.shape,r,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&_(u.inShape,u.outShape))return xS({inputs:{x:a},backend:n});const c=new TT(u,"max",!1);return n.runWebGLProgram(c,[a],a.dtype)}},kR={kernelName:Ht,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{filterSize:r,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=s,c=Wr(a.shape,r,i,[1,1,1],o,u,l),h=new ET(c,"max",!1);return n.runWebGLProgram(h,[a],a.dtype)}};class vR{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,a=e.effectiveFilterHeight,r=e.effectiveFilterWidth,i=a-1-e.padInfo.top,o=r-1-e.padInfo.left,l=a*r-1;this.userCode=`\n const ivec2 pads = ivec2(${i}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${a};\n wR += ${s}) {\n float dyR = float(dyRCorner + wR) / ${t}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${r}; wC++) {\n float dyC = float(dyCCorner + wC) / ${n}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * ${r} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `}}class NR{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,a=e.dilationDepth,r=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=o-1-e.padInfo.front,h=l-1-e.padInfo.top,p=u-1-e.padInfo.left,d=o*l*u-1;this.userCode=`\n const ivec3 pads = ivec3(${c}, ${h}, ${p});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${o};\n wD += ${a}) {\n float dyD = float(dyDCorner + wD) / ${t}.0;\n\n if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${l};\n wR += ${r}) {\n float dyR = float(dyRCorner + wR) / ${n}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${u};\n wC += ${i}) {\n float dyC = float(dyCCorner + wC) / ${s}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${d} -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * ${l} * ${u} +\n wR * ${u} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const IR={kernelName:jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,input:r}=t,i=r,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,h=Wr(i.shape,o,l,[1,1,1],u,c),p=new ET(h,"max",!0),d=n.runWebGLProgram(p,[i],i.dtype),f=new NR(h),m=n.runWebGLProgram(f,[a,d],i.dtype);return n.disposeIntermediateTensorInfo(d),m}},$R={kernelName:Gt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:a,input:r,output:i}=t,o=r;K$([r,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,p=Pr(o.shape,l,u,1,c,h),d=new TT(p,"max",!0),f=n.runWebGLProgram(d,[o],o.dtype),m=new vR(p),g=n.runWebGLProgram(m,[a,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}},CR={kernelName:Kt,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:a,strides:r,pad:i,includeBatchInIndex:o}=t,l=n;E(4===s.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`));const u=[1,1];E(Yr(r,u),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${u}'`));const c=Pr(s.shape,a,r,u,i),[h,p]=function(e,t,n,s){let a=new TT(n,"max",!1);const r=s.runWebGLProgram(a,[e],"float32");return a=new TT(n,"max",!0,!0,t),[r,s.runWebGLProgram(a,[e],"float32")]}(s,o,c,l);return[h,p]}},SR={kernelName:qt,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{keepDims:a,axis:r}=t,i=n,o=s.shape.length,l=P(r,s.shape);let u=l;const c=Zi(u,o),h=null!=c,p=i.shouldExecuteOnCPU([s]),d=[];let f=s;if(h){if(p){const e=i.texData.get(f.dataId).values,t=new Array(o);for(let e=0;e 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",cpuKernelImpl:WC}),AR={kernelName:Yt,backendName:"webgl",kernelFunc:ER};class RR{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,a=vC(s),r=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),l="reflect"===n?0:1;this.userCode=1!==s?`\n ${a} start = ${a}(${r});\n ${a} end = ${a}(${i});\n\n void main() {\n ${a} outC = getOutputCoords();\n for (int i = 0; i < ${s}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${l};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};\n }\n }\n ${a} coords = outC - start;\n setOutput(getX(${o}));\n }\n `:`\n int start = ${r};\n int end = ${i};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${l};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${l};\n }\n setOutput(getX(outC - start));\n }\n `}}class FR{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,a=vC(s),r=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=nS("rc",s),l=nS("source",s),u=`${o[s-1]} < ${this.outputShape[s-1]}`,c=1===s?"source":`vec2(${l.slice(-2).join()})`,h="reflect"===n?0:1;let p="";if(1===s){const e=`\n ${a} source = rc;\n if (source < start) {\n source = start * 2 - source - ${h};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${h};\n }\n source -= start;\n `;p=`\n ${a} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[1] = getChannel(getX(${l.join()}), ${c});\n }\n `}else{const e=`\n ${a} source = rc;\n ${a} lt = ${a}(lessThan(source, start));\n ${a} gte = ${a}(greaterThanEqual(source, end));\n ${a} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${h}) +\n gte * ((end - 1) * 2 - source + ${h});\n source -= start;\n `;p=`\n ${a} rc = outputLoc;\n ${e}\n result[0] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[1] = getChannel(getX(${l.join()}), ${c});\n }\n rc = outputLoc;\n ${o[s-2]} += 1;\n if(${o[s-2]} < ${this.outputShape[s-2]}) {\n ${e}\n result[2] = getChannel(getX(${l.join()}), ${c});\n ${o[s-1]} += 1;\n if(${u}) {\n ${e}\n result[3] = getChannel(getX(${l.join()}), ${c});\n }\n }\n `}this.userCode=`\n const ${a} start = ${a}(${r});\n const ${a} end = ${a}(${i});\n\n void main() {\n ${a} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${p}\n setOutput(result);\n }\n `}}const DR={kernelName:Jt,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:a,mode:r}=n,i=ue().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new FR(s.shape,a,r):new RR(s.shape,a,r);return t.runWebGLProgram(i,[s],s.dtype)}},_R=AS({opSnippet:"if (b == 0.0) return NAN;\n return mod(a, b);",packedOpSnippet:"\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),OR={kernelName:Zt,backendName:"webgl",kernelFunc:_R};class MR{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode=`\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < ${t-1}; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(${t-1}));\n }\n `}getCustomSetupFunc(e){return(t,n)=>{null==this.seedLoc&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}const LR=AS({opSnippet:"\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",checkOutOfBounds:!0}),zR={kernelName:it,backendName:"webgl",kernelFunc:LR},BR="return a - b;",PR=AS({opSnippet:BR,packedOpSnippet:BR,supportsComplex:!0,cpuKernelImpl:YC}),WR={kernelName:Un,backendName:"webgl",kernelFunc:PR};function VR(e){const{inputs:t,backend:n,attrs:s}=e,{logits:a}=t,{dim:r}=s,i=P([r],a.shape),o=gR({inputs:{x:a},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=Yi(o.shape,i),u=LS({inputs:{x:o},backend:n,attrs:{shape:l}}),c=PR({inputs:{a,b:u},backend:n}),h=uA({inputs:{x:c},backend:n}),p=HS({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),d=LS({inputs:{x:p},backend:n,attrs:{shape:l}}),f=LR({inputs:{a:h,b:d},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),f}const UR={kernelName:Pn,backendName:"webgl",kernelFunc:VR},GR={kernelName:Qt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:a}=t,{numSamples:r,seed:i,normalized:o}=s,l=o?a:VR({inputs:{logits:a},backend:n,attrs:{dim:a.shape.length-1}}),u=l.shape[0],c=l.shape[1],h=new MR(u,c,r),p=h.getCustomSetupFunc(i),d=n.runWebGLProgram(h,[l],"int32",p);return o||n.disposeIntermediateTensorInfo(l),d}},HR="return -x;",jR={kernelName:tn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){const e=n.texData.get(s.dataId),[t,a]=UC(e.values,s.shape,s.dtype);return n.makeTensorInfo(a,s.dtype,t)}let a;return a=ue().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new pS(s.shape,HR):new uS(s.shape,HR),n.runWebGLProgram(a,[s],s.dtype)}},KR=bl,qR={kernelName:sn,backendName:"webgl",kernelFunc:function(e){$u("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:a,scores:r}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=s,u=n.readSync(a.dataId),c=n.readSync(r.dataId),{selectedIndices:h}=KR(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},XR=xl,YR={kernelName:an,backendName:"webgl",kernelFunc:function(e){$u("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:a,scores:r}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=s,c=n.readSync(a.dataId),h=n.readSync(r.dataId),{selectedIndices:p,validOutputs:d}=XR(c,h,i,o,l,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},JR=wl,ZR={kernelName:rn,backendName:"webgl",kernelFunc:function(e){$u("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:a,scores:r}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=s,c=n.readSync(a.dataId),h=n.readSync(r.dataId),p=i,d=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=JR(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class QR{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${s}), float(${n}),\n float(index == coords.y)));\n }\n `}}const eF={kernelName:ln,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{indices:a}=t,{depth:r,onValue:i,offValue:o}=s,l=D(a.shape),u=new QR(l,r,i,o),c=LS({inputs:{x:a},backend:n,attrs:{shape:[l]}}),h=n.runWebGLProgram(u,[c],a.dtype);n.disposeIntermediateTensorInfo(c);const p=LS({inputs:{x:h},backend:n,attrs:{shape:[...a.shape,r]}});return n.disposeIntermediateTensorInfo(h),p}};function tF(e){const{inputs:t,backend:n}=e,{x:s}=t;if("complex64"===s.dtype){const e=XT({inputs:{input:s},backend:n}),t=tF({inputs:{x:e},backend:n}),a=cE({inputs:{input:s},backend:n}),r=tF({inputs:{x:a},backend:n}),i=kS({inputs:{real:t,imag:r},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(r),i}return wA({attrs:{shape:s.shape,dtype:s.dtype,value:"string"===s.dtype?"":0},backend:n})}const nF={kernelName:ts,backendName:"webgl",kernelFunc:tF},sF={kernelName:on,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s}=t,{x:a}=n;if("string"===a.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===a.dtype){const t=XT({inputs:{input:a},backend:s}),n=e({inputs:{x:t},backend:s}),r=cE({inputs:{input:a},backend:s}),i=tF({inputs:{x:r},backend:s}),o=kS({inputs:{real:n,imag:i},backend:s});return s.disposeIntermediateTensorInfo(t),s.disposeIntermediateTensorInfo(n),s.disposeIntermediateTensorInfo(r),s.disposeIntermediateTensorInfo(i),o}return wA({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:s})}},aF={kernelName:un,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{axis:a}=s;if(1===t.length)return hA({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const r=t[0].shape,i=t[0].dtype;t.forEach((e=>{A(r,e.shape,"All tensors passed to stack must have matching shapes"),E(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=fE({inputs:t.map((e=>{const t=hA({inputs:{input:e},backend:n,attrs:{dim:a}});return o.push(t),t})),backend:n,attrs:{axis:a}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}};class rF{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,a=vC(s),r=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);this.userCode=1!==s?`\n ${a} start = ${a}(${r});\n ${a} end = ${a}(${i});\n uniform float value;\n\n void main() {\n ${a} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${a} coords = outC - start;\n setOutput(getX(${o}));\n }\n }\n `:`\n int start = ${r};\n int end = ${i};\n uniform float value;\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `}getCustomSetupFunc(e){return(t,n)=>{null==this.valueLoc&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class iF{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,a=vC(s),r=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=nS("rc",s),l=nS("source",s),u=`${o[s-1]} < ${this.outputShape[s-1]}`,c=1===s?"source":`vec2(${l.slice(-2).join()})`,h=[`${a} rc = outputLoc;`,`${o[s-1]} += 1;\n if(${u}) {\n `,1===s?"":`}\n rc = outputLoc;\n ${o[s-2]} += 1;\n if(${o[s-2]} < ${this.outputShape[s-2]}) {`,1===s?"":` ${o[s-1]} += 1;\n if(${u}) {`],p=1===s?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let e=0,t=1===s?2:4;e{null==this.valueLoc&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}const oF=e=>{const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{paddings:r,constantValue:i}=s,o=ue().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new iF(a.shape,r,i):new rF(a.shape,r,i),l=o.getCustomSetupFunc(i);return n.runWebGLProgram(o,[a],a.dtype,l)},lF={kernelName:cn,backendName:"webgl",kernelFunc:oF},uF=AS({opSnippet:"\n if(a < 0.0 && floor(b) < b){\n return NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n return (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",packedOpSnippet:"\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n"}),cF={kernelName:hn,backendName:"webgl",kernelFunc:uF},hF={kernelName:dn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{axis:r,keepDims:i}=s,o=a.shape.length,l=[],u=P(r,a.shape);let c=u;const h=Zi(c,o);let p,d=a;if(null!=h&&(d=KS({inputs:{x:a},backend:n,attrs:{perm:h}}),c=eo(c.length,o),l.push(d)),Ji("prod",c,o),n.shouldExecuteOnCPU([d])){const e=n.texData.get(d.dataId).values,{outVals:t,outShape:s,outDtype:a}=GC(d.shape,d.dtype,e,c);p=n.makeTensorInfo(s,a,t)}else{const[e,t]=Xi(d.shape,c),s=D(t),r=LS({inputs:{x:d},backend:n,attrs:{shape:[-1,s]}}),i=WS(r,Us(a.dtype),"prod",n);p=LS({inputs:{x:i},backend:n,attrs:{shape:e}}),l.push(r),l.push(i)}if(i){l.push(p);const e=Yi(p.shape,u);p=LS({inputs:{x:p},backend:n,attrs:{shape:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}},pF=e=>{const{backend:t,attrs:n}=e,{start:s,stop:a,step:r,dtype:i}=n,o=HC(s,a,r,i);return t.makeTensorInfo([o.length],i,o)},dF={kernelName:fn,backendName:"webgl",kernelFunc:pF},fF=ES({opSnippet:"return 1.0 / x;"}),mF={kernelName:gn,backendName:"webgl",kernelFunc:fF},gF=ES({opSnippet:"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),yF={kernelName:yn,backendName:"webgl",kernelFunc:gF},bF=ES({opSnippet:"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),xF={kernelName:Nn,backendName:"webgl",kernelFunc:bF};class wF{constructor(e,t,n,s,a){this.variableNames=["A"],this.outputShape=[];const[r,i,o,l]=e;this.outputShape=[r,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n];let h;h=a?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${u[0]/c[0]},\n ${u[1]/c[1]});\n const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${h};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `}}class kF{constructor(e,t,n,s,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[r,i,o,l]=e;this.outputShape=[r,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n];let h;h=a?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${u[0]/c[0]},\n ${u[1]/c[1]},\n ${u[1]/c[1]});\n const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n ${o}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${h};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${l-1};\n bool hasNextRow = coords.z < ${n-1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n `}}const vF={kernelName:kn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:a}=t,{alignCorners:r,halfPixelCenters:i,size:o}=s,[l,u]=o,c=ue().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new kF(a.shape,l,u,r,i):new wF(a.shape,l,u,r,i);return n.runWebGLProgram(c,[a],"float32")}};class NF{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,a]=t,[,r,i]=e,o=[n&&r>1?s-1:s,n&&i>1?a-1:a],l=[n&&r>1?r-1:r,n&&i>1?i-1:i],u=o[0]/l[0],c=o[1]/l[1],h=1/u,p=1/c,d=2*Math.ceil(h)+2,f=2*Math.ceil(p)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${u});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${h});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${d});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${r}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${i}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), ${a-1}.0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const IF={kernelName:vn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:a,dy:r}=t,{alignCorners:i}=s,o=new NF(r.shape,a.shape,i);return n.runWebGLProgram(o,[r],r.dtype)}};class $F{constructor(e,t,n,s,a){this.variableNames=["A"],this.outputShape=[];const[r,i,o,l]=e;this.outputShape=[r,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],h=s?"0.5":"0.0";let p;p=a?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${u[0]/c[0]},\n ${u[1]/c[1]});\n const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${p};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `}}const CF={kernelName:xn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:a}=t,{alignCorners:r,halfPixelCenters:i,size:o}=s,[l,u]=o,c=new $F(a.shape,l,u,r,i);return n.runWebGLProgram(c,[a],a.dtype)}};class SF{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,a]=t,[,r,i]=e,o=[n&&r>1?s-1:s,n&&i>1?a-1:a],l=[n&&r>1?r-1:r,n&&i>1?i-1:i],u=o[0]/l[0],c=o[1]/l[1],h=1/u,p=1/c,d=2*Math.ceil(h)+2,f=2*Math.ceil(p)+2;this.userCode=`\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${u});\n const float widthScale = float(${c});\n\n const float invHeightScale = float(${h});\n const float invWidthScale = float(${p});\n\n const int winHeight = int(${d});\n const int winWidth = int(${f});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${r}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${i}) {\n continue;\n }\n\n float sourceFracRow =\n float(${o[0]}) *\n (float(dyR) / float(${l[0]}));\n\n float sourceFracCol =\n float(${o[1]}) *\n (float(dyC) / float(${l[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${s}) - 1),\n ${n} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${a}) - 1),\n ${n} ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n `}}const TF={kernelName:wn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:a,dy:r}=t,{alignCorners:i}=s,o=new SF(r.shape,a.shape,i);return n.runWebGLProgram(o,[r],r.dtype)}};class EF{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${e[0]} - coord - 1));\n }\n `);const s=e.map(((n,s)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(s))).join(","),a=vC(n);this.userCode=`\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${s}));\n }\n `}}class AF{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const s=nS("rc",n),a=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,r=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,i=vC(n);function o(n){const s=e.map(((s,a)=>function(n,s){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${s[n]} - 1`:`${s[n]}`}(a,n)));return`getChannel(getX(${s.join(",")}), vec2(${s.slice(-2).join(",")}))`}this.userCode=1===n?`\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${e[0]} - rc - 1),\n ${e[0]} - rc - 1);\n if(${a}){\n result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),\n ${e[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `:`\n void main() {\n ${i} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${function(e){return o(e)}(s.slice())};\n if(${a}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(s.slice())};\n }\n if(${r}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(e)}(s.slice())};\n if(${a}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",o(e)}(s.slice())};\n }\n }\n setOutput(result);\n }\n `}}const RF={kernelName:In,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{dims:r}=s,i=a.shape.length,o=P(r,a.shape);if(0===i)return xS({inputs:{x:a},backend:n});const l=ue().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new AF(a.shape,o):new EF(a.shape,o);return n.runWebGLProgram(l,[a],a.dtype)}};class FF{constructor(e,t){this.variableNames=["Image"],this.outputShape=[];const n=e[1],s=e[2];this.outputShape=e;let a="";a="number"==typeof t?`float outputValue = ${t.toFixed(2)};`:`\n vec3 fill = vec3(${t.join(",")});\n float outputValue = fill[coords[3]];`,this.userCode=`\n uniform vec4 params;\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n ${a}\n if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${n}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `}getCustomSetupFunc(e,t,n,s){return(a,r)=>{null==this.paramsLoc&&(this.paramsLoc=a.getUniformLocationNoThrow(r,"params")),a.gl.uniform4f(this.paramsLoc,e,t,n,s)}}}const DF={kernelName:as,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:a,fillValue:r,center:i}=t,o=n,l=new FF(s.shape,r),[u,c]=ou(i,s.shape[1],s.shape[2]),h=l.getCustomSetupFunc(u,c,Math.sin(a),Math.cos(a));return o.runWebGLProgram(l,[s],s.dtype,h)}},_F=ES({opSnippet:"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n"}),OF={kernelName:$n,backendName:"webgl",kernelFunc:_F},MF=ES({opSnippet:"return inversesqrt(x);",cpuKernelImpl:jC}),LF={kernelName:Cn,backendName:"webgl",kernelFunc:MF};class zF{constructor(e,t,n,s,a,r,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=r;const o=vC(a.length),l=vC(r.length);let u="";1===n?u="i":2===n&&(u="i, j");const c=`getIndices(${u})`;let h="";1===s?h="i":2===s&&(h="i, coords[1]");const p=`getUpdates(${h})`,d=t>1?"strides[j]":"strides";this.userCode=`\n ${o} strides = ${o}(${a});\n\n void main() {\n ${l} coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < ${e}; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < ${t}; j++) {\n int index = round(${c});\n flattenedIndex += index * ${d};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${p};\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n `}}const BF={kernelName:Sn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:a,updates:r}=t,{shape:i}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=gu(0,a,i),p=[h/u,u];if(0===h)return n.makeTensorInfo(i,a.dtype);const d=LS({inputs:{x:a},backend:n,attrs:{shape:[l,o]}}),f=LS({inputs:{x:r},backend:n,attrs:{shape:[l,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new zF(l,o,d.shape.length,f.shape.length,c,p),y=n.runWebGLProgram(g,[f,d,m],f.dtype),b=LS({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class PF{constructor(e,t,n){let s,a;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)a="resRC",s="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],i=[];for(let s=0;s= 1.0) {\n setOutput(getA(${a}));\n } else {\n setOutput(getB(${a}));\n }\n }\n `}}const WF={kernelName:Tn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:s,t:a,e:r}=t,i=new PF(s.shape.length,a.shape,a.shape.length);return n.runWebGLProgram(i,[s,a,r],Vs(a.dtype,r.dtype))}},VF=ES({opSnippet:`\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${yu};\n float scale = ${bu};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),UF={kernelName:En,backendName:"webgl",kernelFunc:VF},GF=ES({opSnippet:"return 1.0 / (1.0 + exp(-1.0 * x));"}),HF={kernelName:_n,backendName:"webgl",kernelFunc:GF},jF=ES({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),KF={kernelName:Dn,backendName:"webgl",kernelFunc:jF},qF=ES({opSnippet:"if (isnan(x)) return x;\n return sin(x);\n"}),XF={kernelName:Rn,backendName:"webgl",kernelFunc:qF},YF=ES({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),JF={kernelName:Fn,backendName:"webgl",kernelFunc:YF},ZF=ES({opSnippet:"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n"}),QF={kernelName:On,backendName:"webgl",kernelFunc:ZF},eD={kernelName:zn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{blockShape:r,paddings:i}=s;E(a.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const o=r.reduce(((e,t)=>e*t)),l=[[0,0]];l.push(...i);for(let e=1+r.length;en.disposeIntermediateTensorInfo(e))),g}},tD={kernelName:Gn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sparseIndices:a,sparseValues:r,defaultValue:i}=t,{outputShape:o}=s,{sliceRank:l,numUpdates:u,strides:c,outputSize:h}=gu(0,a,o),p=new zF(u,l,a.shape.length,r.shape.length,c,[h,1],!1),d=n.runWebGLProgram(p,[r,a,i],r.dtype),f=LS({inputs:{x:d},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(d),f}},nD={kernelName:Bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{numOrSizeSplits:r,axis:i}=s,o=P(i,a.shape)[0],l=Ou(a,r,o),u=a.shape.length,c=new Array(u).fill(0),h=a.shape.slice();return l.map((e=>{const t=[...h];t[o]=e;const s=UT({inputs:{x:a},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,s}))}},sD=ES({opSnippet:"return sqrt(x);"}),aD={kernelName:Mn,backendName:"webgl",kernelFunc:sD},rD={kernelName:Vn,backendName:"webgl",kernelFunc:ES({opSnippet:"return x * x;"})},iD="return (a - b) * (a - b);",oD=AS({opSnippet:iD,packedOpSnippet:iD}),lD={kernelName:Wn,backendName:"webgl",kernelFunc:oD},uD={kernelName:ns,backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:s}=e,a=`if (isnan(x)) return x;\n return x > 0.0 ? 1.0 : float(${t.alpha});\n `,r=new uS(s.shape,a);return n.runWebGLProgram(r,[s],s.dtype)}};class cD{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,a=vC(n.length),r=vC(n.length);let i="";if(1===s)i="coords * strides + begin";else{let e=0;i=n.map(((t,s)=>(e++,1===n.length?`coords * strides[${s}] + begin[${s}]`:`coords[${e-1}] * strides[${s}] + begin[${s}]`))).join(",")}this.userCode=`\n ${a} begin = ${a}(${e});\n ${a} strides = ${a}(${t});\n\n void main() {\n ${r} coords = getOutputCoords();\n setOutput(getX(${i}));\n }\n `}}const hD={kernelName:Hn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{begin:r,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:h,shrinkAxisMask:p}=s,{nonStrided:d,$begin:f,$strides:m,size:g,newShape:y,outShape:b}=wr(a.shape,r,i,o,l,u,c,h,p),x=LS({inputs:{x:a},backend:n,attrs:{shape:y}});let w;if(d){const e=UT({inputs:{x},backend:n,attrs:{begin:f,size:g}});w=LS({inputs:{x:e},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(e)}else if(b.some((e=>0===e)))w=n.makeTensorInfo(b,a.dtype,[]);else if(n.shouldExecuteOnCPU([x])){const e=n.texData.get(x.dataId).values,t=Ha(x.shape,x.dtype,e),s=XC(b,t,m,f);w=n.makeTensorInfo(b,x.dtype,s.values)}else{const e=new cD(f,m,b);w=n.runWebGLProgram(e,[x],x.dtype)}const k=LS({inputs:{x:w},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(w),k}},pD=ES({opSnippet:"return tan(x);"}),dD={kernelName:jn,backendName:"webgl",kernelFunc:pD},fD=ES({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),mD={kernelName:Kn,backendName:"webgl",kernelFunc:fD};class gD{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let s=0;s5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let t=0;tws(e))),t=Ha(a.shape,a.dtype,e),s=JC(t,r);return n.makeTensorInfo(s.shape,s.dtype,s.values)}const i=new gD(a.shape,r);return n.runWebGLProgram(i,[a],a.dtype)}const bD={kernelName:qn,backendName:"webgl",kernelFunc:yD},xD={kernelName:Xn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a}=t,{k:r,sorted:i}=s,o=n.readSync(a.dataId),[l,u]=ZC(o,a.shape,a.dtype,r,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}};class wD{constructor(e,t,n,s,a,r){this.variableNames=["Image","Transforms"],this.outputShape=r;const i="nearest"===n?1:2;let o;switch(s){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1}this.userCode=`\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${o} == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${o} == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${o} == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${a});\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(${a});\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(${t}));\n float mapY = mapCoord(inY, float(${e}));\n\n if (${i} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `}}const kD={kernelName:Yn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{image:a,transforms:r}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=s,[c,h,p,d]=a.shape,[f,m]=null!=u?u:[h,p],g=new wD(h,p,i,o,l,[c,f,m,d]);return n.runWebGLProgram(g,[a,r],"float32")}},vD={kernelName:Zn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{axis:a}=n,{x:r}=t;K$(r,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=s.readSync(r.dataId),{outputValues:o,outputShape:l,indices:u}=eS(i,a,r.shape,r.dtype);return[s.makeTensorInfo(l,r.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}},ND={kernelName:Qn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{value:a}=t;let{axis:r}=s;r<0&&(r+=a.shape.length);const i=a,o=i.shape.length,l=a.shape[r],u=new Array(o-1);let c=0;for(let e=0;en.disposeIntermediateTensorInfo(e))),f}};class ID{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,s=e.batchSize,a=e.inSize,r=e.numSegments,i=r*Math.ceil(a/n);this.outputShape=[s,i];const o=4*Math.floor(n/4),l=n%4,u="\n sumValue += dot(values, segFilter);\n ";let c="";a%n>0&&(c=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return initializationValue;\n }\n `);let h="";a%n>0&&(h=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return -1.0;\n }\n `),this.userCode=`\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n ${c}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${h}\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n ${r})) * float(${n}));\n int currentSeg = int(mod(float(outIdx), float(${r})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${o}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n ${u}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n ${u}\n } else if (${2===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n ${u}\n } else if (${3===l}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n ${u}\n }\n setOutput(sumValue);\n }\n `}}const $D=[dR,mR,YS,ZS,eT,nT,rT,lT,uT,cT,gT,yT,xT,kT,$T,NT,ST,RT,AT,_T,OT,MT,BT,HT,jT,JT,eE,sE,iE,vS,mE,CE,SE,kE,EE,AE,TE,FE,_E,ME,PE,WE,UE,XE,YE,jE,ZE,eA,nA,sA,rA,oA,cA,pA,mA,bA,kA,NA,CA,TA,RA,DA,_A,MA,zA,PA,VA,wS,UA,hE,HA,KA,XA,$S,JA,QA,eR,aR,nR,iR,lR,cR,yR,kR,wR,IR,$R,CR,xR,SR,TR,AR,DR,OR,GR,MS,jR,qR,YR,ZR,qT,eF,sF,aF,lF,cF,TS,hF,dF,YT,zR,mF,xF,yF,zS,vF,IF,CF,TF,RF,DF,OF,LF,BF,WF,UF,HF,KF,XF,JF,GT,UR,QF,eD,tD,nD,aD,rD,lD,uD,hD,WR,jS,dD,mD,bD,xD,kD,qS,vD,ND,{kernelName:es,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:a,segmentIds:r}=t,{numSegments:i}=s,o=a.shape.length,l=[];let u=0;const c=Zi([u],o);let h=a;null!=c&&(h=KS({inputs:{x:a},backend:n,attrs:{perm:c}}),l.push(h),u=eo(1,o)[0]);const p=Lu(h.shape,u,i),d=D([h.shape[u]]),f=LS({inputs:{x:h},backend:n,attrs:{shape:[-1,d]}});l.push(f);const m=Us(a.dtype),g=(e,t,s,a,r)=>{const i=e.shape[0],o=e.shape[1],u=Mu(o,r),c=new ID({windowSize:u,inSize:o,batchSize:i,numSegments:r},t),h=n.compileAndRun(c,[e,s],a);if(l.push(h),h.shape[1]===r)return h;const p=pF({backend:n,attrs:{start:0,stop:r,step:1,dtype:"float32"}}),d=yD({inputs:{x:p},backend:n,attrs:{reps:[o/u]}});return l.push(p),l.push(d),g(h,t,d,a,r)},y=LS({inputs:{x:g(f,"unsortedSegmentSum",r,m,i)},backend:n,attrs:{shape:p}});let b=y;if(null!=c){l.push(y);const e=Qi(c);b=KS({inputs:{x:b},backend:n,attrs:{perm:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),b}},nF];for(const e of $D)ds(e);const CD="0.1.2",SD={flipHorizontal:!1,outputStride:16,imageScaleFactor:1,maxNumBoxes:20,iouThreshold:.2,scoreThreshold:.6,modelType:"ssd320fpnlite",modelSize:"large",bboxLineWidth:"2",fontSize:17,basePath:"https://cdn.jsdelivr.net/npm/handtrackjs@latest/models/webmodel/",labelMap:{1:"open",2:"closed",3:"pinch",4:"point",5:"face",6:"tip",7:"pinchtip"}},TD={large:"base",medium:"fp16",small:"int8"},ED={open:"#374151",closed:"#B91C1C",pinch:"#F59E0B",point:"#10B981",face:"#3B82F6",tip:"#6366F1",pinchtip:"#EC4899"},AD=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"];async function RD(e){let t=Object.assign({},SD,e);const n=new _D(t);return await n.load(),n}function FD(e){return new Promise((function(t,n){e||t({status:!1,msg:"please provide a valid video element"}),e.width=e.width||640,e.height=e.width*(e.videoHeight/e.videoWidth),e.style.height="20px",navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:"user"}}).then((n=>{window.localStream=n,e.srcObject=n,e.onloadedmetadata=()=>{e.height=e.width*(e.videoHeight/e.videoWidth),e.style.height=parseInt(e.style.width)*(e.videoHeight/e.videoWidth).toFixed(2)+"px",e.play(),t({status:!0,msg:"webcam successfully initiated."})}})).catch((function(e){t({status:!1,msg:e})}))}))}async function DD(){if(!window.localStream)return!1;window.localStream.getTracks().forEach((e=>(e.stop(),!0)))}class _D{constructor(e){this.modelPath=e.basePath+e.modelType+"/"+(TD[e.modelSize]||"base")+"/model.json ",this.modelParams=e}async load(){this.fps=0,this.model&&console.log("model existis ...."),this.model=await async function(e,t={}){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&null==e.load&&(e.endsWith("/")||(e+="/"),e=`${e}model.json?tfjs-format=file`);const n=new ix(e,t);return await n.load(),n}(this.modelPath);const e=io([1,300,300,3],"int32"),t=await this.model.executeAsync(e);t.map((async e=>await e.data())),t.map((async e=>e.dispose())),Sr(e)}async detect(e){let t=Date.now();const[n,s]=function(e){return e instanceof Ds?[e.shape[0],e.shape[1]]:[e.height,e.width]}(e),a=OD(this.modelParams.imageScaleFactor,n,this.modelParams.outputStride),r=OD(this.modelParams.imageScaleFactor,s,this.modelParams.outputStride),i=Cr((()=>{const t=ar(e);return this.modelParams.flipHorizontal?t.reverse(1).resizeBilinear([a,r]).expandDims(0).toInt():t.resizeBilinear([a,r]).expandDims(0).toInt()})),o=this;return this.model.executeAsync(i,AD).then((function(e){const a=e[0].dataSync(),r=e[1].dataSync();i.dispose(),Sr(e);const[l,u]=function(e,t,n){const s=[],a=[];for(let r=0;rt&&(t=e[r*n+s],i=s);s[r]=t,a[r]=i}return[s,a]}(a,e[0].shape[1],e[0].shape[2]),c=Zs.backendName;Er("cpu");const h=Cr((()=>{const t=Oo(r,[e[1].shape[1],e[1].shape[3]]);return Gl.nonMaxSuppression(t,l,o.modelParams.maxNumBoxes,o.modelParams.iouThreshold,o.modelParams.scoreThreshold)})),p=h.dataSync();h.dispose(),Er(c);const d=o.buildDetectedObjects(s,n,r,l,p,u);let f=Date.now();return o.fps=Math.round(1e3/(f-t)),d}))}buildDetectedObjects(e,t,n,s,a,r){const i=a.length,o=[];for(let l=0;l - - - - - - Svelte app - - - - - - - - - -from js import handTrack, requestAnimationFrame -from pyodide import create_once_callable -import asyncio - -context = canvas.element.getContext("2d") - -isVideo = False -model = None - -modelParams = { - "flipHorizontal": True, # flip e.g for video - "maxNumBoxes": 20, # maximum number of boxes to detect - "iouThreshold": 0.5, # ioU threshold for non-max suppression - "scoreThreshold": 0.6, # confidence threshold for predictions. -} - -def toggle_video(evt): - global isVideo - if (not isVideo): - update_note.write("Starting video") - pyscript.run_until_complete(start_video()) - else: - update_note.write("Stopping video") - handTrack.stopVideo(video.element) - isVideo = False - update_note.write("Video stopped") - -async def start_video(): - global isVideo - update_note.write("Inside sstart video") - status = await handTrack.startVideo(video.element) - console.log("video started", status) - if status: - update_note.write("Video started. Now tracking") - isVideo = True - console.log( "Calling RUN DETECTION") - y = await run_detection() - else: - update_note.write( "Please enable video") - -def sync_run_detection(evt): - pyscript.run_until_complete(run_detection()) - -async def run_detection(): - console.log("in RUN DETECTION: "); - global model - global isVideo - - console.log("...1") - - predictions = await model.detect(video.element) - console.log("done...1") - console.log("Predictions: ", predictions); - model.renderPredictions(predictions, canvas.element, context, video.element); - console.log("is Video?", isVideo) - if (isVideo): - console.log("requestingAnimation!") - await requestAnimationFrame(create_once_callable(sync_run_detection)); - console.log("...2") - -def run_detection_image(img): - console.log("in RUN DETECTION IMAGE", predictions); - global model - def detect(predition): - console.log("Predictions: ", predictions); - model.renderPredictions(predictions, canvas, context, img); - console.log("...3") - model.detect(img).then(detect) - console.log("...4") - -def handle_model(lmodel): - global model - model = lmodel - update_note.write("Loaded Model!") - -async def start(): - console.log("creating x") - console.log("calling x") - model = await handTrack.load(modelParams)#.then(handle_model) - console.log("loaded model!") - console.log(model) - handle_model(model) - print(dir(x)) - print(x) - -pyscript.run_until_complete(start()) - -#}); - - - -
- - -
loading model ..
-
-
- - -
- - diff --git a/examples/hello_world.html b/examples/hello_world.html deleted file mode 100644 index 7ae6994a12e..00000000000 --- a/examples/hello_world.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - PyScript Hello World - - - - - - - - - Hello world!
- This is the current date and time, as computed by Python: - -from datetime import datetime -now = datetime.now() -now.strftime("%m/%d/%Y, %H:%M:%S") - - - diff --git a/examples/index.html b/examples/index.html deleted file mode 100644 index 7a64e8279bc..00000000000 --- a/examples/index.html +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - PyScript demo - - - - - - - -

PyScript demos

- -
-

Basic examples

-
- -

Hello world

-

A static demo of the <py-script> tag

- -

Simple clock

-

A dynamic demo of the <py-script> tag

- -

REPL

-

A Python REPL (Read Eval Print Loop).

- -

REPL2

-

A Python REPL (Read Eval Print Loop) with slightly better formatting.

- -

TODO App

-

Demo showing how would a Simple TODO App would look like in PyScript tag

- -

PyScript Native TODO App

-

Demo showing how would a Simple TODO App would look like only using PyScript native elements tag

- -
-

MIME Rendering

-
- -

Matplotlib

-

Demonstrates rendering Matplotlib figure as output of the py-script tag

- -

Altair

-

Demonstrates rendering Altair plot as output of the py-script tag

- -

Folium

-

Demonstrates rendering Folium map as output of the py-script tag

- -
-

JS Interaction

-
- -

Simple d3 visualization

-

Minimal D3 demo demonstrating how to create a visualization

- -

Webgl Icosahedron Example

-

Demo showing how a Simple WebGL scene would work in PyScript tag

- - -
-

Visualizations & Dashboards

-
-

Simple Static Bokeh Plot

-

Minimal Bokeh demo demonstrating how to create a simple Bokeh plot from code

- -

Bokeh Interactive

-

Interactive demo using a Bokeh slider widget to dynamically change a value in the page - - WARNING: This examples takes a little longer to load. So be patient :) -

- -

KMeans Demo in Panel

-

Interactive KMeans Chart using Panel - - WARNING: This examples takes a little longer to load. So be patient :) -

- -

Streaming Demo in Panel

-

Interactive Streaming Table and Bokeh plot using Panel - - WARNING: This examples takes a little longer to load. So be patient :) -

- -

Simple Panel Demo

-

Simple demo showing Panel widgets interacting with parts of the page - - WARNING: This examples takes a little longer to load. So be patient :) -

- -

NYC Taxi Data Panel DeckGL Demo

-

Interactive application exploring the NYC Taxi dataset using Panel and DeckGL - - WARNING: This examples takes a little longer to load. So be patient :) -

- -

Freedom Units!

-

A Toga application (a Fahrenheit to Celsius converter), rendered as a Single Page App

- -

Fractals with NumPy and canvas

-

Visualization of Mandelbrot and Julia sets with Numpy and HTML5 canvas

- - - diff --git a/examples/logo.png b/examples/logo.png deleted file mode 100644 index faa009717d7..00000000000 Binary files a/examples/logo.png and /dev/null differ diff --git a/examples/mario/css/game.css b/examples/mario/css/game.css deleted file mode 100644 index 7dced929362..00000000000 --- a/examples/mario/css/game.css +++ /dev/null @@ -1,32 +0,0 @@ -html, body, ul, li { - margin: 0; - border: 0; - padding: 0; -} - -canvas { - display: block; - width: 762; - margin: 0 auto; - background-color: blue; -} - -p { - text-align: center; -} - -body { - overflow: hidden; - height: 100%; -} - -html { - overflow: hidden; - height: 100%; -} - -.info { - position: absolute; - top: 0; - left: 0; -} diff --git a/examples/mario/js/bcoin.js b/examples/mario/js/bcoin.js deleted file mode 100644 index 34fe1cb5798..00000000000 --- a/examples/mario/js/bcoin.js +++ /dev/null @@ -1,45 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Bcoin = Mario.Bcoin = function(pos) { - Mario.Entity.call(this, { - pos: pos, - sprite: level.bcoinSprite(), - hitbox: [0,0,16,16] - }); - } - - Mario.Util.inherits(Bcoin, Mario.Entity); - - //I'm not sure whether it makes sense to use an array for vel and acc here - //in order to keep with convention, or to just use a single value, since - //it's literally impossible for these to move left or right. - Bcoin.prototype.spawn = function() { - sounds.coin.currentTime = 0.05; - sounds.coin.play(); - this.idx = level.items.length; - level.items.push(this); - this.active = true; - this.vel = -12; - this.targetpos = this.pos[1] - 32; - } - - Bcoin.prototype.update = function(dt) { - if (!this.active) return; - - if (this.vel > 0 && this.pos[1] >= this.targetpos) { - player.coins += 1; - //spawn a score thingy. - delete level.items[this.idx]; - } - - this.acc = 0.75; - this.vel += this.acc; - this.pos[1] += this.vel; - this.sprite.update(dt); - } - - Bcoin.prototype.checkCollisions = function() {;} - -})(); diff --git a/examples/mario/js/block.js b/examples/mario/js/block.js deleted file mode 100644 index e695f049ca9..00000000000 --- a/examples/mario/js/block.js +++ /dev/null @@ -1,81 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - //TODO: clean up the logic for sprite switching. - //TODO: There's a weird bug with the collision logic. Look into it. - - var Block = Mario.Block = function(options) { - this.item = options.item; - this.usedSprite = options.usedSprite; - this.bounceSprite = options.bounceSprite; - this.breakable = options.breakable; - - Mario.Entity.call(this, { - pos: options.pos, - sprite: options.sprite, - hitbox: [0,0,16,16] - }); - - this.standing = true; - } - - Mario.Util.inherits(Block, Mario.Floor); - - Block.prototype.break = function() { - sounds.breakBlock.play(); - (new Mario.Rubble()).spawn(this.pos); - var x = this.pos[0] / 16, y = this.pos[1] / 16; - delete level.blocks[y][x]; - } - - Block.prototype.bonk = function(power) { - sounds.bump.play(); - if (power > 0 && this.breakable) { - this.break(); - } else if (this.standing){ - this.standing = false; - if (this.item) { - this.item.spawn(); - this.item = null; - } - this.opos = []; - this.opos[0] = this.pos[0]; - this.opos[1] = this.pos[1]; - if (this.bounceSprite) { - this.osprite = this.sprite; - this.sprite = this.bounceSprite; - } else { - this.sprite = this.usedSprite; - } - - this.vel[1] = -2; - } - } - - Block.prototype.update = function(dt, gameTime) { - if (!this.standing) { - if (this.pos[1] < this.opos[1] - 8) { - this.vel[1] = 2; - } - if (this.pos[1] > this.opos[1]) { - this.vel[1] = 0; - this.pos = this.opos; - if (this.osprite) { - this.sprite = this.osprite; - } - this.standing = true; - } - } else { - if (this.sprite === this.usedSprite) { - var x = this.pos[0] / 16, y = this.pos[1] / 16; - level.statics[y][x] = new Mario.Floor(this.pos, this.usedSprite); - delete level.blocks[y][x]; - } - } - - this.pos[1] += this.vel[1]; - this.sprite.update(dt, gameTime); - } - -})(); diff --git a/examples/mario/js/coin.js b/examples/mario/js/coin.js deleted file mode 100644 index 28f1758de31..00000000000 --- a/examples/mario/js/coin.js +++ /dev/null @@ -1,47 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Coin = Mario.Coin = function(pos, sprite) { - Mario.Entity.call(this, { - pos: pos, - sprite: sprite, - hitbox: [0,0,16,16] - }); - this.idx = level.items.length - } - - Mario.Util.inherits(Coin, Mario.Entity); - - Coin.prototype.isPlayerCollided = function() { - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [this.pos[0] + this.hitbox[0], this.pos[1] + this.hitbox[1]]; - var hpos2 = [player.pos[0] + player.hitbox[0], player.pos[1] + player.hitbox[1]]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+player.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+player.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - this.collect(); - } - } - } - - Coin.prototype.render = function(ctx, vX, vY) { - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY); - } - - //money is not affected by gravity, you see. - Coin.prototype.update = function(dt) { - this.sprite.update(dt); - } - Coin.prototype.checkCollisions = function() { - this.isPlayerCollided(); - } - - Coin.prototype.collect = function() { - sounds.coin.currentTime = 0.05; - sounds.coin.play(); - player.coins += 1; - delete level.items[this.idx] - } -})(); diff --git a/examples/mario/js/entity.js b/examples/mario/js/entity.js deleted file mode 100644 index 2f102b90ce7..00000000000 --- a/examples/mario/js/entity.js +++ /dev/null @@ -1,34 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Entity = Mario.Entity = function(options) { - this.vel = [0,0]; - this.acc = [0,0]; - this.standing = true; - this.pos = options.pos; - this.sprite = options.sprite; - this.hitbox = options.hitbox; - this.left = false; - } - - Entity.prototype.render = function(ctx, vX, vY) { - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY) - } - - Entity.prototype.collideWall = function(wall) { - //the wall will always be a 16x16 block with hitbox = [0,0,16,16]. - if (this.pos[0] > wall.pos[0]) { - //from the right - this.pos[0] = wall.pos[0] + wall.hitbox[2] - this.hitbox[0]; - this.vel[0] = Math.max(0, this.vel[0]); - this.acc[0] = Math.max(0, this.acc[0]); - } else { - this.pos[0] = wall.pos[0] + wall.hitbox[0] - this.hitbox[2] - this.hitbox[0]; - this.vel[0] = Math.min(0, this.vel[0]); - this.acc[0] = Math.min(0, this.acc[0]); - } - } - - Entity.prototype.bump = function() {;} -})(); diff --git a/examples/mario/js/fireball.js b/examples/mario/js/fireball.js deleted file mode 100644 index f49798be940..00000000000 --- a/examples/mario/js/fireball.js +++ /dev/null @@ -1,126 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Fireball = Mario.Fireball = function(pos) { - this.hit = 0; - this.standing = false; - - Mario.Entity.call(this, { - pos: pos, - sprite: new Mario.Sprite('sprites/items.png', [96, 144], [8,8], 5, [0,1,2,3]), - hitbox: [0,0,8,8] - }); - } - - Mario.Util.inherits(Fireball, Mario.Entity); - - Fireball.prototype.spawn = function(left) { - sounds.fireball.currentTime = 0; - sounds.fireball.play(); - if (fireballs[0]) { - this.idx = 1; - fireballs[1] = this; - } else { - this.idx = 0; - fireballs[0] = this; - } - this.vel[0] = (left ? -5 : 5); - this.standing = false; - this.vel[1] = 0; - } - - Fireball.prototype.render = function(ctx, vX, vY) { - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY); - } - - Fireball.prototype.update = function(dt) { - if (this.hit == 1) { - this.sprite.pos = [96, 160]; - this.sprite.size = [16,16]; - this.sprite.frames = [0,1,2]; - this.sprite.speed = 8; - this.hit += 1; - return; - } else if (this.hit == 5) { - delete fireballs[this.idx]; - player.fireballs -= 1; - return; - } else if (this.hit) { - this.hit += 1; - return; - } - - //In retrospect, the way collision is being handled is RIDICULOUS - //but I don't have to use some horrible kludge for this. - if (this.standing) { - this.standing = false; - this.vel[1] = -4; - } - - this.acc[1] = 0.5; - - this.vel[1] += this.acc[1]; - this.pos[0] += this.vel[0]; - this.pos[1] += this.vel[1]; - if (this.pos[0] < vX || this.pos[0] > vX + 256) { - this.hit = 1; - } - this.sprite.update(dt); - } - - Fireball.prototype.collideWall = function() { - if (!this.hit) this.hit = 1; - } - - Fireball.prototype.checkCollisions = function() { - if (this.hit) return; - var h = this.pos[1] % 16 < 8 ? 1 : 2; - var w = this.pos[0] % 16 < 8 ? 1 : 2; - - var baseX = Math.floor(this.pos[0] / 16); - var baseY = Math.floor(this.pos[1] / 16); - - if (baseY + h > 15) { - delete fireballs[this.idx]; - player.fireballs -= 1; - return; - } - - for (var i = 0; i < h; i++) { - for (var j = 0; j < w; j++) { - if (level.statics[baseY + i][baseX + j]) { - level.statics[baseY + i][baseX + j].isCollideWith(this); - } - if (level.blocks[baseY + i][baseX + j]) { - level.blocks[baseY + i][baseX + j].isCollideWith(this); - } - } - } - - var that = this; - level.enemies.forEach(function(enemy){ - if (enemy.flipping || enemy.pos[0] - vX > 336){ //stop checking once we get to far away dudes. - return; - } else { - that.isCollideWith(enemy); - } - }); - } - - Fireball.prototype.isCollideWith = function(ent) { - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [this.pos[0] + this.hitbox[0], this.pos[1] + this.hitbox[1]]; - var hpos2 = [ent.pos[0] + ent.hitbox[0], ent.pos[1] + ent.hitbox[1]]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+ent.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+ent.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - this.hit = 1; - ent.bump(); - } - } - }; - - Fireball.prototype.bump = function() {;} -})(); diff --git a/examples/mario/js/fireflower.js b/examples/mario/js/fireflower.js deleted file mode 100644 index b66056d43cc..00000000000 --- a/examples/mario/js/fireflower.js +++ /dev/null @@ -1,74 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Fireflower = Mario.Fireflower = function(pos) { - this.spawning = false; - this.waiting = 0; - - Mario.Entity.call(this, { - pos: pos, - sprite: level.fireFlowerSprite, - hitbox: [0,0,16,16] - }); - } - - Mario.Util.inherits(Fireflower, Mario.Entity); - - Fireflower.prototype.render = function(ctx, vX, vY) { - if (this.spawning > 1) return; - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY); - } - - Fireflower.prototype.spawn = function() { - sounds.itemAppear.play(); - this.idx = level.items.length; - level.items.push(this); - this.spawning = 12; - this.targetpos = []; - this.targetpos[0] = this.pos[0]; - this.targetpos[1] = this.pos[1] - 16; - } - - Fireflower.prototype.update = function(dt) { - if (this.spawning > 1) { - this.spawning -= 1; - if (this.spawning == 1) this.vel[1] = -.5; - return; - } - if (this.spawning) { - if (this.pos[1] <= this.targetpos[1]) { - this.pos[1] = this.targetpos[1]; - this.vel[1] = 0; - this.spawning = 0; - } - } - - this.vel[1] += this.acc[1]; - this.pos[0] += this.vel[0]; - this.pos[1] += this.vel[1]; - this.sprite.update(dt); - } - - Fireflower.prototype.checkCollisions = function() { - if (this.spawning) {return;} - this.isPlayerCollided(); - } - - Fireflower.prototype.isPlayerCollided = function() { - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [this.pos[0] + this.hitbox[0], this.pos[1] + this.hitbox[1]]; - var hpos2 = [player.pos[0] + player.hitbox[0], player.pos[1] + player.hitbox[1]]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+player.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+player.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - player.powerUp(this.idx); - } - } - } - - //This should never be called, but just in case. - Fireflower.prototype.bump = function() {;} - -})(); diff --git a/examples/mario/js/flag.js b/examples/mario/js/flag.js deleted file mode 100644 index f71bb5d4c6f..00000000000 --- a/examples/mario/js/flag.js +++ /dev/null @@ -1,47 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - Flag = Mario.Flag = function(pos) { - //afaik flags always have the same height and Y-position - this.pos = [pos, 49]; - this.hitbox = [0,0,0,0]; - this.vel = [0,0]; - this.acc = [0,0]; - } - - Flag.prototype.collideWall = function() {; - } - - Flag.prototype.update = function(dt){ - if (!this.done && this.pos[1] >= 170) { - this.vel = [0,0]; - this.pos[1] = 170; - player.exit(); - this.done = true; - } - this.pos[1] += this.vel[1]; - } - - Flag.prototype.checkCollisions = function() { - this.isPlayerCollided(); - } - - Flag.prototype.isPlayerCollided = function() { - if (this.hit) return; - if (player.pos[0] + 8 >= this.pos[0]) { - music.overworld.pause(); - sounds.flagpole.play(); - setTimeout(function() { - music.clear.play(); - }, 2000); - this.hit = true; - player.flag(); - this.vel = [0, 2]; - } - } - - Flag.prototype.render = function() { - level.flagpoleSprites[2].render(ctx, this.pos[0]-8, this.pos[1], vX, vY); - } -})(); diff --git a/examples/mario/js/floor.js b/examples/mario/js/floor.js deleted file mode 100644 index 016d6788a4c..00000000000 --- a/examples/mario/js/floor.js +++ /dev/null @@ -1,56 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Floor = Mario.Floor = function(pos, sprite) { - - Mario.Entity.call(this, { - pos: pos, - sprite: sprite, - hitbox: [0,0,16,16] - }); - } - - Mario.Util.inherits(Floor, Mario.Entity); - - Floor.prototype.isCollideWith = function (ent) { - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [Math.floor(this.pos[0] + this.hitbox[0]), Math.floor(this.pos[1] + this.hitbox[1])]; - var hpos2 = [Math.floor(ent.pos[0] + ent.hitbox[0]), Math.floor(ent.pos[1] + ent.hitbox[1])]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+ent.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+ent.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - if (!this.standing) { - ent.bump(); - } else { - //if the entity is over the block, it's basically floor - var center = hpos2[0] + ent.hitbox[2] / 2; - if (Math.abs(hpos2[1] + ent.hitbox[3] - hpos1[1]) <= ent.vel[1]) { - if (level.statics[(this.pos[1] / 16) - 1][this.pos[0] / 16]) {return}; - ent.vel[1] = 0; - ent.pos[1] = hpos1[1] - ent.hitbox[3] - ent.hitbox[1]; - ent.standing = true; - if (ent instanceof Mario.Player) { - ent.jumping = 0; - } - } else if (Math.abs(hpos2[1] - hpos1[1] - this.hitbox[3]) > ent.vel[1] && - center + 2 >= hpos1[0] && center - 2 <= hpos1[0] + this.hitbox[2]) { - //ent is under the block. - ent.vel[1] = 0; - ent.pos[1] = hpos1[1] + this.hitbox[3]; - if (ent instanceof Mario.Player) { - this.bonk(ent.power); - ent.jumping = 0; - } - } else { - //entity is hitting it from the side, we're a wall - ent.collideWall(this); - } - } - } - } - } - - Floor.prototype.bonk = function() {;} -})(); diff --git a/examples/mario/js/game.js b/examples/mario/js/game.js deleted file mode 100644 index 2ad523aab94..00000000000 --- a/examples/mario/js/game.js +++ /dev/null @@ -1,241 +0,0 @@ -var requestAnimFrame = (function(){ - return window.requestAnimationFrame || - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - window.oRequestAnimationFrame || - window.msRequestAnimationFrame || - function(callback){ - window.setTimeout(callback, 1000 / 60); - }; -})(); - -//create the canvas -var canvas = document.createElement("canvas"); -var ctx = canvas.getContext('2d'); -var updateables = []; -var fireballs = []; -var player = new Mario.Player([0,0]); - -//we might have to get the size and calculate the scaling -//but this method should let us make it however big. -//Cool! -//TODO: Automatically scale the game to work and look good on widescreen. -//TODO: fiddling with scaled sprites looks BETTER, but not perfect. Hmm. -canvas.width = 762; -canvas.height = 720; -ctx.scale(3,3); -document.body.appendChild(canvas); - -//viewport -var vX = 0, - vY = 0, - vWidth = 256, - vHeight = 240; - -//load our images -resources.load([ - 'sprites/player.png', - 'sprites/enemy.png', - 'sprites/tiles.png', - 'sprites/playerl.png', - 'sprites/items.png', - 'sprites/enemyr.png', -]); - -resources.onReady(init); -var level; -var sounds; -var music; - -//initialize -var lastTime; -function init() { - music = { - overworld: new Audio('sounds/aboveground_bgm.ogg'), - underground: new Audio('sounds/underground_bgm.ogg'), - clear: new Audio('sounds/stage_clear.wav'), - death: new Audio('sounds/mariodie.wav') - }; - sounds = { - smallJump: new Audio('sounds/jump-small.wav'), - bigJump: new Audio('sounds/jump-super.wav'), - breakBlock: new Audio('sounds/breakblock.wav'), - bump: new Audio('sounds/bump.wav'), - coin: new Audio('sounds/coin.wav'), - fireball: new Audio('sounds/fireball.wav'), - flagpole: new Audio('sounds/flagpole.wav'), - kick: new Audio('sounds/kick.wav'), - pipe: new Audio('sounds/pipe.wav'), - itemAppear: new Audio('sounds/itemAppear.wav'), - powerup: new Audio('sounds/powerup.wav'), - stomp: new Audio('sounds/stomp.wav') - }; - Mario.oneone(); - lastTime = Date.now(); - main(); -} - -var gameTime = 0; - -//set up the game loop -function main() { - var now = Date.now(); - var dt = (now - lastTime) / 1000.0; - - update(dt); - render(); - - lastTime = now; - requestAnimFrame(main); -} - -function update(dt) { - gameTime += dt; - - handleInput(dt); - updateEntities(dt, gameTime); - - checkCollisions(); -} - -function handleInput(dt) { - if (player.piping || player.dying || player.noInput) return; //don't accept input - - if (input.isDown('RUN')){ - player.run(); - } else { - player.noRun(); - } - if (input.isDown('JUMP')) { - player.jump(); - } else { - //we need this to handle the timing for how long you hold it - player.noJump(); - } - - if (input.isDown('DOWN')) { - player.crouch(); - } else { - player.noCrouch(); - } - - if (input.isDown('LEFT')) { // 'd' or left arrow - player.moveLeft(); - } - else if (input.isDown('RIGHT')) { // 'k' or right arrow - player.moveRight(); - } else { - player.noWalk(); - } -} - -//update all the moving stuff -function updateEntities(dt, gameTime) { - player.update(dt, vX); - updateables.forEach (function(ent) { - ent.update(dt, gameTime); - }); - - //This should stop the jump when he switches sides on the flag. - if (player.exiting) { - if (player.pos[0] > vX + 96) - vX = player.pos[0] - 96 - }else if (level.scrolling && player.pos[0] > vX + 80) { - vX = player.pos[0] - 80; - } - - if (player.powering.length !== 0 || player.dying) { return; } - level.items.forEach (function(ent) { - ent.update(dt); - }); - - level.enemies.forEach (function(ent) { - ent.update(dt, vX); - }); - - fireballs.forEach(function(fireball) { - fireball.update(dt); - }); - level.pipes.forEach (function(pipe) { - pipe.update(dt); - }); -} - -//scan for collisions -function checkCollisions() { - if (player.powering.length !== 0 || player.dying) { return; } - player.checkCollisions(); - - //Apparently for each will just skip indices where things were deleted. - level.items.forEach(function(item) { - item.checkCollisions(); - }); - level.enemies.forEach (function(ent) { - ent.checkCollisions(); - }); - fireballs.forEach(function(fireball){ - fireball.checkCollisions(); - }); - level.pipes.forEach (function(pipe) { - pipe.checkCollisions(); - }); -} - -//draw the game! -function render() { - updateables = []; - ctx.clearRect(0, 0, canvas.width, canvas.height); - ctx.fillStyle = level.background; - ctx.fillRect(0, 0, canvas.width, canvas.height); - - //scenery gets drawn first to get layering right. - for(var i = 0; i < 15; i++) { - for (var j = Math.floor(vX / 16) - 1; j < Math.floor(vX / 16) + 20; j++){ - if (level.scenery[i][j]) { - renderEntity(level.scenery[i][j]); - } - } - } - - //then items - level.items.forEach (function (item) { - renderEntity(item); - }); - - level.enemies.forEach (function(enemy) { - renderEntity(enemy); - }); - - - - fireballs.forEach(function(fireball) { - renderEntity(fireball); - }) - - //then we draw every static object. - for(var i = 0; i < 15; i++) { - for (var j = Math.floor(vX / 16) - 1; j < Math.floor(vX / 16) + 20; j++){ - if (level.statics[i][j]) { - renderEntity(level.statics[i][j]); - } - if (level.blocks[i][j]) { - renderEntity(level.blocks[i][j]); - updateables.push(level.blocks[i][j]); - } - } - } - - //then the player - if (player.invincibility % 2 === 0) { - renderEntity(player); - } - - //Mario goes INTO pipes, so naturally they go after. - level.pipes.forEach (function(pipe) { - renderEntity(pipe); - }); -} - -function renderEntity(entity) { - entity.render(ctx, vX, vY); -} diff --git a/examples/mario/js/goomba.js b/examples/mario/js/goomba.js deleted file mode 100644 index 78f420a30d1..00000000000 --- a/examples/mario/js/goomba.js +++ /dev/null @@ -1,129 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - //TODO: On console the hitbox is smaller. Measure it and edit this. - - var Goomba = Mario.Goomba = function(pos, sprite) { - this.dying = false; - Mario.Entity.call(this, { - pos: pos, - sprite: sprite, - hitbox: [0,0,16,16] - }); - this.vel[0] = -0.5; - this.idx = level.enemies.length; - }; - - Goomba.prototype.render = function(ctx, vX, vY) { - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY); - }; - - Goomba.prototype.update = function(dt, vX) { - if (this.pos[0] - vX > 336) { //if we're too far away, do nothing. - return; - } else if (this.pos[0] - vX < -32) { - delete level.enemies[this.idx]; - } - - if (this.dying) { - this.dying -= 1; - if (!this.dying) { - delete level.enemies[this.idx]; - } - } - this.acc[1] = 0.2; - this.vel[1] += this.acc[1]; - this.pos[0] += this.vel[0]; - this.pos[1] += this.vel[1]; - this.sprite.update(dt); - }; - - Goomba.prototype.collideWall = function() { - this.vel[0] = -this.vel[0]; - }; - - Goomba.prototype.checkCollisions = function() { - if (this.flipping) { - return; - } - - var h = this.pos[1] % 16 === 0 ? 1 : 2; - var w = this.pos[0] % 16 === 0 ? 1 : 2; - - var baseX = Math.floor(this.pos[0] / 16); - var baseY = Math.floor(this.pos[1] / 16); - - if (baseY + h > 15) { - delete level.enemies[this.idx]; - return; - } - - for (var i = 0; i < h; i++) { - for (var j = 0; j < w; j++) { - if (level.statics[baseY + i][baseX + j]) { - level.statics[baseY + i][baseX + j].isCollideWith(this); - } - if (level.blocks[baseY + i][baseX + j]) { - level.blocks[baseY + i][baseX + j].isCollideWith(this); - } - } - } - var that = this; - level.enemies.forEach(function(enemy){ - if (enemy === that) { //don't check collisions with ourselves. - return; - } else if (enemy.pos[0] - vX > 336){ //stop checking once we get to far away dudes. - return; - } else { - that.isCollideWith(enemy); - } - }); - this.isCollideWith(player); - }; - - Goomba.prototype.isCollideWith = function(ent) { - if (ent instanceof Mario.Player && (this.dying || ent.invincibility)) { - return; - } - - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [this.pos[0] + this.hitbox[0], this.pos[1] + this.hitbox[1]]; - var hpos2 = [ent.pos[0] + ent.hitbox[0], ent.pos[1] + ent.hitbox[1]]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+ent.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+ent.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - if (ent instanceof Mario.Player) { //if we hit the player - if (ent.vel[1] > 0) { //then the goomba dies - this.stomp(); - } else if (ent.starTime) { - this.bump(); - } else { //or the player gets hit - ent.damage(); - } - } else { - this.collideWall(); - } - } - } - }; - - Goomba.prototype.stomp = function() { - sounds.stomp.play(); - player.bounce = true; - this.sprite.pos[0] = 32; - this.sprite.speed = 0; - this.vel[0] = 0; - this.dying = 10; - }; - - Goomba.prototype.bump = function() { - sounds.kick.play(); - this.sprite.img = 'sprites/enemyr.png'; - this.flipping = true; - this.pos[1] -= 1; - this.vel[0] = 0; - this.vel[1] = -2.5; - }; -})(); diff --git a/examples/mario/js/input.js b/examples/mario/js/input.js deleted file mode 100644 index 79ae29629a0..00000000000 --- a/examples/mario/js/input.js +++ /dev/null @@ -1,54 +0,0 @@ -(function() { - var pressedKeys = {}; - - function setKey(event, status) { - var code = event.keyCode; - var key; - - switch(code) { - case 32: - key = 'SPACE'; break; - case 37: - key = 'LEFT'; break; - case 38: - key = 'UP'; break; - case 39: - key = 'RIGHT'; break; - case 40: - key = 'DOWN'; break; - case 88: - key = 'JUMP'; break; - case 90: - key = 'RUN'; break; - default: - key = String.fromCharCode(code); - } - - pressedKeys[key] = status; - } - - document.addEventListener('keydown', function(e) { - setKey(e, true); - }); - - document.addEventListener('keyup', function(e) { - setKey(e, false); - }); - - window.addEventListener('blur', function() { - pressedKeys = {}; - }); - - window.input = { - isDown: function(key) { - return pressedKeys[key.toUpperCase()]; - }, - reset: function() { - pressedKeys['RUN'] = false; - pressedKeys['LEFT'] = false; - pressedKeys['RIGHT'] = false; - pressedKeys['DOWN'] = false; - pressedKeys['JUMP'] = false; - } - }; -})(); diff --git a/examples/mario/js/koopa.js b/examples/mario/js/koopa.js deleted file mode 100644 index d7243b7231e..00000000000 --- a/examples/mario/js/koopa.js +++ /dev/null @@ -1,211 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Koopa = Mario.Koopa = function(pos, sprite, para) { - this.dying = false; - this.shell = false; - - this.para = para; //para. As in, is it a paratroopa? - - //So, funny story. The actual hitboxes don't reach all the way to the ground. - //What that means is, as long as I use them to keep things on the floor - //making the hitboxes accurate will make enemies sink into the ground. - Mario.Entity.call(this, { - pos: pos, - sprite: sprite, - hitbox: [2,8,12,24] - }); - this.vel[0] = -0.5; - this.idx = level.enemies.length; - }; - - Koopa.prototype.render = function(ctx, vX, vY) { - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY); - }; - - Koopa.prototype.update = function(dt, vX) { - if (this.turn) { - this.vel[0] = -this.vel[0]; - if (this.shell) sounds.bump.play(); - this.turn = false; - } - if (this.vel[0] != 0) { - this.left = (this.vel[0] < 0); - } - - if (this.left) { - this.sprite.img = 'sprites/enemy.png'; - } else { - this.sprite.img = 'sprites/enemyr.png'; - } - - if (this.pos[0] - vX > 336) { //if we're too far away, do nothing. - return; - } else if (this.pos[0] - vX < -32) { - delete level.enemies[this.idx]; - } - - if (this.dying) { - this.dying -= 1; - if (!this.dying) { - delete level.enemies[this.idx]; - } - } - - if (this.shell) { - if (this.vel[0] == 0) { - this.shell -= 1; - if (this.shell < 120) { - this.sprite.speed = 5; - } - if (this.shell == 0) { - this.sprite = level.koopaSprite(); - this.hitbox = [2,8,12,24] - if (this.left) { - this.sprite.img = 'sprites/enemyr.png'; - this.vel[0] = 0.5; - this.left = false; - } else { - this.vel[0] = -0.5; - this.left = true; - } - this.pos[1] -= 16; - } - } else { - this.shell = 360; - this.sprite.speed = 0; - this.sprite.setFrame(0); - } - } - this.acc[1] = 0.2; - this.vel[1] += this.acc[1]; - this.pos[0] += this.vel[0]; - this.pos[1] += this.vel[1]; - this.sprite.update(dt); - }; - - Koopa.prototype.collideWall = function() { - //This stops us from flipping twice on the same frame if we collide - //with multiple wall tiles simultaneously. - this.turn = true; - }; - - Koopa.prototype.checkCollisions = function() { - var h = this.shell ? 1 : 2; - if (this.pos[1] % 16 !== 0) { - h += 1; - } - var w = this.pos[0] % 16 === 0 ? 1 : 2; - - var baseX = Math.floor(this.pos[0] / 16); - var baseY = Math.floor(this.pos[1] / 16); - - if (baseY + h > 15) { - delete level.enemies[this.idx]; - return; - } - - if (this.flipping) { - return; - } - - for (var i = 0; i < h; i++) { - for (var j = 0; j < w; j++) { - if (level.statics[baseY + i][baseX + j]) { - level.statics[baseY + i][baseX + j].isCollideWith(this); - } - if (level.blocks[baseY + i][baseX + j]) { - level.blocks[baseY + i][baseX + j].isCollideWith(this); - } - } - } - var that = this; - level.enemies.forEach(function(enemy){ - if (enemy === that) { //don't check collisions with ourselves. - return; - } else if (enemy.pos[0] - vX > 336){ //stop checking once we get to far away dudes. - return; - } else { - that.isCollideWith(enemy); - } - }); - this.isCollideWith(player); - }; - - Koopa.prototype.isCollideWith = function(ent) { - if (ent instanceof Mario.Player && (this.dying || ent.invincibility)) { - return; - } - - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [this.pos[0] + this.hitbox[0], this.pos[1] + this.hitbox[1]]; - var hpos2 = [ent.pos[0] + ent.hitbox[0], ent.pos[1] + ent.hitbox[1]]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+ent.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+ent.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - if (ent instanceof Mario.Player) { - if (ent.vel[1] > 0) { - player.bounce = true; - } - if (this.shell) { - sounds.kick.play(); - if (this.vel[0] === 0) { - if (ent.left) { //I'm pretty sure this isn't the real logic. - this.vel[0] = -4; - } else { - this.vel[0] = 4; - } - } else { - if (ent.bounce) { - this.vel[0] = 0; - } else ent.damage(); - } - } else if (ent.vel[1] > 0) { //then we get BOPPED. - this.stomp(); - } else { //or the player gets hit - ent.damage(); - } - } else { - if (this.shell && (ent instanceof Mario.Goomba)) { - ent.bump(); - } else this.collideWall(); - } - } - } - }; - - Koopa.prototype.stomp = function() { - //Turn this thing into a shell if it isn't already. Kick it if it is. - player.bounce = true; - if (this.para) { - this.para = false; - this.sprite.pos[0] -= 32; - } else { - sounds.stomp.play(); - this.shell = 360; - this.sprite.pos[0] += 64; - this.sprite.pos[1] += 16; - this.sprite.size = [16,16]; - this.hitbox = [2,0,12,16]; - this.sprite.speed = 0; - this.frames = [0,1]; - this.vel = [0,0]; - this.pos[1] += 16; - } - - }; - - Koopa.prototype.bump = function() { - sounds.kick.play(); - if (this.flipping) return; - this.flipping = true; - this.sprite.pos = [160, 0]; - this.sprite.size = [16,16]; - this.hitbox = [2, 0, 12, 16]; - this.sprite.speed = 0; - this.vel[0] = 0; - this.vel[1] = -2.5; - }; -})(); diff --git a/examples/mario/js/levels/11.js b/examples/mario/js/levels/11.js deleted file mode 100644 index a8192e819c2..00000000000 --- a/examples/mario/js/levels/11.js +++ /dev/null @@ -1,219 +0,0 @@ -var oneone = Mario.oneone = function() { - //The things that need to be passed in are basically just dependent on what - //tileset we're in, so it makes more sense to just make one variable for that, so - //TODO: put as much of this in the Level object definition as possible. - level = new Mario.Level({ - playerPos: [56,192], - loader: Mario.oneone, - background: "#7974FF", - scrolling: true, - invincibility: [144, 192, 240], - exit: 204, - floorSprite: new Mario.Sprite('sprites/tiles.png', [0,0],[16,16],0), - cloudSprite: new Mario.Sprite('sprites/tiles.png', [0,320],[48,32],0), - wallSprite: new Mario.Sprite('sprites/tiles.png', [0, 16],[16,16],0), - brickSprite: new Mario.Sprite('sprites/tiles.png', [16, 0], [16,16], 0), - brickBounceSprite: new Mario.Sprite('sprites/tiles.png',[32,0],[16,16],0), - rubbleSprite: function () { - return new Mario.Sprite('sprites/items.png', [64,0], [8,8], 3, [0,1]) - }, - ublockSprite: new Mario.Sprite('sprites/tiles.png', [48, 0], [16,16],0), - superShroomSprite: new Mario.Sprite('sprites/items.png', [0,0], [16,16], 0), - fireFlowerSprite: new Mario.Sprite('sprites/items.png', [0,32], [16,16], 20, [0,1,2,3]), - starSprite: new Mario.Sprite('sprites/items.png', [0,48], [16,16], 20, [0,1,2,3]), - pipeLEndSprite: new Mario.Sprite('sprites/tiles.png', [0, 128], [16,16], 0), - pipeREndSprite: new Mario.Sprite('sprites/tiles.png', [16, 128], [16,16], 0), - pipeLMidSprite: new Mario.Sprite('sprites/tiles.png', [0, 144], [16,16], 0), - pipeRMidSprite: new Mario.Sprite('sprites/tiles.png', [16, 144], [16,16], 0), - - pipeUpMid: new Mario.Sprite('sprites/tiles.png', [0, 144], [32,16], 0), - pipeSideMid: new Mario.Sprite('sprites/tiles.png', [48, 128], [16,32], 0), - pipeLeft: new Mario.Sprite('sprites/tiles.png', [32, 128], [16,32], 0), - pipeTop: new Mario.Sprite('sprites/tiles.png', [0, 128], [32,16], 0), - qblockSprite: new Mario.Sprite('sprites/tiles.png', [384, 0], [16,16], 8, [0,0,0,0,1,2,1]), - bcoinSprite: function() { - return new Mario.Sprite('sprites/items.png', [0,112],[16,16], 20,[0,1,2,3]); - }, - cloudSprites:[ - new Mario.Sprite('sprites/tiles.png', [0,320],[16,32],0), - new Mario.Sprite('sprites/tiles.png', [16,320],[16,32],0), - new Mario.Sprite('sprites/tiles.png', [32,320],[16,32],0) - ], - hillSprites: [ - new Mario.Sprite('sprites/tiles.png', [128,128],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [144,128],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [160,128],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [128,144],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [144,144],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [160,144],[16,16],0) - ], - bushSprite: new Mario.Sprite('sprites/tiles.png', [176, 144], [48, 16], 0), - bushSprites: [ - new Mario.Sprite('sprites/tiles.png', [176,144], [16,16],0), - new Mario.Sprite('sprites/tiles.png', [192,144], [16,16],0), - new Mario.Sprite('sprites/tiles.png', [208,144], [16,16],0)], - goombaSprite: function() { - return new Mario.Sprite('sprites/enemy.png', [0, 16], [16,16], 3, [0,1]); - }, - koopaSprite: function() { - return new Mario.Sprite('sprites/enemy.png', [96,0], [16,32], 2, [0,1]); - }, - flagPoleSprites: [ - new Mario.Sprite('sprites/tiles.png', [256, 128], [16,16], 0), - new Mario.Sprite('sprites/tiles.png', [256, 144], [16,16], 0), - new Mario.Sprite('sprites/items.png', [128, 32], [16,16], 0) - ] - }); - ground = [[0,69],[71,86],[89,153],[155,212]]; - player.pos[0] = level.playerPos[0]; - player.pos[1] = level.playerPos[1]; - vX = 0; - - //build THE GROUND - ground.forEach(function(loc) { - level.putFloor(loc[0],loc[1]); - }); - - //build scenery - clouds = [[7,3],[19, 2],[56, 3],[67, 2],[87, 2],[103, 2],[152, 3],[163, 2],[200, 3]]; - clouds.forEach(function(cloud){ - level.putCloud(cloud[0],cloud[1]); - }); - - twoClouds = [[36,2],[132,2],[180,2]]; - twoClouds.forEach(function(cloud){ - level.putTwoCloud(cloud[0],cloud[1]); - }); - - threeClouds = [[27,3],[75,3],[123,3],[171,3]]; - threeClouds.forEach(function(cloud){ - level.putThreeCloud(cloud[0],cloud[1]); - }); - - bHills = [0,48,96,144,192] - bHills.forEach(function(hill) { - level.putBigHill(hill, 12); - }); - - sHills = [16,64,111,160]; - sHills.forEach(function(hill) { - level.putSmallHill(hill, 12); - }); - - bushes = [23,71,118,167]; - bushes.forEach(function(bush) { - level.putBush(bush, 12); - }); - - twoBushes = [41,89,137]; - twoBushes.forEach(function(bush) { - level.putTwoBush(bush, 12); - }); - - threeBushes = [11,59,106]; - threeBushes.forEach(function(bush) { - level.putThreeBush(bush, 12); - }); - - //interactable terrain - level.putQBlock(16, 9, new Mario.Bcoin([256, 144])); - level.putBrick(20, 9, null); - level.putQBlock(21, 9, new Mario.Mushroom([336, 144])); - level.putBrick(22, 9, null); - level.putQBlock(22, 5, new Mario.Bcoin([352, 80])); - level.putQBlock(23, 9, new Mario.Bcoin([368, 144])); - level.putBrick(24, 9, null); - level.putPipe(28, 13, 2); - level.putPipe(38, 13, 3); - level.putPipe(46, 13, 4); - level.putRealPipe(57, 9, 4, "DOWN", Mario.oneonetunnel); - level.putBrick(77, 9, null); - level.putQBlock(78, 9, new Mario.Mushroom([1248, 144])); - level.putBrick(79, 9, null); - level.putBrick(80, 5, null); - level.putBrick(81, 5, null); - level.putBrick(82, 5, null); - level.putBrick(83, 5, null); - level.putBrick(84, 5, null); - level.putBrick(85, 5, null); - level.putBrick(86, 5, null); - level.putBrick(87, 5, null); - level.putBrick(91, 5, null); - level.putBrick(92, 5, null); - level.putBrick(93, 5, null); - level.putQBlock(94, 5, new Mario.Bcoin([1504, 80])); - level.putBrick(94, 9, null); - level.putBrick(100, 9, new Mario.Star([1600, 144])); - level.putBrick(101, 9, null); - level.putQBlock(105, 9, new Mario.Bcoin([1680, 144])); - level.putQBlock(108, 9, new Mario.Bcoin([1728, 144])); - level.putQBlock(108, 5, new Mario.Mushroom([1728, 80])); - level.putQBlock(111, 9, new Mario.Bcoin([1776, 144])); - level.putBrick(117, 9, null); - level.putBrick(120, 5, null); - level.putBrick(121, 5, null); - level.putBrick(122, 5, null); - level.putBrick(123, 5, null); - level.putBrick(128, 5, null); - level.putQBlock(129, 5, new Mario.Bcoin([2074, 80])); - level.putBrick(129, 9, null); - level.putQBlock(130, 5, new Mario.Bcoin([2080, 80])); - level.putBrick(130, 9, null); - level.putBrick(131, 5, null); - level.putWall(134, 13, 1); - level.putWall(135, 13, 2); - level.putWall(136, 13, 3); - level.putWall(137, 13, 4); - level.putWall(140, 13, 4); - level.putWall(141, 13, 3); - level.putWall(142, 13, 2); - level.putWall(143, 13, 1); - level.putWall(148, 13, 1); - level.putWall(149, 13, 2); - level.putWall(150, 13, 3); - level.putWall(151, 13, 4); - level.putWall(152, 13, 4); - level.putWall(155, 13, 4); - level.putWall(156, 13, 3); - level.putWall(157, 13, 2); - level.putWall(158, 13, 1); - level.putPipe(163, 13, 2); - level.putBrick(168, 9, null); - level.putBrick(169, 9, null); - level.putQBlock(170, 9, new Mario.Bcoin([2720, 144])); - level.putBrick(171, 9, null); - level.putPipe(179, 13, 2); - level.putWall(181, 13, 1); - level.putWall(182, 13, 2); - level.putWall(183, 13, 3); - level.putWall(184, 13, 4); - level.putWall(185, 13, 5); - level.putWall(186, 13, 6); - level.putWall(187, 13, 7); - level.putWall(188, 13, 8); - level.putWall(189, 13, 8); - level.putFlagpole(198); - - //and enemies - level.putGoomba(22, 12); - level.putGoomba(40, 12); - level.putGoomba(50, 12); - level.putGoomba(51, 12); - level.putGoomba(82, 4); - level.putGoomba(84, 4); - level.putGoomba(100, 12); - level.putGoomba(102, 12); - level.putGoomba(114, 12); - level.putGoomba(115, 12); - level.putGoomba(122, 12); - level.putGoomba(123, 12); - level.putGoomba(125, 12); - level.putGoomba(126, 12); - level.putGoomba(170, 12); - level.putGoomba(172, 12); - level.putKoopa(35, 11); - - music.underground.pause(); - // music.overworld.currentTime = 0; - music.overworld.play(); -}; diff --git a/examples/mario/js/levels/11tunnel.js b/examples/mario/js/levels/11tunnel.js deleted file mode 100644 index 25f2ab4bd3a..00000000000 --- a/examples/mario/js/levels/11tunnel.js +++ /dev/null @@ -1,65 +0,0 @@ -var oneonetunnel = Mario.oneonetunnel = function() { - level = new Mario.Level({ - playerPos: [40,16], - loader: Mario.oneonetunnel, - background: "#000000", - scrolling: false, - coinSprite: function() { - return new Mario.Sprite('sprites/items.png', [0,96],[16,16], 6,[0,0,0,0,1,2,1]); - }, - floorSprite: new Mario.Sprite('sprites/tiles.png', [0,32],[16,16],0), - wallSprite: new Mario.Sprite('sprites/tiles.png', [32, 32],[16,16],0), - brickSprite: new Mario.Sprite('sprites/tiles.png', [16, 0], [16,16], 0), - brickBounceSprite: new Mario.Sprite('sprites/tiles.png',[32,0],[16,16],0), - ublockSprite: new Mario.Sprite('sprites/tiles.png', [48, 0], [16,16],0), - pipeLMidSprite: new Mario.Sprite('sprites/tiles.png', [0, 144], [16,16], 0), - pipeRMidSprite: new Mario.Sprite('sprites/tiles.png', [16, 144], [16,16], 0), - pipeLEndSprite: new Mario.Sprite('sprites/tiles.png', [0, 128], [16,16], 0), - pipeREndSprite: new Mario.Sprite('sprites/tiles.png', [16, 128], [16,16], 0), - pipeUpMid: new Mario.Sprite('sprites/tiles.png', [0, 144], [32,16], 0), - pipeSideMid: new Mario.Sprite('sprites/tiles.png', [48, 128], [16,32], 0), - pipeLeft: new Mario.Sprite('sprites/tiles.png', [32, 128], [16,32], 0), - pipeTop: new Mario.Sprite('sprites/tiles.png', [0, 128], [32,16], 0), - - LPipeSprites:[ - new Mario.Sprite('sprites/tiles.png', [32,128],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [32,144],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [48,128],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [48,144],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [64,128],[16,16],0), - new Mario.Sprite('sprites/tiles.png', [64,144],[16,16],0), - ] - - }); - - player.pos[0] = level.playerPos[0]; - player.pos[1] = level.playerPos[1]; - vX = 0; - level.putFloor(0,16); - level.putWall(0,13,11); - walls = [4,5,6,7,8,9,10]; - walls.forEach(function(loc){ - level.putWall(loc,13,3); - level.putWall(loc,3,1); - }); - - coins = [[5,5], [6,5], [7,5], [8,5], [9,5], - [4,7], [5,7], [6,7], [7,7], [8,7], [9,7], [10,7], - [4,9], [5,9], [6,9], [7,9], [8,9], [9,9], [10,9]]; - coins.forEach(function(pos){ - level.putCoin(pos[0],pos[1]); - }); - - //level.putLeftPipe(13,11); - level.putRealPipe(13,11,3,"RIGHT", function() { - Mario.oneone.call(); - player.pos = [2616, 177] - player.pipe("UP", function() {;}); - }); - - level.putPipe(15,13,13); - - music.overworld.pause(); - music.underground.currentTime = 0; - music.underground.play(); -}; diff --git a/examples/mario/js/levels/level.js b/examples/mario/js/levels/level.js deleted file mode 100644 index 2a7ca17dfeb..00000000000 --- a/examples/mario/js/levels/level.js +++ /dev/null @@ -1,218 +0,0 @@ -(function() { - var Level = Mario.Level = function(options) { - this.playerPos = options.playerPos; - this.scrolling = options.scrolling; - this.loader = options.loader; - this.background = options.background; - this.exit = options.exit; - - this.floorSprite = options.floorSprite; - this.cloudSprite = options.cloudSprite; - this.wallSprite = options.wallSprite; - this.brickSprite = options.brickSprite; - this.rubbleSprite = options.rubbleSprite; - this.brickBounceSprite = options.brickBounceSprite; - this.ublockSprite = options.ublockSprite; - this.superShroomSprite = options.superShroomSprite; - this.fireFlowerSprite = options.fireFlowerSprite; - this.starSprite = options.starSprite; - this.coinSprite = options.coinSprite; - this.bcoinSprite = options.bcoinSprite; - this.goombaSprite = options.goombaSprite; - this.koopaSprite = options.koopaSprite; - - //prop pipe sprites, to be phased out - this.pipeLEndSprite = options.pipeLEndSprite; - this.pipeREndSprite = options.pipeREndSprite; - this.pipeLMidSprite = options.pipeLMidSprite; - this.pipeRMidSprite = options.pipeRMidSprite; - - //real pipe sprites, use these. - this.pipeUpMid = options.pipeUpMid; - this.pipeSideMid = options.pipeSideMid; - this.pipeLeft = options.pipeLeft; - this.pipeTop = options.pipeTop; - - this.flagpoleSprites = options.flagPoleSprites; - - this.LPipeSprites = options.LPipeSprites; - this.cloudSprites = options.cloudSprites; - this.hillSprites = options.hillSprites; - this.bushSprite = options.bushSprite; - this.bushSprites = options.bushSprites; - this.qblockSprite = options.qblockSprite; - - this.invincibility = options.invincibility; - this.statics = []; - this.scenery = []; - this.blocks = []; - this.enemies = []; - this.items = []; - this.pipes = []; - - for (var i = 0; i < 15; i++) { - this.statics[i] = []; - this.scenery[i] = []; - this.blocks[i] = []; - } - - }; - - Level.prototype.putFloor = function(start, end) { - for (var i = start; i < end; i++) { - this.statics[13][i] = new Mario.Floor([16*i,208], this.floorSprite); - this.statics[14][i] = new Mario.Floor([16*i,224], this.floorSprite); - } - }; - - Level.prototype.putGoomba = function(x, y) { - this.enemies.push(new Mario.Goomba([16*x, 16*y], this.goombaSprite() )); - }; - - Level.prototype.putKoopa = function(x, y) { - this.enemies.push(new Mario.Koopa([16*x, 16*y], this.koopaSprite(), false)); - }; - - Level.prototype.putWall = function(x, y, height) { - //y is the bottom of the wall in this case. - for (var i = y-height; i < y; i++) { - this.statics[i][x] = new Mario.Floor([16*x, 16*i], this.wallSprite); - } - }; - - Level.prototype.putPipe = function(x, y, height) { - for (var i = y - height; i < y; i++) { - if (i === y - height) { - this.statics[i][x] = new Mario.Floor([16*x, 16*i], this.pipeLEndSprite); - this.statics[i][x+1] = new Mario.Floor([16*x+16, 16*i], this.pipeREndSprite); - } else { - this.statics[i][x] = new Mario.Floor([16*x, 16*i], this.pipeLMidSprite); - this.statics[i][x+1] = new Mario.Floor([16*x+16, 16*i], this.pipeRMidSprite); - } - } - }; - - //sometimes, pipes don't go straight up and down. - Level.prototype.putLeftPipe = function(x,y) { - this.statics[y][x] = new Mario.Floor([16*x, 16*y], this.LPipeSprites[0]); - this.statics[y+1][x] = new Mario.Floor([16*x,16*(y+1)], this.LPipeSprites[1]); - this.statics[y][x+1] = new Mario.Floor([16*(x+1),16*y], this.LPipeSprites[2]); - this.statics[y+1][x+1] = new Mario.Floor([16*(x+1),16*(y+1)], this.LPipeSprites[3]); - this.statics[y][x+2] = new Mario.Floor([16*(x+2),16*y], this.LPipeSprites[4]); - this.statics[y+1][x+2] = new Mario.Floor([16*(x+2),16*(y+1)], this.LPipeSprites[5]); - }; - - Level.prototype.putCoin = function(x, y) { - this.items.push(new Mario.Coin( - [x*16, y*16], - this.coinSprite() - )); - }; - - Level.prototype.putCloud = function(x, y) { - this.scenery[y][x] = new Mario.Prop([x*16, y*16], this.cloudSprite); - }; - - Level.prototype.putQBlock = function(x, y, item) { - this.blocks[y][x] = new Mario.Block( { - pos: [x*16, y*16], - item: item, - sprite: this.qblockSprite, - usedSprite: this.ublockSprite - }); - }; - - Level.prototype.putBrick = function(x,y,item) { - this.blocks[y][x] = new Mario.Block({ - pos: [x*16, y*16], - item: item, - sprite: this.brickSprite, - bounceSprite: this.brickBounceSprite, - usedSprite: this.ublockSprite, - breakable: !item - }); - }; - - Level.prototype.putBigHill = function(x, y) { - var px = x*16, py = y*16; - this.scenery[y][x] = new Mario.Prop([px, py], this.hillSprites[0]); - this.scenery[y][x+1] = new Mario.Prop([px+16, py], this.hillSprites[3]); - this.scenery[y-1][x+1] = new Mario.Prop([px+16, py-16], this.hillSprites[0]); - this.scenery[y][x+2] = new Mario.Prop([px+32, py], this.hillSprites[4]); - this.scenery[y-1][x+2] = new Mario.Prop([px+32, py-16], this.hillSprites[3]); - this.scenery[y-2][x+2] = new Mario.Prop([px+32, py-32], this.hillSprites[1]); - this.scenery[y][x+3] = new Mario.Prop([px+48, py], this.hillSprites[5]); - this.scenery[y-1][x+3] = new Mario.Prop([px+48, py-16], this.hillSprites[2]); - this.scenery[y][x+4] = new Mario.Prop([px+64, py], this.hillSprites[2]); - }; - - Level.prototype.putBush = function(x, y) { - this.scenery[y][x] = new Mario.Prop([x*16, y*16], this.bushSprite); - }; - - Level.prototype.putThreeBush = function(x,y) { - px = x*16; - py = y*16; - this.scenery[y][x] = new Mario.Prop([px, py], this.bushSprites[0]); - this.scenery[y][x+1] = new Mario.Prop([px+16, py], this.bushSprites[1]); - this.scenery[y][x+2] = new Mario.Prop([px+32, py], this.bushSprites[1]); - this.scenery[y][x+3] = new Mario.Prop([px+48, py], this.bushSprites[1]); - this.scenery[y][x+4] = new Mario.Prop([px+64, py], this.bushSprites[2]); - }; - - Level.prototype.putTwoBush = function(x,y) { - px = x*16; - py = y*16; - this.scenery[y][x] = new Mario.Prop([px, py], this.bushSprites[0]); - this.scenery[y][x+1] = new Mario.Prop([px+16, py], this.bushSprites[1]); - this.scenery[y][x+2] = new Mario.Prop([px+32, py], this.bushSprites[1]); - this.scenery[y][x+3] = new Mario.Prop([px+48, py], this.bushSprites[2]); - }; - - Level.prototype.putSmallHill = function(x, y) { - var px = x*16, py = y*16; - this.scenery[y][x] = new Mario.Prop([px, py], this.hillSprites[0]); - this.scenery[y][x+1] = new Mario.Prop([px+16, py], this.hillSprites[3]); - this.scenery[y-1][x+1] = new Mario.Prop([px+16, py-16], this.hillSprites[1]); - this.scenery[y][x+2] = new Mario.Prop([px+32, py], this.hillSprites[2]); - }; - - Level.prototype.putTwoCloud = function(x,y) { - px = x*16; - py = y*16; - this.scenery[y][x] = new Mario.Prop([px, py], this.cloudSprites[0]); - this.scenery[y][x+1] = new Mario.Prop([px+16, py], this.cloudSprites[1]); - this.scenery[y][x+2] = new Mario.Prop([px+32, py], this.cloudSprites[1]); - this.scenery[y][x+3] = new Mario.Prop([px+48, py], this.cloudSprites[2]); - }; - - Level.prototype.putThreeCloud = function(x,y) { - px = x*16; - py = y*16; - this.scenery[y][x] = new Mario.Prop([px, py], this.cloudSprites[0]); - this.scenery[y][x+1] = new Mario.Prop([px+16, py], this.cloudSprites[1]); - this.scenery[y][x+2] = new Mario.Prop([px+32, py], this.cloudSprites[1]); - this.scenery[y][x+3] = new Mario.Prop([px+48, py], this.cloudSprites[1]); - this.scenery[y][x+4] = new Mario.Prop([px+64, py], this.cloudSprites[2]); - }; - - Level.prototype.putRealPipe = function(x, y, length, direction, destination) { - px = x*16; - py = y*16; - this.pipes.push(new Mario.Pipe({ - pos: [px, py], - length: length, - direction: direction, - destination: destination - })); - } - - Level.prototype.putFlagpole = function(x) { - this.statics[12][x] = new Mario.Floor([16*x, 192], this.wallSprite); - for (i=3; i < 12; i++) { - this.scenery[i][x] = new Mario.Prop([16*x, 16*i], this.flagpoleSprites[1]) - } - this.scenery[2][x] = new Mario.Prop([16*x, 32], this.flagpoleSprites[0]); - this.items.push(new Mario.Flag(16*x)); - } -})(); diff --git a/examples/mario/js/mushroom.js b/examples/mario/js/mushroom.js deleted file mode 100644 index 97e7233164c..00000000000 --- a/examples/mario/js/mushroom.js +++ /dev/null @@ -1,118 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Mushroom = Mario.Mushroom = function(pos) { - this.spawning = false; - this.waiting = 0; - - Mario.Entity.call(this, { - pos: pos, - sprite: level.superShroomSprite, - hitbox: [0,0,16,16] - }); - } - - Mario.Util.inherits(Mushroom, Mario.Entity); - - Mushroom.prototype.render = function(ctx, vX, vY) { - if (this.spawning > 1) return; - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY); - } - - Mushroom.prototype.spawn = function() { - if (player.power > 0) { - //replace this with a fire flower - var ff = new Mario.Fireflower(this.pos) - ff.spawn(); - return; - } - sounds.itemAppear.play(); - this.idx = level.items.length; - level.items.push(this); - this.spawning = 12; - this.targetpos = []; - this.targetpos[0] = this.pos[0]; - this.targetpos[1] = this.pos[1] - 16; - } - - Mushroom.prototype.update = function(dt) { - if (this.spawning > 1) { - this.spawning -= 1; - if (this.spawning == 1) this.vel[1] = -.5; - return; - } - if (this.spawning) { - if (this.pos[1] <= this.targetpos[1]) { - this.pos[1] = this.targetpos[1]; - this.vel[1] = 0; - this.waiting = 5; - this.spawning = 0; - this.vel[0] = 1; - } - } else { - this.acc[1] = 0.2; - } - - if (this.waiting) { - this.waiting -= 1; - } else { - this.vel[1] += this.acc[1]; - this.pos[0] += this.vel[0]; - this.pos[1] += this.vel[1]; - this.sprite.update(dt); - } - } - - Mushroom.prototype.collideWall = function() { - this.vel[0] = -this.vel[0]; - } - - Mushroom.prototype.checkCollisions = function() { - if(this.spawning) { - return; - } - var h = this.pos[1] % 16 == 0 ? 1 : 2; - var w = this.pos[0] % 16 == 0 ? 1 : 2; - - var baseX = Math.floor(this.pos[0] / 16); - var baseY = Math.floor(this.pos[1] / 16); - - if (baseY + h > 15) { - delete level.items[this.idx]; - return; - } - - for (var i = 0; i < h; i++) { - for (var j = 0; j < w; j++) { - if (level.statics[baseY + i][baseX + j]) { - level.statics[baseY + i][baseX + j].isCollideWith(this); - } - if (level.blocks[baseY + i][baseX + j]) { - level.blocks[baseY + i][baseX + j].isCollideWith(this); - } - } - } - - this.isPlayerCollided(); - } - - //we have access to player everywhere, so let's just do this. - Mushroom.prototype.isPlayerCollided = function() { - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [this.pos[0] + this.hitbox[0], this.pos[1] + this.hitbox[1]]; - var hpos2 = [player.pos[0] + player.hitbox[0], player.pos[1] + player.hitbox[1]]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+player.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+player.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - player.powerUp(this.idx); - } - } - } - - Mushroom.prototype.bump = function() { - this.vel[1] = -2; - } - -})(); diff --git a/examples/mario/js/outline.txt b/examples/mario/js/outline.txt deleted file mode 100644 index 346b1a7314f..00000000000 --- a/examples/mario/js/outline.txt +++ /dev/null @@ -1,45 +0,0 @@ -Enemy: - #collideWith - checks collision. Bounces off of walls and other enemies. Kills marios. - gets killed by block bonk from below - - Specific enemy behaviors: - koopas get replaced with shells - shells get kicked if touched from the side, instead of killing - -Mario: - #collideWith - gets expelled from walls, bonks blocks, destroys blocks as big Mario - note: collision with blocks is determined by which one is over the center - if you're slightly to the side, you slip past it. - Crazy-ass sprite shifting if you're in star mode! - - -Item - #collideWith - item pickup logic - -Mushroom - #update - movement logic for mushrooms - get impulse from being block bonked - this can be implemented by giving them the appropriate accel - just if they overlap a block from the bottom. - of course, only AFTER they finish sliding out of the block. - -Water levels: - make a separate class for water Marios - less gravity - swimming sprite - fireballs are the same - jump works when not on the ground - different enemies - - -TODO: Make level loader use hashes instead of arrays where possible. -Should be a free performance gain. - -Should also make item deletion less weird. - -TODO: Make gravity exist higher up instead of having a magic number. -Note from the future: Nope. Different objects have different gravity. diff --git a/examples/mario/js/pipe.js b/examples/mario/js/pipe.js deleted file mode 100644 index 8e1ab9063d3..00000000000 --- a/examples/mario/js/pipe.js +++ /dev/null @@ -1,160 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - - //there are too many possible configurations of pipe to capture in a reasonable - //set of simple variables. Joints, etc. are just too much. - //To that end, the pipe class handles simple pipes, and we'll put together - //anything more complex with individual props. OK? OK. - Pipe = Mario.Pipe = function(options) { - this.pos = options.pos - - //NOTE: direction is the direction you move INTO the pipe. - this.direction = options.direction - this.destination = options.destination - this.length = options.length; - - if (this.direction === "UP" || this.direction === "DOWN") { - this.hitbox = [0,0, 32, this.length * 16]; - this.midsection = level.pipeUpMid; - this.endsection = level.pipeTop; - } else { - this.hitbox = [0,0, 16*this.length, 32]; - this.midsection = level.pipeSideMid; - this.endsection = level.pipeLeft; - } - } - - Pipe.prototype.checkPipe = function() { - if (this.destination === undefined || !input.isDown(this.direction)) return; - - var h = player.power===0 ? 16 : 32; - var x = Math.floor(player.pos[0]); - var y = Math.floor(player.pos[1]); - switch (this.direction) { - case 'RIGHT': if (x === this.pos[0]-16 && - y >= this.pos[1] && - y+h <= this.pos[1]+32) { - player.pipe(this.direction, this.destination) - } - break; - case 'LEFT': if (x === this.pos[0]+16*this.length && - y >= this.pos[1] && - y+h <= this.pos[1]+32) { - player.pipe(this.direction, this.destination) - } - break; - case 'UP': if (y === this.pos[1] + 16*this.length && - x >= this.pos[0] && - x+16 <= this.pos[0]+32) { - player.pipe(this.direction, this.destination) - } - break; - case 'DOWN': if (y+h === this.pos[1] && - x >= this.pos[0] && - x+16 <= this.pos[0]+32) { - player.pipe(this.direction, this.destination); - } - break; - } - } - - //Note to self: next time, decide on a convention for which thing checks for collisions - //and stick to it. This is a pain. - Pipe.prototype.checkCollisions = function() { - var that = this; - level.enemies.forEach (function(ent) { - that.isCollideWith(ent); - }); - - level.items.forEach (function(ent) { - that.isCollideWith(ent); - }); - - fireballs.forEach(function(ent){ - that.isCollideWith(ent) - }); - - if (!player.piping) this.isCollideWith(player); - } - - Pipe.prototype.isCollideWith = function (ent) { - //long story short: because we scan every item, and and one 'rubble' item is four things with separate positions - //we'll crash without this line as soon as we destroy a block. OOPS. - if (ent.pos === undefined) return; - - - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [Math.floor(this.pos[0] + this.hitbox[0]), Math.floor(this.pos[1] + this.hitbox[1])]; - var hpos2 = [Math.floor(ent.pos[0] + ent.hitbox[0]), Math.floor(ent.pos[1] + ent.hitbox[1])]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+ent.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+ent.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - //if the entity is over the block, it's basically floor - var center = hpos2[0] + ent.hitbox[2] / 2; - if (Math.abs(hpos2[1] + ent.hitbox[3] - hpos1[1]) <= ent.vel[1]) { - ent.vel[1] = 0; - ent.pos[1] = hpos1[1] - ent.hitbox[3] - ent.hitbox[1]; - ent.standing = true; - if (ent instanceof Mario.Player) { - ent.jumping = 0; - } - } else if (Math.abs(hpos2[1] - hpos1[1] - this.hitbox[3]) > ent.vel[1] && - center + 2 >= hpos1[0] && center - 2 <= hpos1[0] + this.hitbox[2]) { - //ent is under the block. - ent.vel[1] = 0; - ent.pos[1] = hpos1[1] + this.hitbox[3]; - if (ent instanceof Mario.Player) { - ent.jumping = 0; - } - } else { - //entity is hitting it from the side, we're a wall - ent.collideWall(this); - } - } - } - } - - //we COULD try to write some shenanigans so that the check gets put into the - //collision code, but there won't ever be more than a handful of pipes in a level - //so the performance hit of scanning all of them is miniscule. - Pipe.prototype.update = function(dt) { - if (this.destination) this.checkPipe(); - } - - //http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array - //I honestly have no idea if javascript does this, but I feel like it makes sense - //stylistically to prefer branching outside of loops when possible as convention - - //TODO: edit the spritesheet so UP and LEFT pipes aren't backwards. - Pipe.prototype.render = function(ctx, vX, vY) { - switch (this.direction) { - case "DOWN": - this.endsection.render(ctx, this.pos[0], this.pos[1], vX, vY); - for (var i = 1; i < this.length; i++) { - this.midsection.render(ctx, this.pos[0], this.pos[1]+i*16, vX, vY) - } - break; - case "UP": - this.endsection.render(ctx, this.pos[0], this.pos[1]+16*(this.length-1), vX, vY) - for (var i=0; i < this.length - 1; i++) { - this.midsection.render(ctx, this.pos[0], this.pos[1]+i*16, vX, vY) - } - break; - case "RIGHT": - this.endsection.render(ctx, this.pos[0], this.pos[1], vX, vY) - for (var i = 1; i < this.length; i++) { - this.midsection.render(ctx, this.pos[0]+16*i, this.pos[1], vX, vY) - } - break; - case "LEFT": - this.endsection.render(ctx, this.pos[0]+16*(this.length-1), this.pos[1], vX, vY) - for (var i = 0; i < this.legth-1; i++) { - this.midsection.render(ctx, this.pos[0], this.pos[1]+i*16, vX, vY) - } - break; - } - } -})(); diff --git a/examples/mario/js/player.js b/examples/mario/js/player.js deleted file mode 100644 index b085de125bd..00000000000 --- a/examples/mario/js/player.js +++ /dev/null @@ -1,446 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Player = Mario.Player = function(pos) { - //I know, I know, there are a lot of variables tracking Mario's state. - //Maybe these can be consolidated some way? We'll see once they're all in. - this.power = 0; - this.coins = 0; - this.powering = []; - this.bounce = false; - this.jumping = 0; - this.canJump = true; - this.invincibility = 0; - this.crouching = false; - this.fireballs = 0; - this.runheld = false; - this.noInput = false; - this.targetPos = []; - - Mario.Entity.call(this, { - pos: pos, - sprite: new Mario.Sprite('sprites/player.png', [80,32],[16,16],0), - hitbox: [0,0,16,16] - }); - }; - - Mario.Util.inherits(Player, Mario.Entity); - - Player.prototype.run = function() { - this.maxSpeed = 2.5; - if (this.power == 2 && !this.runheld) { - this.shoot(); - } - this.runheld = true; - } - - Player.prototype.shoot = function() { - if (this.fireballs >= 2) return; //Projectile limit! - this.fireballs += 1; - var fb = new Mario.Fireball([this.pos[0]+8,this.pos[1]]); //I hate you, Javascript. - fb.spawn(this.left); - this.shooting = 2; - } - - Player.prototype.noRun = function() { - this.maxSpeed = 1.5; - this.moveAcc = 0.07; - this.runheld = false; - } - - Player.prototype.moveRight = function() { - //we're on the ground - if (this.vel[1] === 0 && this.standing) { - if (this.crouching) { - this.noWalk(); - return; - } - this.acc[0] = this.moveAcc; - this.left = false; - } else { - this.acc[0] = this.moveAcc; - } - }; - - Player.prototype.moveLeft = function() { - if (this.vel[1] === 0 && this.standing) { - if (this.crouching) { - this.noWalk(); - return; - } - this.acc[0] = -this.moveAcc; - this.left = true; - } else { - this.acc[0] = -this.moveAcc; - } - }; - - Player.prototype.noWalk = function() { - this.maxSpeed = 0; - if (this.vel[0] === 0) return; - - if (Math.abs(this.vel[0]) <= 0.1) { - this.vel[0] = 0; - this.acc[0] = 0; - } - - }; - - Player.prototype.crouch = function() { - if (this.power === 0) { - this.crouching = false; - return; - } - - if (this.standing) this.crouching = true; - } - - Player.prototype.noCrouch = function() { - this.crouching = false; - } - - Player.prototype.jump = function() { - if (this.vel[1] > 0) { - return; - } - if (this.jumping) { - this.jumping -= 1; - } else if (this.standing && this.canJump) { - this.jumping = 20; - this.canJump = false; - this.standing = false; - this.vel[1] = -6; - if (this.power === 0) { - sounds.smallJump.currentTime = 0; - sounds.smallJump.play(); - } else { - sounds.bigJump.currentTime = 0; - sounds.bigJump.play(); - } - } - }; - - Player.prototype.noJump = function() { - this.canJump = true; - if (this.jumping) { - if (this.jumping <= 16) { - this.vel[1] = 0; - this.jumping = 0; - } else this.jumping -= 1; - } - }; - - Player.prototype.setAnimation = function() { - if (this.dying) return; - - if (this.starTime) { - var index; - if (this.starTime > 60) - index = Math.floor(this.starTime / 2) % 3; - else index = Math.floor(this.starTime / 8) % 3; - - this.sprite.pos[1] = level.invincibility[index]; - if (this.power == 0) { - this.sprite.pos[1] += 32; - } - this.starTime -= 1; - if (this.starTime == 0) { - switch(this.power) { - case 0: this.sprite.pos[1] = 32; break; - case 1: this.sprite.pos[1] = 0; break; - case 2: this.sprite.pos[1] = 96; break; - } - } - } - //okay cool, now set the sprite - if (this.crouching) { - this.sprite.pos[0] = 176; - this.sprite.speed = 0; - return; - } - - if (this.jumping) { - this.sprite.pos[0] = 160; - this.sprite.speed = 0; - } else if (this.standing) { - if (Math.abs(this.vel[0]) > 0) { - if (this.vel[0] * this.acc[0] >= 0) { - this.sprite.pos[0] = 96; - this.sprite.frames = [0,1,2]; - if (this.vel[0] < 0.2) { - this.sprite.speed = 5; - } else { - this.sprite.speed = Math.abs(this.vel[0]) * 8; - } - } else if ((this.vel[0] > 0 && this.left) || (this.vel[0] < 0 && !this.left)){ - this.sprite.pos[0] = 144; - this.sprite.speed = 0; - } - } else { - this.sprite.pos[0] = 80; - this.sprite.speed = 0; - } - if (this.shooting) { - this.sprite.pos[0] += 160; - this.shooting -= 1; - } - } - - if (this.flagging) { - this.sprite.pos[0] = 192; - this.sprite.frames = [0,1]; - this.sprite.speed = 10; - if (this.vel[1] === 0) this.sprite.frames = [0]; - } - - //which way are we facing? - if (this.left) { - this.sprite.img = 'sprites/playerl.png'; - } else { - this.sprite.img = 'sprites/player.png'; - } - }; - - Player.prototype.update = function(dt, vX) { - if (this.powering.length !== 0) { - var next = this.powering.shift(); - if (next == 5) return; - this.sprite.pos = this.powerSprites[next]; - this.sprite.size = this.powerSizes[next]; - this.pos[1] += this.shift[next]; - if (this.powering.length === 0) { - delete level.items[this.touchedItem]; - } - return; - } - - if (this.invincibility) { - this.invincibility -= Math.round(dt * 60); - } - - if (this.waiting) { - this.waiting -= dt; - if (this.waiting <= 0) { - this.waiting = 0; - } else return; - } - - if (this.bounce) { - this.bounce = false; - this.standing = false; - this.vel[1] = -3; - } - - if (this.pos[0] <= vX) { - this.pos[0] = vX; - this.vel[0] = Math.max(this.vel[0], 0); - } - - if (Math.abs(this.vel[0]) > this.maxSpeed) { - this.vel[0] -= 0.05 * this.vel[0] / Math.abs(this.vel[0]); - this.acc[0] = 0; - } - - if (this.dying){ - if (this.pos[1] < this.targetPos[1]) { - this.vel[1] = 1; - } - this.dying -= 1 * dt; - if (this.dying <= 0) { - player = new Mario.Player(level.playerPos); - level.loader.call(); - input.reset(); - } - } - else { - this.acc[1] = 0.25 - if (this.pos[1] > 240) { - this.die(); - } - } - - if (this.piping) { - this.acc = [0,0]; - var pos = [Math.round(this.pos[0]), Math.round(this.pos[1])] - if (pos[0] === this.targetPos[0] && pos[1] === this.targetPos[1]) { - this.piping = false; - this.pipeLoc.call(); - } - } - - if (this.flagging) { - this.acc = [0,0]; - } - - if (this.exiting) { - this.left = false; - this.flagging = false; - this.vel[0] = 1.5; - if (this.pos[0] >= this.targetPos[0]) { - this.sprite.size = [0,0]; - this.vel = [0,0]; - window.setTimeout(function() { - player.sprite.size = player.power===0 ? [16,16] : [16,32]; - player.exiting = false; - player.noInput = false; - level.loader(); - if (player.power !== 0) player.pos[1] -= 16; - music.overworld.currentTime = 0; - }, 5000); - } - } - - //approximate acceleration - this.vel[0] += this.acc[0]; - this.vel[1] += this.acc[1]; - this.pos[0] += this.vel[0]; - this.pos[1] += this.vel[1]; - - this.setAnimation(); - this.sprite.update(dt); - }; - - Player.prototype.checkCollisions = function() { - if (this.piping || this.dying) return; - //x-axis first! - var h = this.power > 0 ? 2 : 1; - var w = 1; - if (this.pos[1] % 16 !== 0) { - h += 1; - } - if (this.pos[0] % 16 !== 0) { - w += 1; - } - var baseX = Math.floor(this.pos[0] / 16); - var baseY = Math.floor(this.pos[1] / 16); - - for (var i = 0; i < h; i++) { - if (baseY + i < 0 || baseY + i >= 15) continue; - for (var j = 0; j < w; j++) { - if (baseY < 0) { i++;} - if (level.statics[baseY + i][baseX + j]) { - level.statics[baseY + i][baseX + j].isCollideWith(this); - } - if (level.blocks[baseY + i][baseX + j]) { - level.blocks[baseY + i][baseX + j].isCollideWith(this); - } - } - } - }; - - Player.prototype.powerUp = function(idx) { - sounds.powerup.play(); - this.powering = [0,5,2,5,1,5,2,5,1,5,2,5,3,5,1,5,2,5,3,5,1,5,4]; - this.touchedItem = idx; - - if (this.power === 0) { - this.sprite.pos[0] = 80; - var newy = this.sprite.pos[1] - 32; - this.powerSprites = [[80, newy+32], [80, newy+32], [320, newy], [80, newy], [128, newy]]; - this.powerSizes = [[16,16],[16,16],[16,32],[16,32],[16,32]]; - this.shift = [0,16,-16,0,-16]; - this.power = 1; - this.hitbox = [0,0,16,32]; - } else if (this.power == 1) { - var curx = this.sprite.pos[0]; - this.powerSprites = [[curx, 96], [curx, level.invincibility[0]], - [curx, level.invincibility[1]], [curx, level.invincibility[2]], - [curx, 96]]; - this.powerSizes[[16,32],[16,32],[16,32],[16,32],[16,32]]; - this.shift = [0,0,0,0,0]; - this.power = 2; - } else { - this.powering = []; - delete level.items[idx]; - //no animation, but we play the sound and you get 5000 points. - } - }; - - Player.prototype.damage = function() { - if (this.power === 0) { //if you're already small, you dead! - this.die(); - } else { //otherwise, you get turned into small mario - sounds.pipe.play(); - this.powering = [0,5,1,5,2,5,1,5,2,5,1,5,2,5,1,5,2,5,1,5,2,5,3]; - this.shift = [0,16,-16,16]; - this.sprite.pos = [160, 0]; - this.powerSprites = [[160,0], [240, 32], [240, 0], [160, 32]]; - this.powerSizes = [[16, 32], [16,16], [16,32], [16,16]]; - this.invincibility = 120; - this.power = 0; - this.hitbox = [0,0,16,16]; - } - }; - - Player.prototype.die = function () { - //TODO: rewrite the way sounds work to emulate the channels of an NES. - music.overworld.pause(); - music.underground.pause(); - music.overworld.currentTime = 0; - music.death.play(); - this.noWalk(); - this.noRun(); - this.noJump(); - - this.acc[0] = 0; - this.sprite.pos = [176, 32]; - this.sprite.speed = 0; - this.power = 0; - this.waiting = 0.5; - this.dying = 2; - - if (this.pos[1] < 240) { //falling into a pit doesn't do the animation. - this.targetPos = [this.pos[0], this.pos[1]-128]; - this.vel = [0,-5]; - } else { - this.vel = [0,0]; - this.targetPos = [this.pos[0], this.pos[1] - 16]; - } - }; - - Player.prototype.star = function(idx) { - delete level.items[idx]; - this.starTime = 660; - } - - Player.prototype.pipe = function(direction, destination) { - sounds.pipe.play(); - this.piping = true; - this.pipeLoc = destination; - switch(direction) { - case "LEFT": - this.vel = [-1,0]; - this.targetPos = [Math.round(this.pos[0]-16), Math.round(this.pos[1])] - break; - case "RIGHT": - this.vel = [1,0]; - this.targetPos = [Math.round(this.pos[0]+16), Math.round(this.pos[1])] - break; - case "DOWN": - this.vel = [0,1]; - this.targetPos = [Math.round(this.pos[0]), Math.round(this.pos[1]+this.hitbox[3])] - break; - case "UP": - this.vel = [0,-1]; - this.targetPos = [Math.round(this.pos[0]), Math.round(this.pos[1]-this.hitbox[3])] - break; - } - } - - Player.prototype.flag = function() { - this.noInput = true; - this.flagging = true; - this.vel = [0, 2]; - this.acc = [0, 0]; - } - - Player.prototype.exit = function() { - this.pos[0] += 16; - this.targetPos[0] = level.exit * 16; - this.left = true; - this.setAnimation(); - this.waiting = 1; - this.exiting = true; - } -})(); diff --git a/examples/mario/js/prop.js b/examples/mario/js/prop.js deleted file mode 100644 index 8ab2b6c903b..00000000000 --- a/examples/mario/js/prop.js +++ /dev/null @@ -1,15 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - //props do even less than entities, so they don't need to inherit really - var Prop = Mario.Prop = function(pos, sprite) { - this.pos = pos; - this.sprite = sprite; - } - - //but we will be using the same Render, more or less. - Prop.prototype.render = function(ctx, vX, vY) { - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY); - } -})(); diff --git a/examples/mario/js/resources.js b/examples/mario/js/resources.js deleted file mode 100644 index c3add6d28f0..00000000000 --- a/examples/mario/js/resources.js +++ /dev/null @@ -1,62 +0,0 @@ -//simple resource loader -(function() { - var resourceCache = {}; - var loading = []; - var readyCallbacks = []; - - // Load an image url or an array of image urls - function load(urlOrArr) { - if(urlOrArr instanceof Array) { - urlOrArr.forEach(function(url) { - _load(url); - }); - } - else { - _load(urlOrArr); - } - } - - function _load(url) { - if(resourceCache[url]) { - return resourceCache[url]; - } - else { - var img = new Image(); - img.onload = function() { - resourceCache[url] = img; - - if(isReady()) { - readyCallbacks.forEach(function(func) { func(); }); - } - }; - resourceCache[url] = false; - img.src = url; - } - } - - function get(url) { - return resourceCache[url]; - } - - function isReady() { - var ready = true; - for(var k in resourceCache) { - if(resourceCache.hasOwnProperty(k) && - !resourceCache[k]) { - ready = false; - } - } - return ready; - } - - function onReady(func) { - readyCallbacks.push(func); - } - - window.resources = { - load: load, - get: get, - onReady: onReady, - isReady: isReady - }; -})(); diff --git a/examples/mario/js/rubble.js b/examples/mario/js/rubble.js deleted file mode 100644 index 98f6e89d433..00000000000 --- a/examples/mario/js/rubble.js +++ /dev/null @@ -1,55 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - //TODO: make each rubble an entity, use that render and write in Entity.update - var Rubble = Mario.Rubble = function() { - this.sprites = []; - this.poss = []; - this.vels = []; - } - - Rubble.prototype.spawn = function(pos) { - this.idx = level.items.length; - level.items.push(this); - this.sprites[0] = level.rubbleSprite(); - this.sprites[1] = level.rubbleSprite(); - this.sprites[2] = level.rubbleSprite(); - this.sprites[3] = level.rubbleSprite(); - this.poss[0] = pos; - this.poss[1] = [ pos[0] + 8, pos[1] ]; - this.poss[2] = [ pos[0], pos[1] + 8 ]; - this.poss[3] = [ pos[0] + 8, pos[1] + 8 ]; - this.vels[0] = [-1.25, -5]; - this.vels[1] = [1.25, -5]; - this.vels[2] = [-1.25, -3]; - this.vels[3] = [1.25, -3]; - } - - Rubble.prototype.update = function(dt) { - for(var i = 0; i < 4; i++) { - if (this.sprites[i]===undefined) continue; - this.vels[i][1] += .3; - this.poss[i][0] += this.vels[i][0]; - this.poss[i][1] += this.vels[i][1]; - this.sprites[i].update(dt); - if (this.poss[i][1] > 256) { - delete this.sprites[i]; - } - } - if (this.sprites.every(function (el) {return !el})) { - delete level.items[this.idx]; - } - } - - //You might argue that things that can't collide are more like scenery - //but these move and need to be deleted, and i'd rather deal with the 1d array. - Rubble.prototype.checkCollisions = function() {;} - - Rubble.prototype.render = function() { - for(var i = 0; i < 4; i++) { - if (this.sprites[i] === undefined) continue; - this.sprites[i].render(ctx, this.poss[i][0], this.poss[i][1], vX, vY); - } - } -})(); diff --git a/examples/mario/js/sprite.js b/examples/mario/js/sprite.js deleted file mode 100644 index 94b8d6c00cd..00000000000 --- a/examples/mario/js/sprite.js +++ /dev/null @@ -1,47 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Sprite = Mario.Sprite = function(img, pos, size, speed, frames, once) { - this.pos = pos; - this.size = size; - this.speed = speed; - this._index = 0; - this.img = img; - this.once = once; - this.frames = frames; - } - - Sprite.prototype.update = function(dt, gameTime) { - if (gameTime && gameTime == this.lastUpdated) return; - this._index += this.speed*dt; - if (gameTime) this.lastUpdated = gameTime; - } - - Sprite.prototype.setFrame = function(frame) { - this._index = frame; - } - - Sprite.prototype.render = function(ctx, posx, posy, vX, vY) { - var frame; - - if (this.speed > 0) { - var max = this.frames.length; - var idx = Math.floor(this._index); - frame = this.frames[idx % max]; - - if (this.once && idx >= max) { - this.done = true; - return; - } - } else { - frame = 0; - } - - var x = this.pos[0]; - var y = this.pos[1]; - - x += frame*this.size[0]; - ctx.drawImage(resources.get(this.img), x + (1/3),y + (1/3), this.size[0] - (2/3), this.size[1] - (2/3), Math.round(posx - vX), Math.round(posy - vY), this.size[0],this.size[1]); - } -})(); diff --git a/examples/mario/js/star.js b/examples/mario/js/star.js deleted file mode 100644 index dc27b1dc2f0..00000000000 --- a/examples/mario/js/star.js +++ /dev/null @@ -1,116 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') - window.Mario = {}; - - var Star = Mario.Star = function(pos) { - this.spawning = false; - this.waiting = 0; - - Mario.Entity.call(this, { - pos: pos, - sprite: level.starSprite, - hitbox: [0,0,16,16] - }); - } - - Mario.Util.inherits(Star, Mario.Entity); - - Star.prototype.render = function(ctx, vX, vY) { - if (this.spawning > 1) return; - this.sprite.render(ctx, this.pos[0], this.pos[1], vX, vY); - } - - Star.prototype.spawn = function() { - this.idx = level.items.length; - level.items.push(this); - this.spawning = 12; - this.targetpos = []; - this.targetpos[0] = this.pos[0]; - this.targetpos[1] = this.pos[1] - 16; - } - - Star.prototype.update = function(dt) { - if (this.spawning > 1) { - this.spawning -= 1; - if (this.spawning == 1) this.vel[1] = -.5; - return; - } - if (this.spawning) { - if (this.pos[1] <= this.targetpos[1]) { - this.pos[1] = this.targetpos[1]; - this.vel[1] = 0; - this.waiting = 5; - this.spawning = 0; - this.vel[0] = 1; - } - } else { - this.acc[1] = 0.2; - } - - if (this.standing) { - this.standing = false; - this.vel[1] = -3; - } - - if (this.waiting) { - this.waiting -= 1; - } else { - this.vel[1] += this.acc[1]; - this.pos[0] += this.vel[0]; - this.pos[1] += this.vel[1]; - this.sprite.update(dt); - } - } - - Star.prototype.collideWall = function() { - this.vel[0] = -this.vel[0]; - } - - Star.prototype.checkCollisions = function() { - if(this.spawning) { - return; - } - var h = this.pos[1] % 16 == 0 ? 1 : 2; - var w = this.pos[0] % 16 == 0 ? 1 : 2; - - var baseX = Math.floor(this.pos[0] / 16); - var baseY = Math.floor(this.pos[1] / 16); - - if (baseY + h > 15) { - delete level.items[this.idx]; - return; - } - - for (var i = 0; i < h; i++) { - for (var j = 0; j < w; j++) { - if (level.statics[baseY + i][baseX + j]) { - level.statics[baseY + i][baseX + j].isCollideWith(this); - } - if (level.blocks[baseY + i][baseX + j]) { - level.blocks[baseY + i][baseX + j].isCollideWith(this); - } - } - } - - this.isPlayerCollided(); - } - - //we have access to player everywhere, so let's just do this. - Star.prototype.isPlayerCollided = function() { - //the first two elements of the hitbox array are an offset, so let's do this now. - var hpos1 = [this.pos[0] + this.hitbox[0], this.pos[1] + this.hitbox[1]]; - var hpos2 = [player.pos[0] + player.hitbox[0], player.pos[1] + player.hitbox[1]]; - - //if the hitboxes actually overlap - if (!(hpos1[0] > hpos2[0]+player.hitbox[2] || (hpos1[0]+this.hitbox[2] < hpos2[0]))) { - if (!(hpos1[1] > hpos2[1]+player.hitbox[3] || (hpos1[1]+this.hitbox[3] < hpos2[1]))) { - player.star(this.idx); - } - } - } - - Star.prototype.bump = function() { - this.vel[1] = -2; - } - -})(); diff --git a/examples/mario/js/util.js b/examples/mario/js/util.js deleted file mode 100644 index f9aee3cabc0..00000000000 --- a/examples/mario/js/util.js +++ /dev/null @@ -1,14 +0,0 @@ -(function() { - if (typeof Mario === 'undefined') { - window.Mario = {}; - } - - var Util = Mario.Util = {}; - - Util.inherits = function(subclass, superclass) { - function Surrogate() {}; - - Surrogate.prototype = superclass.prototype; - subclass.prototype = new Surrogate(); - } -})() diff --git a/examples/mario/play_mario.html b/examples/mario/play_mario.html deleted file mode 100644 index a7472c9086e..00000000000 --- a/examples/mario/play_mario.html +++ /dev/null @@ -1,144 +0,0 @@ - - - - - - - Svelte app - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -from js import handTrack, setTimeout, requestAnimationFrame, player -from pyodide import create_once_callable -import asyncio - -context = canvas.element.getContext("2d") - -isVideo = False -model = None -last_position = 0 -direction = "stop" - -modelParams = { - "flipHorizontal": True, # flip e.g for video - "maxNumBoxes": 20, # maximum number of boxes to detect - "iouThreshold": 0.5, # ioU threshold for non-max suppression - "scoreThreshold": 0.6, # confidence threshold for predictions. -} - -def toggle_video(evt): - global isVideo - player.jump() - - if (not isVideo): - update_note.write("Starting video") - pyscript.run_until_complete(start_video()) - else: - update_note.write("Stopping video") - handTrack.stopVideo(video.element) - isVideo = False - update_note.write("Video stopped") - -async def start_video(): - global isVideo - update_note.write("Inside sstart video") - status = await handTrack.startVideo(video.element) - console.log("video started", status) - if status: - update_note.write("Video started. Now tracking") - isVideo = True - console.log( "Calling RUN DETECTION") - y = await run_detection() - else: - update_note.write( "Please enable video") - -def sync_run_detection(evt): - pyscript.run_until_complete(run_detection()) - -async def run_detection(): - global model - global isVideo - global last_position - global direction - - predictions = await model.detect(video.element) - model.renderPredictions(predictions, canvas.element, context, video.element); - - if predictions: - curr_position = predictions[0].bbox[0] + (predictions[0].bbox[2] / 2) - delta = last_position - curr_position - last_position = curr_position - #console.log(delta, curr_position, last_position) - if abs(delta) < 2: - direction = "stop" - elif delta > 0: - direction = "left" - else: - direction = "right" - - for prediction in predictions: - if prediction.label == 'open': - player.jump() - elif prediction.label == 'close': - player.crouch() - - if (isVideo): - await requestAnimationFrame(create_once_callable(sync_run_detection)); - -def handle_model(lmodel): - global model - model = lmodel - update_note.write("Loaded Model!") - -async def start(): - model = await handTrack.load(modelParams)#.then(handle_model) - handle_model(model) - -pyscript.run_until_complete(start()) - - - -
-

Use < > to move, ↓ to crouch and x to jump. If video is enabled, say hi to jump as well!

- -
loading model ..
-
-
- - -
- - diff --git a/examples/mario/sounds/aboveground_bgm.ogg b/examples/mario/sounds/aboveground_bgm.ogg deleted file mode 100644 index 4920b63ea76..00000000000 Binary files a/examples/mario/sounds/aboveground_bgm.ogg and /dev/null differ diff --git a/examples/mario/sounds/breakblock.wav b/examples/mario/sounds/breakblock.wav deleted file mode 100644 index 0c7b3c9a44d..00000000000 Binary files a/examples/mario/sounds/breakblock.wav and /dev/null differ diff --git a/examples/mario/sounds/bump.wav b/examples/mario/sounds/bump.wav deleted file mode 100644 index 246bcee1c3d..00000000000 Binary files a/examples/mario/sounds/bump.wav and /dev/null differ diff --git a/examples/mario/sounds/coin.wav b/examples/mario/sounds/coin.wav deleted file mode 100644 index fef4191944b..00000000000 Binary files a/examples/mario/sounds/coin.wav and /dev/null differ diff --git a/examples/mario/sounds/fireball.wav b/examples/mario/sounds/fireball.wav deleted file mode 100644 index 56ed57f83c5..00000000000 Binary files a/examples/mario/sounds/fireball.wav and /dev/null differ diff --git a/examples/mario/sounds/flagpole.wav b/examples/mario/sounds/flagpole.wav deleted file mode 100644 index 10640ace15a..00000000000 Binary files a/examples/mario/sounds/flagpole.wav and /dev/null differ diff --git a/examples/mario/sounds/itemAppear.wav b/examples/mario/sounds/itemAppear.wav deleted file mode 100644 index 1ab578d9969..00000000000 Binary files a/examples/mario/sounds/itemAppear.wav and /dev/null differ diff --git a/examples/mario/sounds/jump-small.wav b/examples/mario/sounds/jump-small.wav deleted file mode 100644 index 6883fdac979..00000000000 Binary files a/examples/mario/sounds/jump-small.wav and /dev/null differ diff --git a/examples/mario/sounds/jump-super.wav b/examples/mario/sounds/jump-super.wav deleted file mode 100644 index 0d94118912d..00000000000 Binary files a/examples/mario/sounds/jump-super.wav and /dev/null differ diff --git a/examples/mario/sounds/kick.wav b/examples/mario/sounds/kick.wav deleted file mode 100644 index 14cc8273408..00000000000 Binary files a/examples/mario/sounds/kick.wav and /dev/null differ diff --git a/examples/mario/sounds/mariodie.wav b/examples/mario/sounds/mariodie.wav deleted file mode 100644 index bd3400f88b4..00000000000 Binary files a/examples/mario/sounds/mariodie.wav and /dev/null differ diff --git a/examples/mario/sounds/pipe.wav b/examples/mario/sounds/pipe.wav deleted file mode 100644 index bbeec364d41..00000000000 Binary files a/examples/mario/sounds/pipe.wav and /dev/null differ diff --git a/examples/mario/sounds/powerup.wav b/examples/mario/sounds/powerup.wav deleted file mode 100644 index d0857839fba..00000000000 Binary files a/examples/mario/sounds/powerup.wav and /dev/null differ diff --git a/examples/mario/sounds/stage_clear.wav b/examples/mario/sounds/stage_clear.wav deleted file mode 100644 index 6c396ded172..00000000000 Binary files a/examples/mario/sounds/stage_clear.wav and /dev/null differ diff --git a/examples/mario/sounds/stomp.wav b/examples/mario/sounds/stomp.wav deleted file mode 100644 index 00ac6c9d6cf..00000000000 Binary files a/examples/mario/sounds/stomp.wav and /dev/null differ diff --git a/examples/mario/sounds/underground_bgm.ogg b/examples/mario/sounds/underground_bgm.ogg deleted file mode 100644 index 64f67efdf5c..00000000000 Binary files a/examples/mario/sounds/underground_bgm.ogg and /dev/null differ diff --git a/examples/mario/sprites/1-1 reference.png b/examples/mario/sprites/1-1 reference.png deleted file mode 100644 index b25d46475a0..00000000000 Binary files a/examples/mario/sprites/1-1 reference.png and /dev/null differ diff --git a/examples/mario/sprites/enemy.png b/examples/mario/sprites/enemy.png deleted file mode 100644 index 4ddd3f0ee94..00000000000 Binary files a/examples/mario/sprites/enemy.png and /dev/null differ diff --git a/examples/mario/sprites/enemyr.png b/examples/mario/sprites/enemyr.png deleted file mode 100644 index 5122f90a5e2..00000000000 Binary files a/examples/mario/sprites/enemyr.png and /dev/null differ diff --git a/examples/mario/sprites/items.png b/examples/mario/sprites/items.png deleted file mode 100644 index 387219d796a..00000000000 Binary files a/examples/mario/sprites/items.png and /dev/null differ diff --git a/examples/mario/sprites/player.png b/examples/mario/sprites/player.png deleted file mode 100644 index b8ee73950d6..00000000000 Binary files a/examples/mario/sprites/player.png and /dev/null differ diff --git a/examples/mario/sprites/playerl.png b/examples/mario/sprites/playerl.png deleted file mode 100644 index 077b502cbbc..00000000000 Binary files a/examples/mario/sprites/playerl.png and /dev/null differ diff --git a/examples/mario/sprites/tiles.png b/examples/mario/sprites/tiles.png deleted file mode 100644 index 31d7a8f9a14..00000000000 Binary files a/examples/mario/sprites/tiles.png and /dev/null differ diff --git a/examples/matplotlib.html b/examples/matplotlib.html deleted file mode 100644 index fe543693f3a..00000000000 --- a/examples/matplotlib.html +++ /dev/null @@ -1,50 +0,0 @@ - - - Matplotlib - - - - - - - matplotlib - - - -
- -import matplotlib.pyplot as plt -import matplotlib.tri as tri -import numpy as np - -# First create the x and y coordinates of the points. -n_angles = 36 -n_radii = 8 -min_radius = 0.25 -radii = np.linspace(min_radius, 0.95, n_radii) - -angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) -angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) -angles[:, 1::2] += np.pi / n_angles - -x = (radii * np.cos(angles)).flatten() -y = (radii * np.sin(angles)).flatten() -z = (np.cos(radii) * np.cos(3 * angles)).flatten() - -# Create the Triangulation; no triangles so Delaunay triangulation created. -triang = tri.Triangulation(x, y) - -# Mask off unwanted triangles. -triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), - y[triang.triangles].mean(axis=1)) - < min_radius) - -fig1, ax1 = plt.subplots() -ax1.set_aspect('equal') -tpc = ax1.tripcolor(triang, z, shading='flat') -fig1.colorbar(tpc) -ax1.set_title('tripcolor of Delaunay triangulation, flat shading') - -fig1 - - - diff --git a/examples/message_passing.html b/examples/message_passing.html deleted file mode 100644 index ee10a74a0fc..00000000000 --- a/examples/message_passing.html +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - numpy - - networkx - - matplotlib - - -import numpy as np -import networkx as nx - - -

Message passing with linear algebra: a demo.

-

Imagine we have a chain graph that looks like this:

-
O --> 1 --> 2 --> 3
-

In NetworkX this graph would look like the following:

-
-        
-G = nx.Graph()
-nodes = list(range(4))
-G.add_edges_from(zip(nodes[0:-1], nodes[1:]))
-print(G.edges())
-
-

This chain graph has the following adjacency matrix:

-
-
-adj_mat = np.eye(4, k=1)
-print(f"A: {adj_mat}")
-
-        
-

And imagine that we have a message that lives on the graph:

-
-            
-message = np.array([1.0, 0.0, 0.0, 0.0])
-print(f"message: {message}")
-            
-        
-

Try out message passing below by doing any one of the following steps:

-
message @ adj_mat
-
message @ adj_mat @ adj_mat
-
message @ adj_mat @ adj_mat @ adj_mat
-
- -
- - - diff --git a/examples/micrograd_ai.html b/examples/micrograd_ai.html deleted file mode 100644 index bbf4546ca2a..00000000000 --- a/examples/micrograd_ai.html +++ /dev/null @@ -1,192 +0,0 @@ - - - - - - - micrograd - - - - - - - micrograd - - numpy - - matplotlib - - - - - - -

Micrograd - A tiny Autograd engine (with a bite! :))


-
-

- Micrograd is a tiny Autograd engine created - by Andrej Karpathy. This app recreates the - demo - he prepared for this package using pyscript to train a basic model, written in Python, natively in - the browser.
-

-
-
-

- You may run each Python REPL cell interactively by pressing (Shift + Enter) or (Ctrl + Enter). - You can also modify the code directly as you wish. If you want to run all the code at once, - not each cell individually, you may instead click the 'Run All' button. Training the model - takes between 1-2 min if you decide to 'Run All' at once. 'Run All' is your only option if - you are running this on a mobile device where you cannot press (Shift + Enter). After the - model is trained, a plot image should be displayed depicting the model's ability to - classify the data.
-

-

- Currently the > symbol is being imported incorrectly as &gt; into the REPL's. - In this app the > symbol has been replaced with ().__gt__() so you can run the code - without issue. Ex: instead of a > b, you will see (a).__gt__(b) instead.
-

-

- import js; js.document.getElementById('python-status').innerHTML = 'Python is now ready. You may proceed.' -

Python is currently starting. Please wait...
-

-

-
- -


-
-

-

-
- -import random -import numpy as np -import matplotlib.pyplot as plt -
- -from micrograd.engine import Value -from micrograd.nn import Neuron, Layer, MLP -
- -np.random.seed(1337) -random.seed(1337) -
- -#An adaptation of sklearn's make_moons function https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html -def make_moons(n_samples=100, noise=None): - n_samples_out, n_samples_in = n_samples, n_samples - - outer_circ_x = np.cos(np.linspace(0, np.pi, n_samples_out)) - outer_circ_y = np.sin(np.linspace(0, np.pi, n_samples_out)) - inner_circ_x = 1 - np.cos(np.linspace(0, np.pi, n_samples_in)) - inner_circ_y = 1 - np.sin(np.linspace(0, np.pi, n_samples_in)) - 0.5 - - X = np.vstack([np.append(outer_circ_x, inner_circ_x), np.append(outer_circ_y, inner_circ_y)]).T - y = np.hstack([np.zeros(n_samples_out, dtype=np.intp), np.ones(n_samples_in, dtype=np.intp)]) - if noise is not None: X += np.random.normal(loc=0.0, scale=noise, size=X.shape) - return X, y -X, y = make_moons(n_samples=100, noise=0.1) -
- -y = y*2 - 1 # make y be -1 or 1 -# visualize in 2D -plt.figure(figsize=(5,5)) -plt.scatter(X[:,0], X[:,1], c=y, s=20, cmap='jet') -plt -
- -model = MLP(2, [16, 16, 1]) # 2-layer neural network -print(model) -print("number of parameters", len(model.parameters())) -
- -
- Line 24 has been changed from:
- accuracy = [(yi > 0) == (scorei.data > 0) for yi, scorei in zip(yb, scores)]
- to:
- accuracy = [((yi).__gt__(0)) == ((scorei.data).__gt__(0)) for yi, scorei in zip(yb, scores)]
-
- - -# loss function -def loss(batch_size=None): - - # inline DataLoader :) - if batch_size is None: - Xb, yb = X, y - else: - ri = np.random.permutation(X.shape[0])[:batch_size] - Xb, yb = X[ri], y[ri] - inputs = [list(map(Value, xrow)) for xrow in Xb] - - # forward the model to get scores - scores = list(map(model, inputs)) - - # svm "max-margin" loss - losses = [(1 + -yi*scorei).relu() for yi, scorei in zip(yb, scores)] - data_loss = sum(losses) * (1.0 / len(losses)) - # L2 regularization - alpha = 1e-4 - reg_loss = alpha * sum((p*p for p in model.parameters())) - total_loss = data_loss + reg_loss - - # also get accuracy - accuracy = [((yi).__gt__(0)) == ((scorei.data).__gt__(0)) for yi, scorei in zip(yb, scores)] - return total_loss, sum(accuracy) / len(accuracy) - -total_loss, acc = loss() -print(total_loss, acc) -
- -# optimization -for k in range(20): #was 100. Accuracy can be further improved w/ more epochs (to 100%). - - # forward - total_loss, acc = loss() - - # backward - model.zero_grad() - total_loss.backward() - - # update (sgd) - learning_rate = 1.0 - 0.9*k/100 - for p in model.parameters(): - p.data -= learning_rate * p.grad - - if k % 1 == 0: - print(f"step {k} loss {total_loss.data}, accuracy {acc*100}%") -
-
-

- Please wait for the training loop above to complete. It will not print out stats until it - has completely finished. This typically takes 1-2 min.

- - Line 9 has been changed from:
- Z = np.array([s.data > 0 for s in scores])
- to:
- Z = np.array([(s.data).__gt__(0) for s in scores])
-

-
- -h = 0.25 -x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 -y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 -xx, yy = np.meshgrid(np.arange(x_min, x_max, h), - np.arange(y_min, y_max, h)) -Xmesh = np.c_[xx.ravel(), yy.ravel()] -inputs = [list(map(Value, xrow)) for xrow in Xmesh] -scores = list(map(model, inputs)) -Z = np.array([(s.data).__gt__(0) for s in scores]) -Z = Z.reshape(xx.shape) - -fig = plt.figure() -plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8) -plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral) -plt.xlim(xx.min(), xx.max()) -plt.ylim(yy.min(), yy.max()) -plt -
- -1+1 -
- - - diff --git a/examples/micrograd_ai.py b/examples/micrograd_ai.py deleted file mode 100644 index 4cfd712f8eb..00000000000 --- a/examples/micrograd_ai.py +++ /dev/null @@ -1,160 +0,0 @@ -# Credit: https://github.com/karpathy/micrograd/blob/master/demo.ipynb -# cell -import datetime -import random - -import matplotlib.pyplot as plt -import numpy as np - -# cell -from micrograd.engine import Value -from micrograd.nn import MLP - -print_statements = [] - - -def run_all_micrograd_demo(*args, **kwargs): - result = micrograd_demo() - pyscript.write("micrograd-run-all-fig2-div", result) - - -def print_div(o): - o = str(o) - print_statements.append(o + " \n
") - pyscript.write("micrograd-run-all-print-div", "".join(print_statements)) - - -# All code is wrapped in this run_all function so it optionally executed (called) -# from pyscript when a button is pressed. -def micrograd_demo(*args, **kwargs): - """ - Runs the micrograd demo. - - *args and **kwargs do nothing and are only there to capture any parameters passed - from pyscript when this function is called when a button is clicked. - """ - - # cell - start = datetime.datetime.now() - print_div("Starting...") - - # cell - np.random.seed(1337) - random.seed(1337) - - # cell - # An adaptation of sklearn's make_moons function - # https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html - def make_moons(n_samples=100, noise=None): - n_samples_out, n_samples_in = n_samples, n_samples - - outer_circ_x = np.cos(np.linspace(0, np.pi, n_samples_out)) - outer_circ_y = np.sin(np.linspace(0, np.pi, n_samples_out)) - inner_circ_x = 1 - np.cos(np.linspace(0, np.pi, n_samples_in)) - inner_circ_y = 1 - np.sin(np.linspace(0, np.pi, n_samples_in)) - 0.5 - - X = np.vstack( - [ - np.append(outer_circ_x, inner_circ_x), - np.append(outer_circ_y, inner_circ_y), - ] - ).T - y = np.hstack( - [ - np.zeros(n_samples_out, dtype=np.intp), - np.ones(n_samples_in, dtype=np.intp), - ] - ) - if noise is not None: - X += np.random.normal(loc=0.0, scale=noise, size=X.shape) - return X, y - - X, y = make_moons(n_samples=100, noise=0.1) - - # cell - y = y * 2 - 1 # make y be -1 or 1 - # visualize in 2D - plt.figure(figsize=(5, 5)) - plt.scatter(X[:, 0], X[:, 1], c=y, s=20, cmap="jet") - plt - pyscript.write("micrograd-run-all-fig1-div", plt) - - # cell - model = MLP(2, [16, 16, 1]) # 2-layer neural network - print_div(model) - print_div(("number of parameters", len(model.parameters()))) - - # cell - # loss function - def loss(batch_size=None): - # inline DataLoader :) - if batch_size is None: - Xb, yb = X, y - else: - ri = np.random.permutation(X.shape[0])[:batch_size] - Xb, yb = X[ri], y[ri] - inputs = [list(map(Value, xrow)) for xrow in Xb] - - # forward the model to get scores - scores = list(map(model, inputs)) - - # svm "max-margin" loss - losses = [(1 + -yi * scorei).relu() for yi, scorei in zip(yb, scores)] - data_loss = sum(losses) * (1.0 / len(losses)) - # L2 regularization - alpha = 1e-4 - reg_loss = alpha * sum(p * p for p in model.parameters()) - total_loss = data_loss + reg_loss - - # also get accuracy - accuracy = [ - ((yi).__gt__(0)) == ((scorei.data).__gt__(0)) - for yi, scorei in zip(yb, scores) - ] - return total_loss, sum(accuracy) / len(accuracy) - - total_loss, acc = loss() - print((total_loss, acc)) - - # cell - # optimization - for k in range(20): # was 100 - - # forward - total_loss, _ = loss() - - # backward - model.zero_grad() - total_loss.backward() - - # update (sgd) - learning_rate = 1.0 - 0.9 * k / 100 - for p in model.parameters(): - p.data -= learning_rate * p.grad - - if k % 1 == 0: - # print(f"step {k} loss {total_loss.data}, accuracy {acc*100}%") - print_div(f"step {k} loss {total_loss.data}, accuracy {acc*100}%") - - # cell - h = 0.25 - x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 - y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 - xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) - Xmesh = np.c_[xx.ravel(), yy.ravel()] - inputs = [list(map(Value, xrow)) for xrow in Xmesh] - scores = list(map(model, inputs)) - Z = np.array([(s.data).__gt__(0) for s in scores]) - Z = Z.reshape(xx.shape) - - _ = plt.figure() - plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8) - plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral) - plt.xlim(xx.min(), xx.max()) - plt.ylim(yy.min(), yy.max()) - - finish = datetime.datetime.now() - print_div(f"It took {(finish-start).seconds} seconds to run this code.") - - plt - return plt diff --git a/examples/numpy_canvas_fractals.html b/examples/numpy_canvas_fractals.html deleted file mode 100644 index 37cbbbe1eac..00000000000 --- a/examples/numpy_canvas_fractals.html +++ /dev/null @@ -1,318 +0,0 @@ - - - Visualization of Mandelbrot, Julia and Newton sets with NumPy and HTML5 canvas - - - - - - - - - - - -
-
-
Mandelbrot set
-
-
- -
-
-
-
Julia set
-
-
- -
-
-
-
Newton set
-
-
p(z) =
-
a =
-
- x = [ - - , - - ] -
-
- y = [ - - , - - ] -
-
-
convergence
-
iterations
-
-
-
-
- -
-
-
- - -- numpy -- sympy -- paths: - - ./palettes.py - - ./fractals.py - - - -from pyodide import to_js, create_proxy - -import numpy as np -import sympy - -from palettes import Magma256 -from fractals import mandelbrot, julia, newton - -from js import ( - console, - document, - devicePixelRatio, - ImageData, - Uint8ClampedArray, - CanvasRenderingContext2D as Context2d, - requestAnimationFrame, -) - -def prepare_canvas(width: int, height: int, canvas: Element) -> Context2d: - ctx = canvas.getContext("2d") - - canvas.style.width = f"{width}px" - canvas.style.height = f"{height}px" - - canvas.width = width - canvas.height = height - - ctx.clearRect(0, 0, width, height) - - return ctx - -def color_map(array: np.array, palette: np.array) -> np.array: - size, _ = palette.shape - index = (array/array.max()*(size - 1)).round().astype("uint8") - - width, height = array.shape - image = np.full((width, height, 4), 0xff, dtype=np.uint8) - image[:, :, :3] = palette[index] - - return image - -def draw_image(ctx: Context2d, image: np.array) -> None: - data = Uint8ClampedArray.new(to_js(image.tobytes())) - width, height, _ = image.shape - image_data = ImageData.new(data, width, height) - ctx.putImageData(image_data, 0, 0) - -width, height = 600, 600 - -async def draw_mandelbrot() -> None: - spinner = document.querySelector("#mandelbrot .loading") - canvas = document.querySelector("#mandelbrot canvas") - - spinner.style.display = "" - canvas.style.display = "none" - - ctx = prepare_canvas(width, height, canvas) - - console.log("Computing Mandelbrot set ...") - console.time("mandelbrot") - iters = mandelbrot(width, height) - console.timeEnd("mandelbrot") - - image = color_map(iters, Magma256) - draw_image(ctx, image) - - spinner.style.display = "none" - canvas.style.display = "block" - -async def draw_julia() -> None: - spinner = document.querySelector("#julia .loading") - canvas = document.querySelector("#julia canvas") - - spinner.style.display = "" - canvas.style.display = "none" - - ctx = prepare_canvas(width, height, canvas) - - console.log("Computing Julia set ...") - console.time("julia") - iters = julia(width, height) - console.timeEnd("julia") - - image = color_map(iters, Magma256) - draw_image(ctx, image) - - spinner.style.display = "none" - canvas.style.display = "block" - -def ranges(): - x0_in = document.querySelector("#x0") - x1_in = document.querySelector("#x1") - y0_in = document.querySelector("#y0") - y1_in = document.querySelector("#y1") - - xr = (float(x0_in.value), float(x1_in.value)) - yr = (float(y0_in.value), float(y1_in.value)) - - return xr, yr - -current_image = None -async def draw_newton() -> None: - spinner = document.querySelector("#newton .loading") - canvas = document.querySelector("#newton canvas") - - spinner.style.display = "" - canvas.style.display = "none" - - ctx = prepare_canvas(width, height, canvas) - - console.log("Computing Newton set ...") - - poly_in = document.querySelector("#poly") - coef_in = document.querySelector("#coef") - conv_in = document.querySelector("#conv") - iter_in = document.querySelector("#iter") - - xr, yr = ranges() - - # z**3 - 1 - # z**8 + 15*z**4 - 16 - # z**3 - 2*z + 2 - - expr = sympy.parse_expr(poly_in.value) - coeffs = [ complex(c) for c in reversed(sympy.Poly(expr, sympy.Symbol("z")).all_coeffs()) ] - poly = np.polynomial.Polynomial(coeffs) - - coef = complex(sympy.parse_expr(coef_in.value)) - - console.time("newton") - iters, roots = newton(width, height, p=poly, a=coef, xr=xr, yr=yr) - console.timeEnd("newton") - - if conv_in.checked: - n = poly.degree() + 1 - k = int(len(Magma256)/n) - - colors = Magma256[::k, :][:n] - colors[0, :] = [255, 0, 0] # red: no convergence - - image = color_map(roots, colors) - else: - image = color_map(iters, Magma256) - - global current_image - current_image = image - draw_image(ctx, image) - - spinner.style.display = "none" - canvas.style.display = "block" - -handler = create_proxy(lambda _event: draw_newton()) -document.querySelector("#newton fieldset").addEventListener("change", handler) - -canvas = document.querySelector("#newton canvas") - -is_selecting = False -init_sx, init_sy = None, None -sx, sy = None, None -async def mousemove(event): - global is_selecting - global init_sx - global init_sy - global sx - global sy - - def invert(sx, source_range, target_range): - source_start, source_end = source_range - target_start, target_end = target_range - factor = (target_end - target_start)/(source_end - source_start) - offset = -(factor * source_start) + target_start - return (sx - offset) / factor - - bds = canvas.getBoundingClientRect() - event_sx, event_sy = event.clientX - bds.x, event.clientY - bds.y - - ctx = canvas.getContext("2d") - - pressed = event.buttons == 1 - if is_selecting: - if not pressed: - xr, yr = ranges() - - x0 = invert(init_sx, xr, (0, width)) - x1 = invert(sx, xr, (0, width)) - y0 = invert(init_sy, yr, (0, height)) - y1 = invert(sy, yr, (0, height)) - - document.querySelector("#x0").value = x0 - document.querySelector("#x1").value = x1 - document.querySelector("#y0").value = y0 - document.querySelector("#y1").value = y1 - - is_selecting = False - init_sx, init_sy = None, None - sx, sy = init_sx, init_sy - - await draw_newton() - else: - ctx.save() - ctx.clearRect(0, 0, width, height) - draw_image(ctx, current_image) - sx, sy = event_sx, event_sy - ctx.beginPath() - ctx.rect(init_sx, init_sy, sx - init_sx, sy - init_sy) - ctx.fillStyle = "rgba(255, 255, 255, 0.4)" - ctx.strokeStyle = "rgba(255, 255, 255, 1.0)" - ctx.fill() - ctx.stroke() - ctx.restore() - else: - if pressed: - is_selecting = True - init_sx, init_sy = event_sx, event_sy - sx, sy = init_sx, init_sy - -canvas.addEventListener("mousemove", create_proxy(mousemove)) - -import asyncio - -_ = await asyncio.gather( - draw_mandelbrot(), - draw_julia(), - draw_newton(), -) - - - - diff --git a/examples/palettes.py b/examples/palettes.py deleted file mode 100644 index b4362c17ed7..00000000000 --- a/examples/palettes.py +++ /dev/null @@ -1,263 +0,0 @@ -import numpy as np - -Magma256 = np.array( - [ - [0x00, 0x00, 0x03], - [0x00, 0x00, 0x04], - [0x00, 0x00, 0x06], - [0x01, 0x00, 0x07], - [0x01, 0x01, 0x09], - [0x01, 0x01, 0x0B], - [0x02, 0x02, 0x0D], - [0x02, 0x02, 0x0F], - [0x03, 0x03, 0x11], - [0x04, 0x03, 0x13], - [0x04, 0x04, 0x15], - [0x05, 0x04, 0x17], - [0x06, 0x05, 0x19], - [0x07, 0x05, 0x1B], - [0x08, 0x06, 0x1D], - [0x09, 0x07, 0x1F], - [0x0A, 0x07, 0x22], - [0x0B, 0x08, 0x24], - [0x0C, 0x09, 0x26], - [0x0D, 0x0A, 0x28], - [0x0E, 0x0A, 0x2A], - [0x0F, 0x0B, 0x2C], - [0x10, 0x0C, 0x2F], - [0x11, 0x0C, 0x31], - [0x12, 0x0D, 0x33], - [0x14, 0x0D, 0x35], - [0x15, 0x0E, 0x38], - [0x16, 0x0E, 0x3A], - [0x17, 0x0F, 0x3C], - [0x18, 0x0F, 0x3F], - [0x1A, 0x10, 0x41], - [0x1B, 0x10, 0x44], - [0x1C, 0x10, 0x46], - [0x1E, 0x10, 0x49], - [0x1F, 0x11, 0x4B], - [0x20, 0x11, 0x4D], - [0x22, 0x11, 0x50], - [0x23, 0x11, 0x52], - [0x25, 0x11, 0x55], - [0x26, 0x11, 0x57], - [0x28, 0x11, 0x59], - [0x2A, 0x11, 0x5C], - [0x2B, 0x11, 0x5E], - [0x2D, 0x10, 0x60], - [0x2F, 0x10, 0x62], - [0x30, 0x10, 0x65], - [0x32, 0x10, 0x67], - [0x34, 0x10, 0x68], - [0x35, 0x0F, 0x6A], - [0x37, 0x0F, 0x6C], - [0x39, 0x0F, 0x6E], - [0x3B, 0x0F, 0x6F], - [0x3C, 0x0F, 0x71], - [0x3E, 0x0F, 0x72], - [0x40, 0x0F, 0x73], - [0x42, 0x0F, 0x74], - [0x43, 0x0F, 0x75], - [0x45, 0x0F, 0x76], - [0x47, 0x0F, 0x77], - [0x48, 0x10, 0x78], - [0x4A, 0x10, 0x79], - [0x4B, 0x10, 0x79], - [0x4D, 0x11, 0x7A], - [0x4F, 0x11, 0x7B], - [0x50, 0x12, 0x7B], - [0x52, 0x12, 0x7C], - [0x53, 0x13, 0x7C], - [0x55, 0x13, 0x7D], - [0x57, 0x14, 0x7D], - [0x58, 0x15, 0x7E], - [0x5A, 0x15, 0x7E], - [0x5B, 0x16, 0x7E], - [0x5D, 0x17, 0x7E], - [0x5E, 0x17, 0x7F], - [0x60, 0x18, 0x7F], - [0x61, 0x18, 0x7F], - [0x63, 0x19, 0x7F], - [0x65, 0x1A, 0x80], - [0x66, 0x1A, 0x80], - [0x68, 0x1B, 0x80], - [0x69, 0x1C, 0x80], - [0x6B, 0x1C, 0x80], - [0x6C, 0x1D, 0x80], - [0x6E, 0x1E, 0x81], - [0x6F, 0x1E, 0x81], - [0x71, 0x1F, 0x81], - [0x73, 0x1F, 0x81], - [0x74, 0x20, 0x81], - [0x76, 0x21, 0x81], - [0x77, 0x21, 0x81], - [0x79, 0x22, 0x81], - [0x7A, 0x22, 0x81], - [0x7C, 0x23, 0x81], - [0x7E, 0x24, 0x81], - [0x7F, 0x24, 0x81], - [0x81, 0x25, 0x81], - [0x82, 0x25, 0x81], - [0x84, 0x26, 0x81], - [0x85, 0x26, 0x81], - [0x87, 0x27, 0x81], - [0x89, 0x28, 0x81], - [0x8A, 0x28, 0x81], - [0x8C, 0x29, 0x80], - [0x8D, 0x29, 0x80], - [0x8F, 0x2A, 0x80], - [0x91, 0x2A, 0x80], - [0x92, 0x2B, 0x80], - [0x94, 0x2B, 0x80], - [0x95, 0x2C, 0x80], - [0x97, 0x2C, 0x7F], - [0x99, 0x2D, 0x7F], - [0x9A, 0x2D, 0x7F], - [0x9C, 0x2E, 0x7F], - [0x9E, 0x2E, 0x7E], - [0x9F, 0x2F, 0x7E], - [0xA1, 0x2F, 0x7E], - [0xA3, 0x30, 0x7E], - [0xA4, 0x30, 0x7D], - [0xA6, 0x31, 0x7D], - [0xA7, 0x31, 0x7D], - [0xA9, 0x32, 0x7C], - [0xAB, 0x33, 0x7C], - [0xAC, 0x33, 0x7B], - [0xAE, 0x34, 0x7B], - [0xB0, 0x34, 0x7B], - [0xB1, 0x35, 0x7A], - [0xB3, 0x35, 0x7A], - [0xB5, 0x36, 0x79], - [0xB6, 0x36, 0x79], - [0xB8, 0x37, 0x78], - [0xB9, 0x37, 0x78], - [0xBB, 0x38, 0x77], - [0xBD, 0x39, 0x77], - [0xBE, 0x39, 0x76], - [0xC0, 0x3A, 0x75], - [0xC2, 0x3A, 0x75], - [0xC3, 0x3B, 0x74], - [0xC5, 0x3C, 0x74], - [0xC6, 0x3C, 0x73], - [0xC8, 0x3D, 0x72], - [0xCA, 0x3E, 0x72], - [0xCB, 0x3E, 0x71], - [0xCD, 0x3F, 0x70], - [0xCE, 0x40, 0x70], - [0xD0, 0x41, 0x6F], - [0xD1, 0x42, 0x6E], - [0xD3, 0x42, 0x6D], - [0xD4, 0x43, 0x6D], - [0xD6, 0x44, 0x6C], - [0xD7, 0x45, 0x6B], - [0xD9, 0x46, 0x6A], - [0xDA, 0x47, 0x69], - [0xDC, 0x48, 0x69], - [0xDD, 0x49, 0x68], - [0xDE, 0x4A, 0x67], - [0xE0, 0x4B, 0x66], - [0xE1, 0x4C, 0x66], - [0xE2, 0x4D, 0x65], - [0xE4, 0x4E, 0x64], - [0xE5, 0x50, 0x63], - [0xE6, 0x51, 0x62], - [0xE7, 0x52, 0x62], - [0xE8, 0x54, 0x61], - [0xEA, 0x55, 0x60], - [0xEB, 0x56, 0x60], - [0xEC, 0x58, 0x5F], - [0xED, 0x59, 0x5F], - [0xEE, 0x5B, 0x5E], - [0xEE, 0x5D, 0x5D], - [0xEF, 0x5E, 0x5D], - [0xF0, 0x60, 0x5D], - [0xF1, 0x61, 0x5C], - [0xF2, 0x63, 0x5C], - [0xF3, 0x65, 0x5C], - [0xF3, 0x67, 0x5B], - [0xF4, 0x68, 0x5B], - [0xF5, 0x6A, 0x5B], - [0xF5, 0x6C, 0x5B], - [0xF6, 0x6E, 0x5B], - [0xF6, 0x70, 0x5B], - [0xF7, 0x71, 0x5B], - [0xF7, 0x73, 0x5C], - [0xF8, 0x75, 0x5C], - [0xF8, 0x77, 0x5C], - [0xF9, 0x79, 0x5C], - [0xF9, 0x7B, 0x5D], - [0xF9, 0x7D, 0x5D], - [0xFA, 0x7F, 0x5E], - [0xFA, 0x80, 0x5E], - [0xFA, 0x82, 0x5F], - [0xFB, 0x84, 0x60], - [0xFB, 0x86, 0x60], - [0xFB, 0x88, 0x61], - [0xFB, 0x8A, 0x62], - [0xFC, 0x8C, 0x63], - [0xFC, 0x8E, 0x63], - [0xFC, 0x90, 0x64], - [0xFC, 0x92, 0x65], - [0xFC, 0x93, 0x66], - [0xFD, 0x95, 0x67], - [0xFD, 0x97, 0x68], - [0xFD, 0x99, 0x69], - [0xFD, 0x9B, 0x6A], - [0xFD, 0x9D, 0x6B], - [0xFD, 0x9F, 0x6C], - [0xFD, 0xA1, 0x6E], - [0xFD, 0xA2, 0x6F], - [0xFD, 0xA4, 0x70], - [0xFE, 0xA6, 0x71], - [0xFE, 0xA8, 0x73], - [0xFE, 0xAA, 0x74], - [0xFE, 0xAC, 0x75], - [0xFE, 0xAE, 0x76], - [0xFE, 0xAF, 0x78], - [0xFE, 0xB1, 0x79], - [0xFE, 0xB3, 0x7B], - [0xFE, 0xB5, 0x7C], - [0xFE, 0xB7, 0x7D], - [0xFE, 0xB9, 0x7F], - [0xFE, 0xBB, 0x80], - [0xFE, 0xBC, 0x82], - [0xFE, 0xBE, 0x83], - [0xFE, 0xC0, 0x85], - [0xFE, 0xC2, 0x86], - [0xFE, 0xC4, 0x88], - [0xFE, 0xC6, 0x89], - [0xFE, 0xC7, 0x8B], - [0xFE, 0xC9, 0x8D], - [0xFE, 0xCB, 0x8E], - [0xFD, 0xCD, 0x90], - [0xFD, 0xCF, 0x92], - [0xFD, 0xD1, 0x93], - [0xFD, 0xD2, 0x95], - [0xFD, 0xD4, 0x97], - [0xFD, 0xD6, 0x98], - [0xFD, 0xD8, 0x9A], - [0xFD, 0xDA, 0x9C], - [0xFD, 0xDC, 0x9D], - [0xFD, 0xDD, 0x9F], - [0xFD, 0xDF, 0xA1], - [0xFD, 0xE1, 0xA3], - [0xFC, 0xE3, 0xA5], - [0xFC, 0xE5, 0xA6], - [0xFC, 0xE6, 0xA8], - [0xFC, 0xE8, 0xAA], - [0xFC, 0xEA, 0xAC], - [0xFC, 0xEC, 0xAE], - [0xFC, 0xEE, 0xB0], - [0xFC, 0xF0, 0xB1], - [0xFC, 0xF1, 0xB3], - [0xFC, 0xF3, 0xB5], - [0xFC, 0xF5, 0xB7], - [0xFB, 0xF7, 0xB9], - [0xFB, 0xF9, 0xBB], - [0xFB, 0xFA, 0xBD], - [0xFB, 0xFC, 0xBF], - ], - dtype="uint8", -) diff --git a/examples/panel.html b/examples/panel.html deleted file mode 100644 index 251141041b9..00000000000 --- a/examples/panel.html +++ /dev/null @@ -1,32 +0,0 @@ - - - Panel Example - - - - - - - - - - - - bokeh - - numpy - - panel==0.13.1 - - -

Panel Example

-
- - import panel as pn - - slider = pn.widgets.FloatSlider(start=0, end=10, name='Amplitude') - - def callback(new): - return f'Amplitude is: {new}' - - pn.Row(slider, pn.bind(callback, slider)).servable(target='simple_app'); - - - diff --git a/examples/panel_deckgl.html b/examples/panel_deckgl.html deleted file mode 100644 index 8e9d1cf78be..00000000000 --- a/examples/panel_deckgl.html +++ /dev/null @@ -1,222 +0,0 @@ - - - - - - - - - - - PyScript/Panel DeckGL Demo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bokeh - - numpy - - pandas - - panel==0.13.1 - - - -
- - -
- -
-
-
-
-
- - - import panel as pn - import pandas as pd - import param - - from pyodide.http import open_url - - MAPBOX_KEY = "pk.eyJ1IjoicGFuZWxvcmciLCJhIjoiY2s1enA3ejhyMWhmZjNobjM1NXhtbWRrMyJ9.B_frQsAVepGIe-HiOJeqvQ" - - class App(param.Parameterized): - - data = param.DataFrame(precedence=-1) - - view = param.DataFrame(precedence=-1) - - arc_view = param.DataFrame(precedence=-1) - - radius = param.Integer(default=50, bounds=(20, 1000)) - - elevation = param.Integer(default=10, bounds=(0, 50)) - - hour = param.Integer(default=0, bounds=(0, 23)) - - speed = param.Integer(default=1, bounds=(0, 10), precedence=-1) - - play = param.Event(label='▷') - - def __init__(self, **params): - self.deck_gl = None - super().__init__(**params) - self.deck_gl = pn.pane.DeckGL( - dict(self.spec), - mapbox_api_key=MAPBOX_KEY, - throttle={'click': 10}, - sizing_mode='stretch_both', - margin=0 - ) - self.deck_gl.param.watch(self._update_arc_view, 'click_state') - self._playing = False - self._cb = pn.state.add_periodic_callback( - self._update_hour, 1000//self.speed, start=False - ) - - @property - def spec(self): - return { - "initialViewState": { - "bearing": 0, - "latitude": 40.7, - "longitude": -73.9, - "maxZoom": 15, - "minZoom": 5, - "pitch": 40.5, - "zoom": 11 - }, - "layers": [self.hex_layer, self.arc_layer], - "mapStyle": "mapbox://styles/mapbox/dark-v9", - "views": [ - {"@@type": "MapView", "controller": True} - ] - } - - @property - def hex_layer(self): - return { - "@@type": "HexagonLayer", - "autoHighlight": True, - "coverage": 1, - "data": self.data if self.view is None else self.view, - "elevationRange": [0, 100], - "elevationScale": self.elevation, - "radius": self.radius, - "extruded": True, - "getPosition": "@@=[pickup_x, pickup_y]", - "id": "8a553b25-ef3a-489c-bbe2-e102d18a3211" - } - - @property - def arc_layer(self): - return { - "@@type": "ArcLayer", - "id": 'arc-layer', - "data": self.arc_view, - "pickable": True, - "getWidth": 1, - "getSourcePosition": "@@=[pickup_x, pickup_y]", - "getTargetPosition": "@@=[dropoff_x, dropoff_y]", - "getSourceColor": [0, 255, 0, 180], - "getTargetColor": [240, 100, 0, 180] - } - - def _update_hour(self): - self.hour = (self.hour+1) % 24 - - @param.depends('view', watch=True) - def _update_arc_view(self, event=None): - data = self.data if self.view is None else self.view - if not self.deck_gl or not self.deck_gl.click_state: - self.arc_view = data.iloc[:0] - return - lon, lat = self.deck_gl.click_state['coordinate'] - tol = 0.001 - self.arc_view = data[ - (df.pickup_x>=float(lon-tol)) & - (df.pickup_x<=float(lon+tol)) & - (df.pickup_y>=float(lat-tol)) & - (df.pickup_y<=float(lat+tol)) - ] - - @param.depends('hour', watch=True, on_init=True) - def _update_hourly_view(self): - self.view = self.data[self.data.hour==self.hour] - - @param.depends('speed', watch=True) - def _update_speed(self): - self._cb.period = 1000//self.speed - - @param.depends('play', watch=True) - def _play_pause(self): - if self._playing: - self._cb.stop() - self.param.play.label = '▷' - self.param.speed.precedence = -1 - else: - self._cb.start() - self.param.play.label = '❚❚' - self.param.speed.precedence = 1 - self._playing = not self._playing - - @param.depends('view', 'radius', 'elevation', 'arc_view', watch=True) - def update_spec(self): - self.deck_gl.object = dict(self.spec) - - url = 'https://s3.eu-west-1.amazonaws.com/assets.holoviews.org/data/nyc_taxi_wide.csv' - df = pd.read_csv(open_url(url)) - app = App(data=df) - controls = pn.Param(app.param, sizing_mode='stretch_width', show_name=False) - - app.deck_gl.servable(target='plot') - controls.servable(target='widgets'); - - - diff --git a/examples/panel_kmeans.html b/examples/panel_kmeans.html deleted file mode 100644 index f4a76d18328..00000000000 --- a/examples/panel_kmeans.html +++ /dev/null @@ -1,173 +0,0 @@ - - - - - - - - - - - Pyscript/Panel KMeans Demo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - altair - - numpy - - pandas - - scikit-learn - - panel==0.13.1 - - - -
- - -
- -
-
-
-
-
-
-
- - - import altair as alt - import panel as pn - import pandas as pd - - from sklearn.cluster import KMeans - from pyodide.http import open_url - - pn.config.sizing_mode = 'stretch_width' - - url = 'https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-07-28/penguins.csv' - penguins = pd.read_csv(open_url(url)).dropna() - cols = list(penguins.columns)[2:6] - - x = pn.widgets.Select(name='x', options=cols, value='bill_depth_mm').servable(target='x-widget') - y = pn.widgets.Select(name='y', options=cols, value='bill_length_mm').servable(target='y-widget') - n_clusters = pn.widgets.IntSlider(name='n_clusters', start=1, end=5, value=3).servable(target='n-widget') - - brush = alt.selection_interval(name='brush') # selection of type "interval" - - def get_clusters(n_clusters): - kmeans = KMeans(n_clusters=n_clusters) - est = kmeans.fit(penguins[cols].values) - df = penguins.copy() - df['labels'] = est.labels_.astype('str') - return df - - def get_chart(x, y, df): - centers = df.groupby('labels').mean() - return ( - alt.Chart(df) - .mark_point(size=100) - .encode( - x=alt.X(x, scale=alt.Scale(zero=False)), - y=alt.Y(y, scale=alt.Scale(zero=False)), - shape='labels', - color='species' - ).add_selection(brush).properties(width=800) + - alt.Chart(centers) - .mark_point(size=250, shape='cross', color='black') - .encode(x=x+':Q', y=y+':Q') - ) - - intro = pn.pane.Markdown(""" - This app provides an example of **building a simple dashboard using - Panel**.\n\nIt demonstrates how to take the output of **k-means - clustering on the Penguins dataset** using scikit-learn, - parameterizing the number of clusters and the variables to - plot.\n\nThe plot and the table are linked, i.e. selecting on the plot - will filter the data in the table.\n\n The **`x` marks the center** of - the cluster. - """).servable(target='intro') - - chart = pn.pane.Vega().servable(target='cluster-plot') - table = pn.widgets.Tabulator(pagination='remote', page_size=10).servable(target='table') - - def update_table(event=None): - table.value = get_clusters(n_clusters.value) - - n_clusters.param.watch(update_table, 'value') - - @pn.depends(x, y, n_clusters, watch=True) - def update_chart(*events): - chart.object = get_chart(x.value, y.value, table.value) - chart.selection.param.watch(update_filters, 'brush') - - def update_filters(event=None): - filters = [] - for k, v in (getattr(event, 'new') or {}).items(): - filters.append(dict(field=k, type='>=', value=v[0])) - filters.append(dict(field=k, type='<=', value=v[1])) - table.filters = filters - - update_table() - update_chart() - - - - - diff --git a/examples/panel_stream.html b/examples/panel_stream.html deleted file mode 100644 index 5fc0f079483..00000000000 --- a/examples/panel_stream.html +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - - - - - PyScript/Panel Streaming Demo - - - - - - - - - - - - - - - - - - - - - - - - - - - bokeh - - numpy - - pandas - - panel==0.13.1 - - - -
- - -
-
-
-
-
-
-
-
-
-
- - - import panel as pn - import numpy as np - import pandas as pd - - from bokeh.models import ColumnDataSource - from bokeh.plotting import figure - - df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD')).cumsum() - - rollover = pn.widgets.IntInput(name='Rollover', value=15) - follow = pn.widgets.Checkbox(name='Follow', value=True, align='end') - - tabulator = pn.widgets.Tabulator(df, height=450, width=400).servable(target='table') - - def color_negative_red(val): - """ - Takes a scalar and returns a string with - the css property `'color: red'` for negative - strings, black otherwise. - """ - color = 'red' if val < 0 else 'green' - return 'color: %s' % color - - tabulator.style.applymap(color_negative_red) - - p = figure(height=450, width=600) - - cds = ColumnDataSource(data=ColumnDataSource.from_df(df)) - - p.line('index', 'A', source=cds, line_color='red') - p.line('index', 'B', source=cds, line_color='green') - p.line('index', 'C', source=cds, line_color='blue') - p.line('index', 'D', source=cds, line_color='purple') - - def stream(): - data = df.iloc[-1] + np.random.randn(4) - tabulator.stream(data, rollover=rollover.value, follow=follow.value) - value = {k: [v] for k, v in tabulator.value.iloc[-1].to_dict().items()} - value['index'] = [tabulator.value.index[-1]] - cds.stream(value) - - cb = pn.state.add_periodic_callback(stream, 200) - - pn.pane.Bokeh(p).servable(target='plot') - pn.Row(cb.param.period, rollover, follow, width=400).servable(target='controls') - - - diff --git a/examples/pylist.py b/examples/pylist.py deleted file mode 100644 index 4b704332260..00000000000 --- a/examples/pylist.py +++ /dev/null @@ -1,19 +0,0 @@ -from datetime import datetime as dt - - -class PyItem(PyItemTemplate): - def on_click(self, evt=None): - self.data["done"] = not self.data["done"] - self.strike(self.data["done"]) - - self.select("input").element.checked = self.data["done"] - - -class PyList(PyListTemplate): - item_class = PyItem - - def add(self, item): - if isinstance(item, str): - item = {"content": item, "done": False, "created_at": dt.now()} - - super().add(item, labels=["content"], state_key="done") diff --git a/examples/readme.md b/examples/readme.md deleted file mode 100644 index e6ce651ca1f..00000000000 --- a/examples/readme.md +++ /dev/null @@ -1 +0,0 @@ -# [Pyscript Examples](https://pyscript.net/examples/) diff --git a/examples/repl.css b/examples/repl.css deleted file mode 100644 index a9156df8117..00000000000 --- a/examples/repl.css +++ /dev/null @@ -1,16 +0,0 @@ -#output > div { - font-family: 'monospace'; - background-color: #e5e5e5; - border: 1px solid lightgray; - border-top: 0; - font-size: 0.875rem; - padding: 0.5rem; - } - - #output > div:first-child { - border-top: 1px solid lightgray; - } - - #output > div:nth-child(even) { - border: 0; - } diff --git a/examples/repl.html b/examples/repl.html deleted file mode 100644 index 5969ad71820..00000000000 --- a/examples/repl.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - REPL - - - - - - - -- paths: - - ./antigravity.py - - - -

pyscript REPL

- Tip: press Shift-ENTER to evaluate a cell -
-
- -
- - diff --git a/examples/repl2.html b/examples/repl2.html deleted file mode 100644 index c667bd2cd04..00000000000 --- a/examples/repl2.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - Custom REPL Example - - - - - - - - - -- bokeh -- numpy -- paths: - - ./utils.py - - ./antigravity.py - - - -

Custom REPL

- - -
-
-
-
- - diff --git a/examples/simple_bioinformatics_tool.html b/examples/simple_bioinformatics_tool.html deleted file mode 100644 index b6ca8bb9b15..00000000000 --- a/examples/simple_bioinformatics_tool.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - PyScript — Simple Bioinformatics Example - - - - - - - - -
-
-

PyScript — Simple Bioinformatics Example v.1

-

- Demonstrates the simple use of PyScript - in Bioinformatics/Computational Biology fields! -

-
-
- - - -
-

🧬 DNA Sequence Tool

- - -
- -
- -
-
- - - -
-
-
- -
-
-
- - -
-
- -
- - - -
-
- -

- - - - -# Define HTML elements and inputs -dna_alphabet = "ATGC" -output = Element("output") -dna_seq_element = Element("dna_seq") -operation_element = Element("operation") -operation_name_output_element = Element("operation_name_output") - -# DNA Sequene Operations -def return_reverse(dna_seq): - return dna_seq[::-1] -def return_complement(dna_seq): - return dna_seq.translate(str.maketrans("ATCG", "TAGC")) -def return_reverse_complement(dna_seq): - return dna_seq.translate(str.maketrans("ATCG", "TAGC"))[::-1] - -# Check DNA seq is valid -def check_dna_seq(dna_seq): - return all(letter in dna_alphabet for letter in dna_seq.upper()) - -# Clear the form and output -def clear(*args, **kwargs): - dna_seq_element.clear() - output.clear() - -# Run -def run(*args, **kwargs): - dna_seq = dna_seq_element.value - is_dna_seq_valid = check_dna_seq(dna_seq) - if is_dna_seq_valid: - operation_name = operation_element.value - operation_name_output_element.write(operation_name) - - # Compute the desired outputs - if operation_name == "Reverse": - output_dna_seq = return_reverse(dna_seq) - elif operation_name == "Complement": - output_dna_seq = return_complement(dna_seq) - elif operation_name == "ReverseComplement": - output_dna_seq = return_reverse_complement(dna_seq) - - # Output the result - output.write(output_dna_seq) - elif (dna_seq.strip() == "") or (dna_seq is None): - output.write("No DNA sequence provided") - else: - output.write("Invalid DNA sequence entered") - - - - diff --git a/examples/simple_clock.html b/examples/simple_clock.html deleted file mode 100644 index 799a0ed3053..00000000000 --- a/examples/simple_clock.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - Simple Clock Demo - - - - - - - - paths: - - ./utils.py - - - - autoclose_loader: false - - runtimes: - - - src: "https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js" - name: pyodide-0.20 - lang: python - - - - -
start time:
-
-
- -# demonstrates how use the global PyScript pyscript_loader -# to send operation log messages to it -import utils -utils.now() - - - -from utils import now -import asyncio - -async def foo(): - while True: - await asyncio.sleep(1) - output = now() - pyscript.write("outputDiv2", output) - - out3 = Element("outputDiv3") - if output[-1] in ["0", "4", "8"]: - out3.write("It's espresso time!") - else: - out3.clear() - -# close the global PyScript pyscript_loader -pyscript_loader.close() -pyscript.run_until_complete(foo()) - - - diff --git a/examples/todo-pylist.html b/examples/todo-pylist.html deleted file mode 100644 index c7a622b5f46..00000000000 --- a/examples/todo-pylist.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - Todo App - - - - - - - - paths: - - ./utils.py - - - - - def add_task(*ags, **kws): - # create a new dictionary representing the new task - task = { "content": new_task_content.value, "done": False, "created_at": dt.now() } - - # add a new task to the list and tell it to use the `content` key to show in the UI - # and to use the key `done` to sync the task status with a checkbox element in the UI - myList.add(task) - - # clear the inputbox element used to create the new task - new_task_content.clear() - - - - - - To Do List - - - def on_keypress(e): - if (e.code == "Enter"): - add_task() - - - def on_click(evt): - add_task() - - - - - - - diff --git a/examples/todo.html b/examples/todo.html deleted file mode 100644 index 692bbc3d226..00000000000 --- a/examples/todo.html +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - Todo App - - - - - - - - paths: - - ./utils.py - - - - - - - -
-
- -
-

To Do List

-
-
- - -
- - -
-
- - - -
-
- - diff --git a/examples/todo.py b/examples/todo.py deleted file mode 100644 index 128802633f5..00000000000 --- a/examples/todo.py +++ /dev/null @@ -1,53 +0,0 @@ -from datetime import datetime as dt - -from utils import add_class, remove_class - -tasks = [] - -# define the task template that will be use to render new templates to the page -task_template = Element("task-template").select(".task", from_content=True) -task_list = Element("list-tasks-container") -new_task_content = Element("new-task-content") - - -def add_task(*ags, **kws): - # ignore empty task - if not new_task_content.element.value: - return None - - # create task - task_id = f"task-{len(tasks)}" - task = { - "id": task_id, - "content": new_task_content.element.value, - "done": False, - "created_at": dt.now(), - } - - tasks.append(task) - - # add the task element to the page as new node in the list by cloning from a - # template - task_html = task_template.clone(task_id, to=task_list) - task_html_content = task_html.select("p") - task_html_content.element.innerText = task["content"] - task_html_check = task_html.select("input") - task_list.element.appendChild(task_html.element) - - def check_task(evt=None): - task["done"] = not task["done"] - if task["done"]: - add_class(task_html_content, "line-through") - else: - remove_class(task_html_content, "line-through") - - new_task_content.clear() - task_html_check.element.onclick = check_task - - -def add_task_event(e): - if e.key == "Enter": - add_task() - - -new_task_content.element.onkeypress = add_task_event diff --git a/examples/toga/README.md b/examples/toga/README.md deleted file mode 100644 index ae974ea1e6e..00000000000 --- a/examples/toga/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# Freedom Units! - -This is a demo Toga app implementing a Fahrenheit to Celsius converter. - -## Initial setup - -1. Create and activate a virtual environment: - - $ python -m venv venv - $ . ./venv/bin/activate - -2. Install the demo requirements: - - $ pip install -r requirements.txt - -### Development details - -This demo symbolically links the pyscript build generated by the npm server -(`../build`) into the `./static/pyscript` directory. This symbolic link should -be restored automatically by git. This also means you'll need to run the main -pyscript demos at least once before running the server-rendered version of the -app. If you experience problems loading pyscript, check whether this link -exists, and the `build/pyscript.js` file has been compiled. - -It also includes an vendored experimental version of toga-core, toga-web and -toga-flask, packaged as wheels in the `./static/wheels` directory. If any changes -are made to the Toga sources, these vendored resources will need to be updated. - -## Web app - -This app can be viewed as a Single Page App (SPA); this version of the app is -linked from the main PyScript demo pages. - -It can also be viewed as a server-rendered app. This version of the app is -delivered by a demo Flask server, serving a version of app at the root URL. To -run the web demo server: - - $ cd server - $ PYTHONPATH=../freedom/src python -m demo - -then point your browser at http://localhost:8081/ - -Enter a value in the "Fahrenheit" input, and click the "calculate" button. - -It may take a few seconds for this button to become live; look for the -"Collecting nodes..." entry in the console log. - -## Desktop app - -To run this app in development mode: - - $ briefcase dev - -To build and run an app bundle: - - $ briefcase run - -If you're on an M1 macOS, this will raise an error on first run; if you get this error, run: - - $ briefcase package -p app --adhoc-sign - -then re-run `briefcase run` - -## iOS app - -To run this in the iOS simulator, run: - - $ briefcase run iOS - -To run this in the Android simulator, run: - - $ briefcase run android - -Note that these builds have extensive requirements that must be installed - -Xcode for iOS, and the Android SDKs for Android. These are multiple gigabyte -downloads. Briefcase will detect when these tools aren't available, and either -prompt you to download them, or perform a download for you. As a result, your -first build may take up to 20 minutes to complete, depending on the speed of -your connection. diff --git a/examples/toga/freedom.html b/examples/toga/freedom.html deleted file mode 100644 index fbf3d247af2..00000000000 --- a/examples/toga/freedom.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - Loading... - - -
Loading...
- - - - - - - - - './static/wheels/travertino-0.1.3-py3-none-any.whl' - - './static/wheels/toga_core-0.3.0.dev33-py3-none-any.whl' - - './static/wheels/toga_web-0.3.0.dev33-py3-none-any.whl' - - './static/wheels/freedom-0.0.1-py3-none-any.whl' - - -from toga_web.dom import handle as dom_handle - -from freedom.__main__ import main - -app = main().main_loop(spa=True) - - diff --git a/examples/toga/freedom/base-wheel.zip b/examples/toga/freedom/base-wheel.zip deleted file mode 100644 index 22e0976727b..00000000000 Binary files a/examples/toga/freedom/base-wheel.zip and /dev/null differ diff --git a/examples/toga/freedom/fake-briefcase.sh b/examples/toga/freedom/fake-briefcase.sh deleted file mode 100755 index df64f9889cd..00000000000 --- a/examples/toga/freedom/fake-briefcase.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -mkdir -p ../static/wheels -cd src -unzip ../base-wheel.zip -zip ../../static/wheels/freedom-0.0.1-py3-none-any.whl -r freedom* -rm -rf freedom-0.0.1.dist-info diff --git a/examples/toga/freedom/pyproject.toml b/examples/toga/freedom/pyproject.toml deleted file mode 100644 index ba1e5b86eb6..00000000000 --- a/examples/toga/freedom/pyproject.toml +++ /dev/null @@ -1,48 +0,0 @@ -[build-system] -requires = ["briefcase"] - -[tool.briefcase] -project_name = "Freedom Units" -bundle = "org.beeware" -version = "0.0.1" -url = "https://beeware.org" -license = "BSD license" -author = 'Tiberius Yak' -author_email = "tiberius@beeware.org" - -[tool.briefcase.app.freedom] -formal_name = "Freedom Units" -description = "A testing app" -sources = ['src/freedom'] -requires = [ - '../static/wheels/toga_core-0.3.0.dev33-py3-none-any.whl', -] - - -[tool.briefcase.app.freedom.macOS] -requires = [ - 'git+https://github.com/beeware/toga.git#egg=toga-cocoa&subdirectory=src/cocoa', - 'std-nslog>=1.0.0', -] - -[tool.briefcase.app.freedom.linux] -requires = [ - 'git+https://github.com/beeware/toga.git#egg=toga-gtk&subdirectory=src/gtk', -] - -[tool.briefcase.app.freedom.windows] -requires = [ - 'git+https://github.com/beeware/toga.git#egg=toga-winforms&subdirectory=src/winforms', -] - -# Mobile deployments -[tool.briefcase.app.freedom.iOS] -requires = [ - 'git+https://github.com/beeware/toga.git#egg=toga-iOS&subdirectory=src/iOS', - 'std-nslog>=1.0.0', -] - -[tool.briefcase.app.freedom.android] -requires = [ - 'git+https://github.com/beeware/toga.git#egg=toga-android&subdirectory=src/android', -] diff --git a/examples/toga/freedom/src/freedom/__main__.py b/examples/toga/freedom/src/freedom/__main__.py deleted file mode 100644 index 243efbc58cf..00000000000 --- a/examples/toga/freedom/src/freedom/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -from freedom.app import main - -print("IN FREEDOM", main) - -if __name__ == "__main__": - main().main_loop() diff --git a/examples/toga/freedom/src/freedom/app.py b/examples/toga/freedom/src/freedom/app.py deleted file mode 100644 index 188c9738789..00000000000 --- a/examples/toga/freedom/src/freedom/app.py +++ /dev/null @@ -1,60 +0,0 @@ -import toga -from toga.style.pack import COLUMN, LEFT, RIGHT, ROW, Pack - - -class FreedomApp(toga.App): - def calculate(self, widget): - try: - self.c_input.value = (float(self.f_input.value) - 32.0) * 5.0 / 9.0 - except ValueError: - self.c_input.value = "???" - - def startup(self): - self.main_window = toga.MainWindow(title=self.name) - - c_box = toga.Box() - f_box = toga.Box() - box = toga.Box() - - self.c_input = toga.TextInput(id="c_input", readonly=True) - self.f_input = toga.TextInput(id="f_input") - - c_label = toga.Label("Celsius", style=Pack(text_align=LEFT)) - f_label = toga.Label("Fahrenheit", style=Pack(text_align=LEFT)) - join_label = toga.Label("is equivalent to", style=Pack(text_align=RIGHT)) - - button = toga.Button("Calculate", id="calculate", on_press=self.calculate) - - f_box.add(self.f_input) - f_box.add(f_label) - - c_box.add(join_label) - c_box.add(self.c_input) - c_box.add(c_label) - - box.add(f_box) - box.add(c_box) - box.add(button) - - box.style.update(direction=COLUMN, padding_top=10) - f_box.style.update(direction=ROW, padding=5) - c_box.style.update(direction=ROW, padding=5) - - self.c_input.style.update(flex=1) - self.f_input.style.update(flex=1, padding_left=160) - c_label.style.update(width=100, padding_left=10) - f_label.style.update(width=100, padding_left=10) - join_label.style.update(width=150, padding_right=10) - - button.style.update(padding=15, flex=1) - - self.main_window.content = box - self.main_window.show() - - -def main(): - return FreedomApp("Freedom Units", "org.beeware.freedom", version="0.0.1") - - -if __name__ == "__main__": - main().main_loop() diff --git a/examples/toga/requirements.txt b/examples/toga/requirements.txt deleted file mode 100644 index dccd73e71f6..00000000000 --- a/examples/toga/requirements.txt +++ /dev/null @@ -1,9 +0,0 @@ -setuptools -wheel -check-manifest -briefcase -flask==2.1.1 -static/wheels/toga_core-0.3.0.dev33-py3-none-any.whl -static/wheels/toga_flask-0.3.0.dev33-py3-none-any.whl -static/wheels/toga_web-0.3.0.dev33-py3-none-any.whl -static/wheels/travertino-0.1.3-py3-none-any.whl diff --git a/examples/toga/server/demo.py b/examples/toga/server/demo.py deleted file mode 100644 index 35ce764c1ef..00000000000 --- a/examples/toga/server/demo.py +++ /dev/null @@ -1,11 +0,0 @@ -from flask import Flask -from freedom import app as freedom -from toga_flask import TogaApp - -app = Flask(__name__, static_folder="../static") - -app.add_url_rule("/", view_func=TogaApp.as_view("foo", app_module=freedom)) - - -if __name__ == "__main__": - app.run(port=8081, debug=True) diff --git a/examples/toga/static/logo-32.png b/examples/toga/static/logo-32.png deleted file mode 100644 index eae2a2e7531..00000000000 Binary files a/examples/toga/static/logo-32.png and /dev/null differ diff --git a/examples/toga/static/toga.css b/examples/toga/static/toga.css deleted file mode 100644 index cdea8be3553..00000000000 --- a/examples/toga/static/toga.css +++ /dev/null @@ -1,9 +0,0 @@ -main.toga.window { - margin-top: 5em; - display: flex; - flex-direction: column; -} - -div.toga.box { - display: flex; -} diff --git a/examples/toga/static/wheels/README.md b/examples/toga/static/wheels/README.md deleted file mode 100644 index c597914e9a2..00000000000 --- a/examples/toga/static/wheels/README.md +++ /dev/null @@ -1 +0,0 @@ -Wheels will go here. diff --git a/examples/toga/static/wheels/freedom-0.0.1-py3-none-any.whl b/examples/toga/static/wheels/freedom-0.0.1-py3-none-any.whl deleted file mode 100644 index 51443667fe3..00000000000 Binary files a/examples/toga/static/wheels/freedom-0.0.1-py3-none-any.whl and /dev/null differ diff --git a/examples/toga/static/wheels/toga_core-0.3.0.dev33-py3-none-any.whl b/examples/toga/static/wheels/toga_core-0.3.0.dev33-py3-none-any.whl deleted file mode 100644 index b5ea626559b..00000000000 Binary files a/examples/toga/static/wheels/toga_core-0.3.0.dev33-py3-none-any.whl and /dev/null differ diff --git a/examples/toga/static/wheels/toga_flask-0.3.0.dev33-py3-none-any.whl b/examples/toga/static/wheels/toga_flask-0.3.0.dev33-py3-none-any.whl deleted file mode 100644 index eba5bb5b5de..00000000000 Binary files a/examples/toga/static/wheels/toga_flask-0.3.0.dev33-py3-none-any.whl and /dev/null differ diff --git a/examples/toga/static/wheels/toga_web-0.3.0.dev33-py3-none-any.whl b/examples/toga/static/wheels/toga_web-0.3.0.dev33-py3-none-any.whl deleted file mode 100644 index e30259764f7..00000000000 Binary files a/examples/toga/static/wheels/toga_web-0.3.0.dev33-py3-none-any.whl and /dev/null differ diff --git a/examples/toga/static/wheels/travertino-0.1.3-py3-none-any.whl b/examples/toga/static/wheels/travertino-0.1.3-py3-none-any.whl deleted file mode 100644 index 07a73999dbc..00000000000 Binary files a/examples/toga/static/wheels/travertino-0.1.3-py3-none-any.whl and /dev/null differ diff --git a/examples/utils.py b/examples/utils.py deleted file mode 100644 index 1b5275d5867..00000000000 --- a/examples/utils.py +++ /dev/null @@ -1,17 +0,0 @@ -from datetime import datetime as dt - - -def format_date(dt_, fmt="%m/%d/%Y, %H:%M:%S"): - return dt_.strftime(fmt) - - -def now(fmt="%m/%d/%Y, %H:%M:%S"): - return format_date(dt.now(), fmt) - - -def remove_class(element, class_name): - element.element.classList.remove(class_name) - - -def add_class(element, class_name): - element.element.classList.add(class_name) diff --git a/examples/webgl/raycaster/index.html b/examples/webgl/raycaster/index.html deleted file mode 100644 index a767f792fdc..00000000000 --- a/examples/webgl/raycaster/index.html +++ /dev/null @@ -1,196 +0,0 @@ - - - - - Raycaster - - - - -
-
-
-
-
-
-
-
-
-
-
-
- - - - - - -from pyodide import create_proxy, to_js -from js import window -from js import Math -from js import THREE -from js import performance -from pyodide import to_js -from js import Object - - - -mouse = THREE.Vector2.new(); - -renderer = THREE.WebGLRenderer.new({"antialias":True}) -renderer.setSize(1000, 1000) -renderer.shadowMap.enabled = False -renderer.shadowMap.type = THREE.PCFSoftShadowMap -renderer.shadowMap.needsUpdate = True - -document.body.appendChild( renderer.domElement ) - -import js, pyodide -def onMouseMove(event): - event.preventDefault(); - mouse.x = (event.clientX / window.innerWidth) * 2 - 1; - mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; -js.document.addEventListener('mousemove', pyodide.create_proxy(onMouseMove)) - -camera = THREE.PerspectiveCamera.new( 35, window.innerWidth / window.innerHeight, 1, 500 ) -scene = THREE.Scene.new() -cameraRange = 3 - -camera.aspect = window.innerWidth / window.innerHeight -camera.updateProjectionMatrix() -renderer.setSize( window.innerWidth, window.innerHeight ) - -setcolor = "#000000" - -scene.background = THREE.Color.new(setcolor) -scene.fog = THREE.Fog.new(setcolor, 2.5, 3.5); - -sceneGruop = THREE.Object3D.new(); -particularGruop = THREE.Object3D.new(); - -def mathRandom(num = 1): - setNumber = - Math.random() * num + Math.random() * num - return setNumber - -particularGruop = THREE.Object3D.new(); -modularGruop = THREE.Object3D.new(); - -perms = {"flatShading":True, "color":"#111111", "transparent":False, "opacity":1, "wireframe":False} -perms = Object.fromEntries(to_js(perms)) - -particle_perms = {"color":"#FFFFFF", "side":THREE.DoubleSide} -particle_perms = Object.fromEntries(to_js(particle_perms)) - -def create_cubes(mathRandom, modularGruop): - i = 0 - while i < 30: - geometry = THREE.IcosahedronGeometry.new(); - material = THREE.MeshStandardMaterial.new(perms); - cube = THREE.Mesh.new(geometry, material); - cube.speedRotation = Math.random() * 0.1; - cube.positionX = mathRandom(); - cube.positionY = mathRandom(); - cube.positionZ = mathRandom(); - cube.castShadow = True; - cube.receiveShadow = True; - newScaleValue = mathRandom(0.3); - cube.scale.set(newScaleValue,newScaleValue,newScaleValue); - cube.rotation.x = mathRandom(180 * Math.PI / 180); - cube.rotation.y = mathRandom(180 * Math.PI / 180); - cube.rotation.z = mathRandom(180 * Math.PI / 180); - cube.position.set(cube.positionX, cube.positionY, cube.positionZ); - modularGruop.add(cube); - i += 1 - -create_cubes(mathRandom, modularGruop) - - -def generateParticle(mathRandom, particularGruop, num, amp = 2): - gmaterial = THREE.MeshPhysicalMaterial.new(particle_perms); - gparticular = THREE.CircleGeometry.new(0.2,5); - i = 0 - while i < num: - pscale = 0.001+Math.abs(mathRandom(0.03)); - particular = THREE.Mesh.new(gparticular, gmaterial); - particular.position.set(mathRandom(amp),mathRandom(amp),mathRandom(amp)); - particular.rotation.set(mathRandom(),mathRandom(),mathRandom()); - particular.scale.set(pscale,pscale,pscale); - particular.speedValue = mathRandom(1); - particularGruop.add(particular); - i += 1 - -generateParticle(mathRandom, particularGruop, 200, 2) - -sceneGruop.add(particularGruop); -scene.add(modularGruop); -scene.add(sceneGruop); - -camera.position.set(0, 0, cameraRange); -cameraValue = False; - -ambientLight = THREE.AmbientLight.new(0xFFFFFF, 0.1); - -light = THREE.SpotLight.new(0xFFFFFF, 3); -light.position.set(5, 5, 2); -light.castShadow = True; -light.shadow.mapSize.width = 10000; -light.shadow.mapSize.height = light.shadow.mapSize.width; -light.penumbra = 0.5; - -lightBack = THREE.PointLight.new(0x0FFFFF, 1); -lightBack.position.set(0, -3, -1); - -scene.add(sceneGruop); -scene.add(light); -scene.add(lightBack); - -rectSize = 2 -intensity = 100 -rectLight = THREE.RectAreaLight.new( 0x0FFFFF, intensity, rectSize, rectSize ) -rectLight.position.set( 0, 0, 1 ) -rectLight.lookAt( 0, 0, 0 ) -scene.add( rectLight ) - -rectLightHelper = THREE.RectAreaLightHelper.new( rectLight ); -raycaster = THREE.Raycaster.new(); -uSpeed = 0.1 - -time = 0.0003; -camera.lookAt(scene.position) - -while True: - time = performance.now() * 0.0003; - i = 0 - while i < particularGruop.children.length: - newObject = particularGruop.children[i]; - newObject.rotation.x += newObject.speedValue/10; - newObject.rotation.y += newObject.speedValue/10; - newObject.rotation.z += newObject.speedValue/10; - i += 1 - - i = 0 - while i < modularGruop.children.length: - newCubes = modularGruop.children[i]; - newCubes.rotation.x += 0.008; - newCubes.rotation.y += 0.005; - newCubes.rotation.z += 0.003; - - newCubes.position.x = Math.sin(time * newCubes.positionZ) * newCubes.positionY; - newCubes.position.y = Math.cos(time * newCubes.positionX) * newCubes.positionZ; - newCubes.position.z = Math.sin(time * newCubes.positionY) * newCubes.positionX; - i += 1 - - particularGruop.rotation.y += 0.005; - - modularGruop.rotation.y -= ((mouse.x * 4) + modularGruop.rotation.y) * uSpeed; - modularGruop.rotation.x -= ((-mouse.y * 4) + modularGruop.rotation.x) * uSpeed; - - renderer.render( scene, camera ) - await asyncio.sleep(0.02) - - - - - diff --git a/examples/webgl/raycaster/style.css b/examples/webgl/raycaster/style.css deleted file mode 100644 index 2d529a857b4..00000000000 --- a/examples/webgl/raycaster/style.css +++ /dev/null @@ -1,53 +0,0 @@ -body { - margin: 0; - text-align: center; - background-color: black; - cursor: crosshair; -} -canvas { - display: block; - width: 100%; - height: 100%; -} -.header { - /*top:45%;*/ - top: 45%; - color: #DDDDDD; -} -.footer { - bottom:3%; -} -.description { - color: gray; - padding-top: 50px; -} -.btn { - border-radius: 30px; - padding: 10px 30px; -} -a, a:hover, a:visited { - color: red; - text-decoration: none; -} -.disable-selection { - -moz-user-select: none; /* Firefox */ - -ms-user-select: none; /* Internet Explorer */ - -khtml-user-select: none; /* KHTML browsers (e.g. Konqueror) */ - -webkit-user-select: none; /* Chrome, Safari, and Opera */ - -webkit-touch-callout: none; /* Disable Android and iOS callouts*/ -} -h1::after { - content: ' V 2.0'; - font-size: 12px; - position:absolute; - top: 3px; - padding-left: 5px; - font-weight: 400; -} -h2::after { - content: '2'; - font-size: 12px; - position:absolute; - top: 14px; - padding-left: 5px; -} diff --git a/public/README.md b/public/README.md new file mode 100644 index 00000000000..2a384d12071 --- /dev/null +++ b/public/README.md @@ -0,0 +1,7 @@ +# Public + +The `index.html` file found in this directory is used by the GitHub Actions +(defined in this repo's `.github/workflows/` directory) as a template for the +static page used to collate all the information relating to a release of +PyScript. Such static pages (and related release assets) eventually end up on +the https://pyscript.net/ domain. diff --git a/public/index.html b/public/index.html new file mode 100644 index 00000000000..3ea49dd74e3 --- /dev/null +++ b/public/index.html @@ -0,0 +1,157 @@ + + + + + + + + + PyScript Release: _VERSION_ + + + + + +
+ +

Files

+ +
+ + + +

+ Example + + + + + +

+
+<!DOCTYPE html>
+<html lang="en">
+    <head>
+        <meta charset="utf-8" />
+        <meta name="viewport" content="width=device-width,initial-scale=1" />
+        <title>PyScript _VERSION_</title>
+        <link rel="stylesheet" href="_PATH_core.css" />
+        <script type="module" src="_PATH_core.js"></script>
+    </head>
+    <body>
+        <h1>Hello world!</h1>
+        <p>These are the Python interpreters in PyScript _VERSION_:</p>
+        <script type="py">
+            # Pyodide
+            from pyscript import display
+            import sys
+            display(sys.version)
+        </script>
+        <script type="mpy">
+            # MicroPython
+            from pyscript import display
+            import sys
+            display(sys.version)
+        </script>
+    </body>
+</html>
+
+ + diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000000..a3a7cbc434d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,9 @@ +[tool.codespell] +ignore-words-list = "afterall" +skip = "*.js,*.json" + +[tool.ruff] +line-length = 114 +lint.select = ["C4", "C90", "E", "EM", "F", "PIE", "PYI", "PLC", "Q", "RET", "W"] +lint.ignore = ["E402", "E722", "E731", "E741", "F401", "F704", "F811", "F821"] +lint.mccabe.max-complexity = 27 diff --git a/pyscriptjs/.eslintrc.js b/pyscriptjs/.eslintrc.js deleted file mode 100644 index ff2b6c8ead2..00000000000 --- a/pyscriptjs/.eslintrc.js +++ /dev/null @@ -1,46 +0,0 @@ -module.exports = { - parser: '@typescript-eslint/parser', - extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - 'plugin:@typescript-eslint/recommended-requiring-type-checking', - ], - parserOptions: { - ecmaVersion: 2020, - sourceType: 'module', - tsconfigRootDir: __dirname, - project: ['./tsconfig.json'], - extraFileExtensions: ['.svelte'], - }, - env: { - es6: true, - browser: true, - }, - overrides: [ - { - files: ['*.svelte'], - processor: 'svelte3/svelte3', - }, - ], - settings: { - 'svelte3/typescript': require('typescript'), - // ignore style tags in Svelte because of Tailwind CSS - // See https://github.com/sveltejs/eslint-plugin-svelte3/issues/70 - 'svelte3/ignore-styles': () => true, - }, - plugins: ['svelte3', '@typescript-eslint'], - ignorePatterns: ['node_modules'], - rules: { - 'no-prototype-builtins': 'warn', - '@typescript-eslint/no-unused-vars': 'warn', - '@typescript-eslint/no-explicit-any': 'warn', - '@typescript-eslint/no-unsafe-assignment': 'warn', - '@typescript-eslint/no-unsafe-argument': 'warn', - '@typescript-eslint/no-unsafe-member-access': 'warn', - '@typescript-eslint/no-unsafe-call': 'warn', - '@typescript-eslint/no-unsafe-return': 'warn', - '@typescript-eslint/no-floating-promises': 'warn', - '@typescript-eslint/restrict-plus-operands': 'warn', - '@typescript-eslint/no-empty-function': 'warn', - }, -}; diff --git a/pyscriptjs/.prettierignore b/pyscriptjs/.prettierignore deleted file mode 100644 index 0a170957e99..00000000000 --- a/pyscriptjs/.prettierignore +++ /dev/null @@ -1,6 +0,0 @@ -build -node_modules - - -# Ignore all HTML files -*.html diff --git a/pyscriptjs/.prettierrc.js b/pyscriptjs/.prettierrc.js deleted file mode 100644 index e0c5738c253..00000000000 --- a/pyscriptjs/.prettierrc.js +++ /dev/null @@ -1,13 +0,0 @@ -module.exports = { - arrowParens: 'avoid', - bracketSameLine: true, - singleQuote: true, - printWidth: 120, - plugins: ['prettier-plugin-svelte'], - semi: true, - svelteSortOrder: 'options-styles-scripts-markup', - svelteStrictMode: false, - svelteIndentScriptAndStyle: true, - tabWidth: 4, - trailingComma: 'all', -} diff --git a/pyscriptjs/Makefile b/pyscriptjs/Makefile deleted file mode 100644 index fa794c2a881..00000000000 --- a/pyscriptjs/Makefile +++ /dev/null @@ -1,83 +0,0 @@ -tag := latest -git_hash ?= $(shell git log -1 --pretty=format:%h) - -base_dir ?= $(shell git rev-parse --show-toplevel) -src_dir ?= $(base_dir)/src -examples ?= ../$(base_dir)/examples -app_dir ?= $(shell git rev-parse --show-prefix) - -CONDA_EXE := conda -CONDA_ENV ?= ./env -env := $(CONDA_ENV) -conda_run := $(CONDA_EXE) run -p $(env) - -setup: - npm install - $(CONDA_EXE) env $(shell [ -d $(env) ] && echo update || echo create) -p $(env) --file environment.yml - $(conda_run) playwright install - $(CONDA_EXE) install -c anaconda pytest - -clean: - find . -name \*.py[cod] -delete - rm -rf .pytest_cache .coverage coverage.xml - -clean-all: clean - rm -rf $(env) *.egg-info - -shell: - @export CONDA_ENV_PROMPT='<{name}>' - @echo 'conda activate $(env)' - -dev: - npm run dev - -build: - npm run build - -example: - mkdir -p ./examples - cp -r ../examples/* ./examples - chmod -R 755 examples - find ./examples/toga -type f -name '*.html' -exec sed -i '' s+https://pyscript.net/alpha/+../build/+g {} \; - find ./examples/webgl -type f -name '*.html' -exec sed -i '' s+https://pyscript.net/alpha/+../../build/+g {} \; - find ./examples -type f -name '*.html' -exec sed -i '' s+https://pyscript.net/alpha/+./build/+g {} \; - -test: - make example - npm run build - $(conda_run) pytest -vv $(ARGS) tests/ --log-cli-level=warning - -test-py: - @echo "Tests are coming :( this is a placeholder and it's meant to fail!" - $(conda_run) pytest -vv $(ARGS) tests/ --log-cli-level=warning - -test-ts: - @echo "Tests are coming :( this is a placeholder and it's meant to fail!" - npm run tests - -fmt: fmt-py fmt-ts - @echo "Format completed" - -fmt-check: fmt-ts-check fmt-py-check - @echo "Format check completed" - -fmt-ts: - npm run format - -fmt-ts-check: - npm run format:check - -fmt-py: - $(conda_run) black --skip-string-normalization . - $(conda_run) isort --profile black . - -fmt-py-check: - $(conda_run) black -l 88 --check . - -lint: lint-ts - @echo "Format check completed" - -lint-ts: - $(conda_run) npm run lint - -.PHONY: $(MAKECMDGOALS) diff --git a/pyscriptjs/README.md b/pyscriptjs/README.md deleted file mode 100644 index 6fd8fb25d17..00000000000 --- a/pyscriptjs/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# PyScript Demonstrator - -A simple webapp to demonstrate the capabilities of PyScript. - -## Getting started - -1. If you don't already have Node.js, install it. The official installer for the - LTS version of Node is available from [nodejs.org](https://nodejs.org/). - -2. If you don't already have Rollup, install it. Rollup can be installed as a - global resource using: - - $ npm install --global rollup - -3. Install the demo apps requirements: - - $ npm install - -4. Start the server: - - $ npm run dev - - This will compile the resources for the app, and start the development server. - -5. When the compilation completes, it will display something like: - - Your application is ready~! 🚀 - - - Local: http://localhost:8080 - - Network: Add `--host` to expose - - ────────────────── LOGS ────────────────── - - Once this is visible, open a browser at - [http://localhost:8080](http://localhost:8080). This will provide a list of - demos that you can run. - -## More information - -There is a forum PyScript where you can discuss the project or ask questions at [https://community.anaconda.cloud/c/pyscript](https://community.anaconda.cloud/c/pyscript) diff --git a/pyscriptjs/environment.yml b/pyscriptjs/environment.yml deleted file mode 100644 index 4e4bb33cc51..00000000000 --- a/pyscriptjs/environment.yml +++ /dev/null @@ -1,14 +0,0 @@ -channels: -- defaults -- conda-forge -- microsoft -dependencies: -- python=3.9 -- pip=20.2.2 -- pytest=7 -- nodejs=16 -- black -- isort -- codespell -- pre-commit -- playwright diff --git a/pyscriptjs/package-lock.json b/pyscriptjs/package-lock.json deleted file mode 100644 index 96416630b9f..00000000000 --- a/pyscriptjs/package-lock.json +++ /dev/null @@ -1,2884 +0,0 @@ -{ - "name": "pyscript", - "version": "0.0.1", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "@babel/code-frame": { - "version": "7.16.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.7.tgz", - "integrity": "sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg==", - "dev": true, - "requires": { - "@babel/highlight": "^7.16.7" - } - }, - "@babel/helper-validator-identifier": { - "version": "7.16.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz", - "integrity": "sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==", - "dev": true - }, - "@babel/highlight": { - "version": "7.16.10", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.10.tgz", - "integrity": "sha512-5FnTQLSLswEj6IkgVw5KusNUUFY9ZGqe/TRFnP/BKYHYgfh7tc+C7mwiy95/yNP7Dh9x580Vv8r7u7ZfTBFxdw==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.16.7", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" - } - }, - "@codemirror/autocomplete": { - "version": "0.19.15", - "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-0.19.15.tgz", - "integrity": "sha512-GQWzvvuXxNUyaEk+5gawbAD8s51/v2Chb++nx0e2eGWrphWk42isBtzOMdc3DxrxrZtPZ55q2ldNp+6G8KJLIQ==", - "requires": { - "@codemirror/language": "^0.19.0", - "@codemirror/state": "^0.19.4", - "@codemirror/text": "^0.19.2", - "@codemirror/tooltip": "^0.19.12", - "@codemirror/view": "^0.19.0", - "@lezer/common": "^0.15.0" - } - }, - "@codemirror/basic-setup": { - "version": "0.19.3", - "resolved": "https://registry.npmjs.org/@codemirror/basic-setup/-/basic-setup-0.19.3.tgz", - "integrity": "sha512-2hfO+QDk/HTpQzeYk1NyL1G9D5L7Sj78dtaQP8xBU42DKU9+OBPF5MdjLYnxP0jKzm6IfQfsLd89fnqW3rBVfQ==", - "requires": { - "@codemirror/autocomplete": "^0.19.0", - "@codemirror/closebrackets": "^0.19.0", - "@codemirror/commands": "^0.19.0", - "@codemirror/comment": "^0.19.0", - "@codemirror/fold": "^0.19.0", - "@codemirror/gutter": "^0.19.0", - "@codemirror/highlight": "^0.19.0", - "@codemirror/history": "^0.19.0", - "@codemirror/language": "^0.19.0", - "@codemirror/lint": "^0.19.0", - "@codemirror/matchbrackets": "^0.19.0", - "@codemirror/rectangular-selection": "^0.19.2", - "@codemirror/search": "^0.19.0", - "@codemirror/state": "^0.19.0", - "@codemirror/view": "^0.19.31" - } - }, - "@codemirror/closebrackets": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@codemirror/closebrackets/-/closebrackets-0.19.1.tgz", - "integrity": "sha512-ZiLXT6u+VuBK5QnfBbt/Vmfd9Pg6449wn1DIOWFZHUOldg5eFn3VGGjYY2XWuHQz5WuK+7dXamV2KE885O1gyA==", - "requires": { - "@codemirror/language": "^0.19.0", - "@codemirror/rangeset": "^0.19.0", - "@codemirror/state": "^0.19.2", - "@codemirror/text": "^0.19.0", - "@codemirror/view": "^0.19.44" - } - }, - "@codemirror/commands": { - "version": "0.19.8", - "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-0.19.8.tgz", - "integrity": "sha512-65LIMSGUGGpY3oH6mzV46YWRrgao6NmfJ+AuC7jNz3K5NPnH6GCV1H5I6SwOFyVbkiygGyd0EFwrWqywTBD1aw==", - "requires": { - "@codemirror/language": "^0.19.0", - "@codemirror/matchbrackets": "^0.19.0", - "@codemirror/state": "^0.19.2", - "@codemirror/text": "^0.19.6", - "@codemirror/view": "^0.19.22", - "@lezer/common": "^0.15.0" - } - }, - "@codemirror/comment": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@codemirror/comment/-/comment-0.19.1.tgz", - "integrity": "sha512-uGKteBuVWAC6fW+Yt8u27DOnXMT/xV4Ekk2Z5mRsiADCZDqYvryrJd6PLL5+8t64BVyocwQwNfz1UswYS2CtFQ==", - "requires": { - "@codemirror/state": "^0.19.9", - "@codemirror/text": "^0.19.0", - "@codemirror/view": "^0.19.0" - } - }, - "@codemirror/fold": { - "version": "0.19.3", - "resolved": "https://registry.npmjs.org/@codemirror/fold/-/fold-0.19.3.tgz", - "integrity": "sha512-8hT+Eq2G68mL0yPRvSD2ewhnLQAX6sbUJmtGVKFcj8oAXtfpYCX8LIcfXsuI19Qs7gZkOSpqZvn+KKj8IhZoAw==", - "requires": { - "@codemirror/gutter": "^0.19.0", - "@codemirror/language": "^0.19.0", - "@codemirror/rangeset": "^0.19.0", - "@codemirror/state": "^0.19.0", - "@codemirror/view": "^0.19.22" - } - }, - "@codemirror/gutter": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@codemirror/gutter/-/gutter-0.19.9.tgz", - "integrity": "sha512-PFrtmilahin1g6uL27aG5tM/rqR9DZzZYZsIrCXA5Uc2OFTFqx4owuhoU9hqfYxHp5ovfvBwQ+txFzqS4vog6Q==", - "requires": { - "@codemirror/rangeset": "^0.19.0", - "@codemirror/state": "^0.19.0", - "@codemirror/view": "^0.19.23" - } - }, - "@codemirror/highlight": { - "version": "0.19.8", - "resolved": "https://registry.npmjs.org/@codemirror/highlight/-/highlight-0.19.8.tgz", - "integrity": "sha512-v/lzuHjrYR8MN2mEJcUD6fHSTXXli9C1XGYpr+ElV6fLBIUhMTNKR3qThp611xuWfXfwDxeL7ppcbkM/MzPV3A==", - "requires": { - "@codemirror/language": "^0.19.0", - "@codemirror/rangeset": "^0.19.0", - "@codemirror/state": "^0.19.3", - "@codemirror/view": "^0.19.39", - "@lezer/common": "^0.15.0", - "style-mod": "^4.0.0" - } - }, - "@codemirror/history": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/@codemirror/history/-/history-0.19.2.tgz", - "integrity": "sha512-unhP4t3N2smzmHoo/Yio6ueWi+il8gm9VKrvi6wlcdGH5fOfVDNkmjHQ495SiR+EdOG35+3iNebSPYww0vN7ow==", - "requires": { - "@codemirror/state": "^0.19.2", - "@codemirror/view": "^0.19.0" - } - }, - "@codemirror/lang-python": { - "version": "0.19.5", - "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-0.19.5.tgz", - "integrity": "sha512-MQf7t0k6+i9KCzlFCI8EY+jjwyXLy5AwjmXsMyMCMbOw/97j70jFZYrs7Mm7RJakNE2rypWhnLGlyBTSYMqR5g==", - "requires": { - "@codemirror/highlight": "^0.19.7", - "@codemirror/language": "^0.19.0", - "@lezer/python": "^0.15.0" - } - }, - "@codemirror/language": { - "version": "0.19.10", - "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-0.19.10.tgz", - "integrity": "sha512-yA0DZ3RYn2CqAAGW62VrU8c4YxscMQn45y/I9sjBlqB1e2OTQLg4CCkMBuMSLXk4xaqjlsgazeOQWaJQOKfV8Q==", - "requires": { - "@codemirror/state": "^0.19.0", - "@codemirror/text": "^0.19.0", - "@codemirror/view": "^0.19.0", - "@lezer/common": "^0.15.5", - "@lezer/lr": "^0.15.0" - } - }, - "@codemirror/lint": { - "version": "0.19.6", - "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-0.19.6.tgz", - "integrity": "sha512-Pbw1Y5kHVs2J+itQ0uez3dI4qY9ApYVap7eNfV81x1/3/BXgBkKfadaw0gqJ4h4FDG7OnJwb0VbPsjJQllHjaA==", - "requires": { - "@codemirror/gutter": "^0.19.4", - "@codemirror/panel": "^0.19.0", - "@codemirror/rangeset": "^0.19.1", - "@codemirror/state": "^0.19.4", - "@codemirror/tooltip": "^0.19.16", - "@codemirror/view": "^0.19.22", - "crelt": "^1.0.5" - } - }, - "@codemirror/matchbrackets": { - "version": "0.19.4", - "resolved": "https://registry.npmjs.org/@codemirror/matchbrackets/-/matchbrackets-0.19.4.tgz", - "integrity": "sha512-VFkaOKPNudAA5sGP1zikRHCEKU0hjYmkKpr04pybUpQvfTvNJXlReCyP0rvH/1iEwAGPL990ZTT+QrLdu4MeEA==", - "requires": { - "@codemirror/language": "^0.19.0", - "@codemirror/state": "^0.19.0", - "@codemirror/view": "^0.19.0", - "@lezer/common": "^0.15.0" - } - }, - "@codemirror/panel": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@codemirror/panel/-/panel-0.19.1.tgz", - "integrity": "sha512-sYeOCMA3KRYxZYJYn5PNlt9yNsjy3zTNTrbYSfVgjgL9QomIVgOJWPO5hZ2sTN8lufO6lw0vTBsIPL9MSidmBg==", - "requires": { - "@codemirror/state": "^0.19.0", - "@codemirror/view": "^0.19.0" - } - }, - "@codemirror/rangeset": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@codemirror/rangeset/-/rangeset-0.19.9.tgz", - "integrity": "sha512-V8YUuOvK+ew87Xem+71nKcqu1SXd5QROMRLMS/ljT5/3MCxtgrRie1Cvild0G/Z2f1fpWxzX78V0U4jjXBorBQ==", - "requires": { - "@codemirror/state": "^0.19.0" - } - }, - "@codemirror/rectangular-selection": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/@codemirror/rectangular-selection/-/rectangular-selection-0.19.2.tgz", - "integrity": "sha512-AXK/p5eGwFJ9GJcLfntqN4dgY+XiIF7eHfXNQJX5HhQLSped2wJE6WuC1rMEaOlcpOqlb9mrNi/ZdUjSIj9mbA==", - "requires": { - "@codemirror/state": "^0.19.0", - "@codemirror/text": "^0.19.4", - "@codemirror/view": "^0.19.48" - } - }, - "@codemirror/search": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-0.19.9.tgz", - "integrity": "sha512-h3MuwbUbiyOp6Np3IB5r4LH0w4inZvbtLO1Ipmz8RhElcGRiYr11Q6Bim8ocLfe08RmZT6B5EkTj1E8eNlugQQ==", - "requires": { - "@codemirror/panel": "^0.19.0", - "@codemirror/rangeset": "^0.19.0", - "@codemirror/state": "^0.19.3", - "@codemirror/text": "^0.19.0", - "@codemirror/view": "^0.19.34", - "crelt": "^1.0.5" - } - }, - "@codemirror/state": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-0.19.9.tgz", - "integrity": "sha512-psOzDolKTZkx4CgUqhBQ8T8gBc0xN5z4gzed109aF6x7D7umpDRoimacI/O6d9UGuyl4eYuDCZmDFr2Rq7aGOw==", - "requires": { - "@codemirror/text": "^0.19.0" - } - }, - "@codemirror/text": { - "version": "0.19.6", - "resolved": "https://registry.npmjs.org/@codemirror/text/-/text-0.19.6.tgz", - "integrity": "sha512-T9jnREMIygx+TPC1bOuepz18maGq/92q2a+n4qTqObKwvNMg+8cMTslb8yxeEDEq7S3kpgGWxgO1UWbQRij0dA==" - }, - "@codemirror/theme-one-dark": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-0.19.1.tgz", - "integrity": "sha512-8gc4c2k2o/EhyHoWkghCxp5vyDT96JaFGtRy35PHwIom0LZdx7aU4AbDUnITvwiFB+0+i54VO+WQjBqgTyJvqg==", - "requires": { - "@codemirror/highlight": "^0.19.0", - "@codemirror/state": "^0.19.0", - "@codemirror/view": "^0.19.0" - } - }, - "@codemirror/tooltip": { - "version": "0.19.16", - "resolved": "https://registry.npmjs.org/@codemirror/tooltip/-/tooltip-0.19.16.tgz", - "integrity": "sha512-zxKDHryUV5/RS45AQL+wOeN+i7/l81wK56OMnUPoTSzCWNITfxHn7BToDsjtrRKbzHqUxKYmBnn/4hPjpZ4WJQ==", - "requires": { - "@codemirror/state": "^0.19.0", - "@codemirror/view": "^0.19.0" - } - }, - "@codemirror/view": { - "version": "0.19.48", - "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-0.19.48.tgz", - "integrity": "sha512-0eg7D2Nz4S8/caetCTz61rK0tkHI17V/d15Jy0kLOT8dTLGGNJUponDnW28h2B6bERmPlVHKh8MJIr5OCp1nGw==", - "requires": { - "@codemirror/rangeset": "^0.19.5", - "@codemirror/state": "^0.19.3", - "@codemirror/text": "^0.19.0", - "style-mod": "^4.0.0", - "w3c-keyname": "^2.2.4" - } - }, - "@eslint/eslintrc": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.2.2.tgz", - "integrity": "sha512-lTVWHs7O2hjBFZunXTZYnYqtB9GakA1lnxIf+gKq2nY5gxkkNi/lQvveW6t8gFdOHTg6nG50Xs95PrLqVpcaLg==", - "dev": true, - "requires": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.3.1", - "globals": "^13.9.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.0.4", - "strip-json-comments": "^3.1.1" - } - }, - "@fortawesome/fontawesome-common-types": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.1.1.tgz", - "integrity": "sha512-wVn5WJPirFTnzN6tR95abCx+ocH+3IFLXAgyavnf9hUmN0CfWoDjPT/BAWsUVwSlYYVBeCLJxaqi7ZGe4uSjBA==" - }, - "@fortawesome/free-solid-svg-icons": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.1.1.tgz", - "integrity": "sha512-0/5exxavOhI/D4Ovm2r3vxNojGZioPwmFrKg0ZUH69Q68uFhFPs6+dhAToh6VEQBntxPRYPuT5Cg1tpNa9JUPg==", - "requires": { - "@fortawesome/fontawesome-common-types": "6.1.1" - } - }, - "@humanwhocodes/config-array": { - "version": "0.9.5", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.9.5.tgz", - "integrity": "sha512-ObyMyWxZiCu/yTisA7uzx81s40xR2fD5Cg/2Kq7G02ajkNubJf6BopgDTmDyc3U7sXpNKM8cYOw7s7Tyr+DnCw==", - "dev": true, - "requires": { - "@humanwhocodes/object-schema": "^1.2.1", - "debug": "^4.1.1", - "minimatch": "^3.0.4" - } - }, - "@humanwhocodes/object-schema": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", - "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", - "dev": true - }, - "@lezer/common": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/@lezer/common/-/common-0.15.12.tgz", - "integrity": "sha512-edfwCxNLnzq5pBA/yaIhwJ3U3Kz8VAUOTRg0hhxaizaI1N+qxV7EXDv/kLCkLeq2RzSFvxexlaj5Mzfn2kY0Ig==" - }, - "@lezer/lr": { - "version": "0.15.8", - "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-0.15.8.tgz", - "integrity": "sha512-bM6oE6VQZ6hIFxDNKk8bKPa14hqFrV07J/vHGOeiAbJReIaQXmkVb6xQu4MR+JBTLa5arGRyAAjJe1qaQt3Uvg==", - "requires": { - "@lezer/common": "^0.15.0" - } - }, - "@lezer/python": { - "version": "0.15.1", - "resolved": "https://registry.npmjs.org/@lezer/python/-/python-0.15.1.tgz", - "integrity": "sha512-Xdb2nh+FoxR8ssEADGsroDtsnP+EDhiPpW9zhER3h+6cpGtZ2e9Oq/Rwn9nFQRiKCfMT+AQaqC3ZgAbhbnumyQ==", - "requires": { - "@lezer/lr": "^0.15.0" - } - }, - "@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "requires": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - } - }, - "@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true - }, - "@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "requires": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - } - }, - "@polka/url": { - "version": "1.0.0-next.21", - "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.21.tgz", - "integrity": "sha512-a5Sab1C4/icpTZVzZc5Ghpz88yQtGOyNqYXcZgOssB2uuAr+wF/MvN6bgtW32q7HHrvBki+BsZ0OuNv6EV3K9g==" - }, - "@rollup/plugin-commonjs": { - "version": "17.1.0", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-17.1.0.tgz", - "integrity": "sha512-PoMdXCw0ZyvjpCMT5aV4nkL0QywxP29sODQsSGeDpr/oI49Qq9tRtAsb/LbYbDzFlOydVEqHmmZWFtXJEAX9ew==", - "dev": true, - "requires": { - "@rollup/pluginutils": "^3.1.0", - "commondir": "^1.0.1", - "estree-walker": "^2.0.1", - "glob": "^7.1.6", - "is-reference": "^1.2.1", - "magic-string": "^0.25.7", - "resolve": "^1.17.0" - } - }, - "@rollup/plugin-node-resolve": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-11.2.1.tgz", - "integrity": "sha512-yc2n43jcqVyGE2sqV5/YCmocy9ArjVAP/BeXyTtADTBBX6V0e5UMqwO8CdQ0kzjb6zu5P1qMzsScCMRvE9OlVg==", - "dev": true, - "requires": { - "@rollup/pluginutils": "^3.1.0", - "@types/resolve": "1.17.1", - "builtin-modules": "^3.1.0", - "deepmerge": "^4.2.2", - "is-module": "^1.0.0", - "resolve": "^1.19.0" - } - }, - "@rollup/plugin-typescript": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-8.3.2.tgz", - "integrity": "sha512-MtgyR5LNHZr3GyN0tM7gNO9D0CS+Y+vflS4v/PHmrX17JCkHUYKvQ5jN5o3cz1YKllM3duXUqu3yOHwMPUxhDg==", - "dev": true, - "requires": { - "@rollup/pluginutils": "^3.1.0", - "resolve": "^1.17.0" - } - }, - "@rollup/pluginutils": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", - "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", - "dev": true, - "requires": { - "@types/estree": "0.0.39", - "estree-walker": "^1.0.1", - "picomatch": "^2.2.2" - }, - "dependencies": { - "estree-walker": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", - "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==", - "dev": true - } - } - }, - "@tsconfig/svelte": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/@tsconfig/svelte/-/svelte-1.0.13.tgz", - "integrity": "sha512-5lYJP45Xllo4yE/RUBccBT32eBlRDbqN8r1/MIvQbKxW3aFqaYPCNgm8D5V20X4ShHcwvYWNlKg3liDh1MlBoA==", - "dev": true - }, - "@types/estree": { - "version": "0.0.39", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", - "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", - "dev": true - }, - "@types/js-yaml": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.5.tgz", - "integrity": "sha512-FhpRzf927MNQdRZP0J5DLIdTXhjLYzeUTmLAu69mnVksLH9CJY3IuSeEgbKUki7GQZm0WqDkGzyxju2EZGD2wA==", - "dev": true - }, - "@types/json-schema": { - "version": "7.0.11", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.11.tgz", - "integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==", - "dev": true - }, - "@types/node": { - "version": "17.0.23", - "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.23.tgz", - "integrity": "sha512-UxDxWn7dl97rKVeVS61vErvw086aCYhDLyvRQZ5Rk65rZKepaFdm53GeqXaKBuOhED4e9uWq34IC3TdSdJJ2Gw==", - "dev": true - }, - "@types/parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==", - "dev": true - }, - "@types/pug": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@types/pug/-/pug-2.0.6.tgz", - "integrity": "sha512-SnHmG9wN1UVmagJOnyo/qkk0Z7gejYxOYYmaAwr5u2yFYfsupN3sg10kyzN8Hep/2zbHxCnsumxOoRIRMBwKCg==", - "dev": true - }, - "@types/resolve": { - "version": "1.17.1", - "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz", - "integrity": "sha512-yy7HuzQhj0dhGpD8RLXSZWEkLsV9ibvxvi6EiJ3bkqLAO1RGo0WbkWQiwpRlSFymTJRz0d3k5LM3kkx8ArDbLw==", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@types/sass": { - "version": "1.43.1", - "resolved": "https://registry.npmjs.org/@types/sass/-/sass-1.43.1.tgz", - "integrity": "sha512-BPdoIt1lfJ6B7rw35ncdwBZrAssjcwzI5LByIrYs+tpXlj/CAkuVdRsgZDdP4lq5EjyWzwxZCqAoFyHKFwp32g==", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@typescript-eslint/eslint-plugin": { - "version": "5.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.20.0.tgz", - "integrity": "sha512-fapGzoxilCn3sBtC6NtXZX6+P/Hef7VDbyfGqTTpzYydwhlkevB+0vE0EnmHPVTVSy68GUncyJ/2PcrFBeCo5Q==", - "dev": true, - "requires": { - "@typescript-eslint/scope-manager": "5.20.0", - "@typescript-eslint/type-utils": "5.20.0", - "@typescript-eslint/utils": "5.20.0", - "debug": "^4.3.2", - "functional-red-black-tree": "^1.0.1", - "ignore": "^5.1.8", - "regexpp": "^3.2.0", - "semver": "^7.3.5", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/parser": { - "version": "5.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.20.0.tgz", - "integrity": "sha512-UWKibrCZQCYvobmu3/N8TWbEeo/EPQbS41Ux1F9XqPzGuV7pfg6n50ZrFo6hryynD8qOTTfLHtHjjdQtxJ0h/w==", - "dev": true, - "requires": { - "@typescript-eslint/scope-manager": "5.20.0", - "@typescript-eslint/types": "5.20.0", - "@typescript-eslint/typescript-estree": "5.20.0", - "debug": "^4.3.2" - } - }, - "@typescript-eslint/scope-manager": { - "version": "5.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.20.0.tgz", - "integrity": "sha512-h9KtuPZ4D/JuX7rpp1iKg3zOH0WNEa+ZIXwpW/KWmEFDxlA/HSfCMhiyF1HS/drTICjIbpA6OqkAhrP/zkCStg==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.20.0", - "@typescript-eslint/visitor-keys": "5.20.0" - } - }, - "@typescript-eslint/type-utils": { - "version": "5.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.20.0.tgz", - "integrity": "sha512-WxNrCwYB3N/m8ceyoGCgbLmuZwupvzN0rE8NBuwnl7APgjv24ZJIjkNzoFBXPRCGzLNkoU/WfanW0exvp/+3Iw==", - "dev": true, - "requires": { - "@typescript-eslint/utils": "5.20.0", - "debug": "^4.3.2", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/types": { - "version": "5.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.20.0.tgz", - "integrity": "sha512-+d8wprF9GyvPwtoB4CxBAR/s0rpP25XKgnOvMf/gMXYDvlUC3rPFHupdTQ/ow9vn7UDe5rX02ovGYQbv/IUCbg==", - "dev": true - }, - "@typescript-eslint/typescript-estree": { - "version": "5.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.20.0.tgz", - "integrity": "sha512-36xLjP/+bXusLMrT9fMMYy1KJAGgHhlER2TqpUVDYUQg4w0q/NW/sg4UGAgVwAqb8V4zYg43KMUpM8vV2lve6w==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.20.0", - "@typescript-eslint/visitor-keys": "5.20.0", - "debug": "^4.3.2", - "globby": "^11.0.4", - "is-glob": "^4.0.3", - "semver": "^7.3.5", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/utils": { - "version": "5.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.20.0.tgz", - "integrity": "sha512-lHONGJL1LIO12Ujyx8L8xKbwWSkoUKFSO+0wDAqGXiudWB2EO7WEUT+YZLtVbmOmSllAjLb9tpoIPwpRe5Tn6w==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.20.0", - "@typescript-eslint/types": "5.20.0", - "@typescript-eslint/typescript-estree": "5.20.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" - }, - "dependencies": { - "eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", - "dev": true, - "requires": { - "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - } - }, - "estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true - } - } - }, - "@typescript-eslint/visitor-keys": { - "version": "5.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.20.0.tgz", - "integrity": "sha512-1flRpNF+0CAQkMNlTJ6L/Z5jiODG/e5+7mk6XwtPOUS3UrTz3UOiAg9jG2VtKsWI6rZQfy4C6a232QNRZTRGlg==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.20.0", - "eslint-visitor-keys": "^3.0.0" - } - }, - "acorn": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", - "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", - "dev": true - }, - "acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true - }, - "acorn-node": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/acorn-node/-/acorn-node-1.8.2.tgz", - "integrity": "sha512-8mt+fslDufLYntIoPAaIMUe/lrbrehIiwmR3t2k9LljIzoigEPF27eLk2hy8zSGzmR/ogr7zbRKINMo1u0yh5A==", - "dev": true, - "requires": { - "acorn": "^7.0.0", - "acorn-walk": "^7.0.0", - "xtend": "^4.0.2" - } - }, - "acorn-walk": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", - "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==", - "dev": true - }, - "ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "dev": true, - "requires": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - } - }, - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true - }, - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, - "anymatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", - "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", - "dev": true, - "requires": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - } - }, - "arg": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.1.tgz", - "integrity": "sha512-e0hDa9H2Z9AwFkk2qDlwhoMYE4eToKarchkQHovNdLTCYMHZHeRjI71crOh+dio4K6u1IcwubQqo79Ga4CyAQA==", - "dev": true - }, - "argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" - }, - "array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "dev": true - }, - "autoprefixer": { - "version": "10.4.7", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.7.tgz", - "integrity": "sha512-ypHju4Y2Oav95SipEcCcI5J7CGPuvz8oat7sUtYj3ClK44bldfvtvcxK6IEK++7rqB7YchDGzweZIBG+SD0ZAA==", - "dev": true, - "requires": { - "browserslist": "^4.20.3", - "caniuse-lite": "^1.0.30001335", - "fraction.js": "^4.2.0", - "normalize-range": "^0.1.2", - "picocolors": "^1.0.0", - "postcss-value-parser": "^4.2.0" - } - }, - "balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true - }, - "binary-extensions": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", - "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", - "dev": true - }, - "brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, - "requires": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "dev": true, - "requires": { - "fill-range": "^7.0.1" - } - }, - "browserslist": { - "version": "4.20.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.20.3.tgz", - "integrity": "sha512-NBhymBQl1zM0Y5dQT/O+xiLP9/rzOIQdKM/eMJBAq7yBgaB6krIYLGejrwVYnSHZdqjscB1SPuAjHwxjvN6Wdg==", - "dev": true, - "requires": { - "caniuse-lite": "^1.0.30001332", - "electron-to-chromium": "^1.4.118", - "escalade": "^3.1.1", - "node-releases": "^2.0.3", - "picocolors": "^1.0.0" - } - }, - "buffer-crc32": { - "version": "0.2.13", - "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", - "integrity": "sha1-DTM+PwDqxQqhRUq9MO+MKl2ackI=", - "dev": true - }, - "buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true - }, - "builtin-modules": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-3.2.0.tgz", - "integrity": "sha512-lGzLKcioL90C7wMczpkY0n/oART3MbBa8R9OFGE1rJxoVI86u4WAGfEk8Wjv10eKSyTHVGkSo3bvBylCEtk7LA==", - "dev": true - }, - "bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "dev": true - }, - "callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true - }, - "camelcase-css": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", - "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", - "dev": true - }, - "caniuse-lite": { - "version": "1.0.30001341", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001341.tgz", - "integrity": "sha512-2SodVrFFtvGENGCv0ChVJIDQ0KPaS1cg7/qtfMaICgeMolDdo/Z2OD32F0Aq9yl6F4YFwGPBS5AaPqNYiW4PoA==", - "dev": true - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - } - }, - "chokidar": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", - "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", - "dev": true, - "requires": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "fsevents": "~2.3.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - } - }, - "codemirror": { - "version": "5.65.4", - "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.65.4.tgz", - "integrity": "sha512-tytrSm5Rh52b6j36cbDXN+FHwHCl9aroY4BrDZB2NFFL3Wjfq9nuYVLFFhaOYOczKAg3JXTr8BuT8LcE5QY4Iw==" - }, - "color": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/color/-/color-4.2.1.tgz", - "integrity": "sha512-MFJr0uY4RvTQUKvPq7dh9grVOTYSFeXja2mBXioCGjnjJoXrAp9jJ1NQTDR73c9nwBSAQiNKloKl5zq9WB9UPw==", - "dev": true, - "requires": { - "color-convert": "^2.0.1", - "color-string": "^1.9.0" - }, - "dependencies": { - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - } - } - }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true - }, - "color-string": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.0.tgz", - "integrity": "sha512-9Mrz2AQLefkH1UvASKj6v6hj/7eWgjnT/cVsR8CumieLoT+g900exWeNogqtweI8dxloXN9BDQTYro1oWu/5CQ==", - "dev": true, - "requires": { - "color-name": "^1.0.0", - "simple-swizzle": "^0.2.2" - } - }, - "commander": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", - "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", - "dev": true - }, - "commondir": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", - "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", - "dev": true - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", - "dev": true - }, - "console-clear": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/console-clear/-/console-clear-1.1.1.tgz", - "integrity": "sha512-pMD+MVR538ipqkG5JXeOEbKWS5um1H4LUUccUQG68qpeqBYbzYy79Gh55jkd2TtPdRfUaLWdv6LPP//5Zt0aPQ==" - }, - "cosmiconfig": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.1.tgz", - "integrity": "sha512-a1YWNUV2HwGimB7dU2s1wUMurNKjpx60HxBB6xUM8Re+2s1g1IIfJvFR0/iCF+XHdE0GMTKTuLR32UQff4TEyQ==", - "dev": true, - "requires": { - "@types/parse-json": "^4.0.0", - "import-fresh": "^3.2.1", - "parse-json": "^5.0.0", - "path-type": "^4.0.0", - "yaml": "^1.10.0" - }, - "dependencies": { - "yaml": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", - "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", - "dev": true - } - } - }, - "crelt": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.5.tgz", - "integrity": "sha512-+BO9wPPi+DWTDcNYhr/W90myha8ptzftZT+LwcmUbbok0rcP/fequmFYCw8NMoH7pkAZQzU78b3kYrlua5a9eA==" - }, - "cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", - "dev": true, - "requires": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - } - }, - "css-color-names": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/css-color-names/-/css-color-names-0.0.4.tgz", - "integrity": "sha1-gIrcLnnPhHOAabZGyyDsJ762KeA=", - "dev": true - }, - "css-unit-converter": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/css-unit-converter/-/css-unit-converter-1.1.2.tgz", - "integrity": "sha512-IiJwMC8rdZE0+xiEZHeru6YoONC4rfPMqGm2W85jMIbkFvv5nFTwJVFHam2eFrN6txmoUYFAFXiv8ICVeTO0MA==", - "dev": true - }, - "cssesc": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", - "dev": true - }, - "debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dev": true, - "requires": { - "ms": "2.1.2" - } - }, - "deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true - }, - "deepmerge": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", - "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", - "dev": true - }, - "defined": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz", - "integrity": "sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=", - "dev": true - }, - "detect-indent": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", - "integrity": "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==", - "dev": true - }, - "detective": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/detective/-/detective-5.2.0.tgz", - "integrity": "sha512-6SsIx+nUUbuK0EthKjv0zrdnajCCXVYGmbYYiYjFVpzcjwEs/JMDZ8tPRG29J/HhN56t3GJp2cGSWDRjjot8Pg==", - "dev": true, - "requires": { - "acorn-node": "^1.6.1", - "defined": "^1.0.0", - "minimist": "^1.1.1" - } - }, - "didyoumean": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", - "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", - "dev": true - }, - "dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "dev": true, - "requires": { - "path-type": "^4.0.0" - } - }, - "dlv": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", - "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", - "dev": true - }, - "doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "requires": { - "esutils": "^2.0.2" - } - }, - "electron-to-chromium": { - "version": "1.4.137", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.137.tgz", - "integrity": "sha512-0Rcpald12O11BUogJagX3HsCN3FE83DSqWjgXoHo5a72KUKMSfI39XBgJpgNNxS9fuGzytaFjE06kZkiVFy2qA==", - "dev": true - }, - "error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, - "requires": { - "is-arrayish": "^0.2.1" - } - }, - "es6-promise": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", - "integrity": "sha1-oIzd6EzNvzTQJ6FFG8kdS80ophM=", - "dev": true - }, - "escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "dev": true - }, - "escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", - "dev": true - }, - "eslint": { - "version": "8.14.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.14.0.tgz", - "integrity": "sha512-3/CE4aJX7LNEiE3i6FeodHmI/38GZtWCsAtsymScmzYapx8q1nVVb+eLcLSzATmCPXw5pT4TqVs1E0OmxAd9tw==", - "dev": true, - "requires": { - "@eslint/eslintrc": "^1.2.2", - "@humanwhocodes/config-array": "^0.9.2", - "ajv": "^6.10.0", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.3.2", - "doctrine": "^3.0.0", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.1.1", - "eslint-utils": "^3.0.0", - "eslint-visitor-keys": "^3.3.0", - "espree": "^9.3.1", - "esquery": "^1.4.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "functional-red-black-tree": "^1.0.1", - "glob-parent": "^6.0.1", - "globals": "^13.6.0", - "ignore": "^5.2.0", - "import-fresh": "^3.0.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.0.4", - "natural-compare": "^1.4.0", - "optionator": "^0.9.1", - "regexpp": "^3.2.0", - "strip-ansi": "^6.0.1", - "strip-json-comments": "^3.1.0", - "text-table": "^0.2.0", - "v8-compile-cache": "^2.0.3" - }, - "dependencies": { - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } - }, - "chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - } - }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, - "escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true - }, - "glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "requires": { - "is-glob": "^4.0.3" - } - }, - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - } - } - }, - "eslint-plugin-svelte3": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-svelte3/-/eslint-plugin-svelte3-3.4.1.tgz", - "integrity": "sha512-7p59WG8qV8L6wLdl4d/c3mdjkgVglQCdv5XOTk/iNPBKXuuV+Q0eFP5Wa6iJd/G2M1qR3BkLPEzaANOqKAZczw==", - "dev": true - }, - "eslint-scope": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.1.1.tgz", - "integrity": "sha512-QKQM/UXpIiHcLqJ5AOyIW7XZmzjkzQXYE54n1++wb0u9V/abW3l9uQnxX8Z5Xd18xyKIMTUAyQ0k1e8pz6LUrw==", - "dev": true, - "requires": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - } - }, - "eslint-utils": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz", - "integrity": "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==", - "dev": true, - "requires": { - "eslint-visitor-keys": "^2.0.0" - }, - "dependencies": { - "eslint-visitor-keys": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz", - "integrity": "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==", - "dev": true - } - } - }, - "eslint-visitor-keys": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz", - "integrity": "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==", - "dev": true - }, - "espree": { - "version": "9.3.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.3.1.tgz", - "integrity": "sha512-bvdyLmJMfwkV3NCRl5ZhJf22zBFo1y8bYh3VYb+bfzqNB4Je68P2sSuXyuFquzWLebHpNd2/d5uv7yoP9ISnGQ==", - "dev": true, - "requires": { - "acorn": "^8.7.0", - "acorn-jsx": "^5.3.1", - "eslint-visitor-keys": "^3.3.0" - }, - "dependencies": { - "acorn": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz", - "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", - "dev": true - } - } - }, - "esquery": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", - "integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==", - "dev": true, - "requires": { - "estraverse": "^5.1.0" - } - }, - "esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "requires": { - "estraverse": "^5.2.0" - } - }, - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - }, - "estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "dev": true - }, - "esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true - }, - "fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true - }, - "fast-glob": { - "version": "3.2.11", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.11.tgz", - "integrity": "sha512-xrO3+1bxSo3ZVHAnqzyuewYT6aMFHRAd4Kcs92MAonjwQZLsK9d0SF1IyQ3k5PoirxTW0Oe/RqFgMQ6TcNE5Ew==", - "dev": true, - "requires": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.4" - } - }, - "fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true - }, - "fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", - "dev": true - }, - "fastq": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.13.0.tgz", - "integrity": "sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==", - "dev": true, - "requires": { - "reusify": "^1.0.4" - } - }, - "file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", - "dev": true, - "requires": { - "flat-cache": "^3.0.4" - } - }, - "fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "dev": true, - "requires": { - "to-regex-range": "^5.0.1" - } - }, - "flat-cache": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", - "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", - "dev": true, - "requires": { - "flatted": "^3.1.0", - "rimraf": "^3.0.2" - }, - "dependencies": { - "rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "dev": true, - "requires": { - "glob": "^7.1.3" - } - } - } - }, - "flatted": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.5.tgz", - "integrity": "sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==", - "dev": true - }, - "fraction.js": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.2.0.tgz", - "integrity": "sha512-MhLuK+2gUcnZe8ZHlaaINnQLl0xRIGRfcGk2yl8xoQAfHrSsL3rYu6FCmBdkdbhc9EPlwyGHewaRsvwRMJtAlA==", - "dev": true - }, - "fs-extra": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.0.1.tgz", - "integrity": "sha512-NbdoVMZso2Lsrn/QwLXOy6rm0ufY2zEOKCDzJR/0kBsb0E6qed0P3iYK+Ath3BfvXEeu4JhEtXLgILx5psUfag==", - "dev": true, - "requires": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - } - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", - "dev": true - }, - "fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "optional": true - }, - "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true - }, - "functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "dev": true - }, - "get-port": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/get-port/-/get-port-3.2.0.tgz", - "integrity": "sha1-3Xzn3hh8Bsi/NTeWrHHgmfCYDrw=" - }, - "glob": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", - "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "requires": { - "is-glob": "^4.0.1" - } - }, - "globals": { - "version": "13.13.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.13.0.tgz", - "integrity": "sha512-EQ7Q18AJlPwp3vUDL4mKA0KXrXyNIQyWon6T6XQiBQF0XHvRsiCSrWmmeATpUzdJN2HhWZU6Pdl0a9zdep5p6A==", - "dev": true, - "requires": { - "type-fest": "^0.20.2" - } - }, - "globby": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", - "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", - "dev": true, - "requires": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.2.9", - "ignore": "^5.2.0", - "merge2": "^1.4.1", - "slash": "^3.0.0" - } - }, - "graceful-fs": { - "version": "4.2.9", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", - "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", - "dev": true - }, - "has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "dev": true, - "requires": { - "function-bind": "^1.1.1" - } - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "hex-color-regex": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/hex-color-regex/-/hex-color-regex-1.1.0.tgz", - "integrity": "sha512-l9sfDFsuqtOqKDsQdqrMRk0U85RZc0RtOR9yPI7mRVOa4FsR/BVnZ0shmQRM96Ji99kYZP/7hn1cedc1+ApsTQ==", - "dev": true - }, - "hsl-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/hsl-regex/-/hsl-regex-1.0.0.tgz", - "integrity": "sha1-1JMwx4ntgZ4nakwNJy3/owsY/m4=", - "dev": true - }, - "hsla-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/hsla-regex/-/hsla-regex-1.0.0.tgz", - "integrity": "sha1-wc56MWjIxmFAM6S194d/OyJfnDg=", - "dev": true - }, - "html-tags": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/html-tags/-/html-tags-3.1.0.tgz", - "integrity": "sha512-1qYz89hW3lFDEazhjW0yVAV87lw8lVkrJocr72XmBkMKsoSVJCQx3W8BXsC7hO2qAt8BoVjYjtAcZ9perqGnNg==", - "dev": true - }, - "ignore": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.0.tgz", - "integrity": "sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ==", - "dev": true - }, - "import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", - "dev": true, - "requires": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - } - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", - "dev": true - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "dev": true, - "requires": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true - }, - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true - }, - "is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "dev": true, - "requires": { - "binary-extensions": "^2.0.0" - } - }, - "is-color-stop": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-color-stop/-/is-color-stop-1.1.0.tgz", - "integrity": "sha1-z/9HGu5N1cnhWFmPvhKWe1za00U=", - "dev": true, - "requires": { - "css-color-names": "^0.0.4", - "hex-color-regex": "^1.1.0", - "hsl-regex": "^1.0.0", - "hsla-regex": "^1.0.0", - "rgb-regex": "^1.0.1", - "rgba-regex": "^1.0.0" - } - }, - "is-core-module": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.1.tgz", - "integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==", - "dev": true, - "requires": { - "has": "^1.0.3" - } - }, - "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", - "dev": true - }, - "is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "requires": { - "is-extglob": "^2.1.1" - } - }, - "is-module": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", - "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", - "dev": true - }, - "is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true - }, - "is-reference": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", - "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", - "dev": true, - "requires": { - "@types/estree": "*" - } - }, - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true - }, - "jest-worker": { - "version": "26.6.2", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-26.6.2.tgz", - "integrity": "sha512-KWYVV1c4i+jbMpaBC+U++4Va0cp8OisU185o73T1vo99hqi7w8tSJfUXYswwqqrjzwxa6KpRK54WhPvwf5w6PQ==", - "dev": true, - "requires": { - "@types/node": "*", - "merge-stream": "^2.0.0", - "supports-color": "^7.0.0" - }, - "dependencies": { - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - } - } - }, - "js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true - }, - "js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "requires": { - "argparse": "^2.0.1" - } - }, - "json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true - }, - "json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", - "dev": true - }, - "jsonfile": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", - "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", - "dev": true, - "requires": { - "graceful-fs": "^4.1.6", - "universalify": "^2.0.0" - } - }, - "kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==" - }, - "levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "requires": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - } - }, - "lilconfig": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.0.5.tgz", - "integrity": "sha512-xaYmXZtTHPAw5m+xLN8ab9C+3a8YmV3asNSPOATITbtwrfbwaLJj8h66H1WMIpALCkqsIzK3h7oQ+PdX+LQ9Eg==", - "dev": true - }, - "lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true - }, - "livereload": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/livereload/-/livereload-0.9.3.tgz", - "integrity": "sha512-q7Z71n3i4X0R9xthAryBdNGVGAO2R5X+/xXpmKeuPMrteg+W2U8VusTKV3YiJbXZwKsOlFlHe+go6uSNjfxrZw==", - "dev": true, - "requires": { - "chokidar": "^3.5.0", - "livereload-js": "^3.3.1", - "opts": ">= 1.2.0", - "ws": "^7.4.3" - } - }, - "livereload-js": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/livereload-js/-/livereload-js-3.3.3.tgz", - "integrity": "sha512-a7Jipme3XIBIryJluWP5LQrEAvhobDPyScBe+q+MYwxBiMT2Ck7msy4tAdF8TAa33FMdJqX4guP81Yhiu6BkmQ==", - "dev": true - }, - "local-access": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/local-access/-/local-access-1.1.0.tgz", - "integrity": "sha512-XfegD5pyTAfb+GY6chk283Ox5z8WexG56OvM06RWLpAc/UHozO8X6xAxEkIitZOtsSMM1Yr3DkHgW5W+onLhCw==" - }, - "lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true - }, - "lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true - }, - "lodash.topath": { - "version": "4.5.2", - "resolved": "https://registry.npmjs.org/lodash.topath/-/lodash.topath-4.5.2.tgz", - "integrity": "sha1-NhY1Hzu6YZlKCTGYlmC9AyVP0Ak=", - "dev": true - }, - "lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "requires": { - "yallist": "^4.0.0" - } - }, - "magic-string": { - "version": "0.25.9", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz", - "integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==", - "dev": true, - "requires": { - "sourcemap-codec": "^1.4.8" - } - }, - "merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true - }, - "merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true - }, - "micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", - "dev": true, - "requires": { - "braces": "^3.0.2", - "picomatch": "^2.3.1" - } - }, - "mime": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", - "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", - "dev": true - }, - "min-indent": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", - "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", - "dev": true - }, - "minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "requires": { - "brace-expansion": "^1.1.7" - } - }, - "minimist": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", - "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==", - "dev": true - }, - "mkdirp": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", - "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", - "dev": true, - "requires": { - "minimist": "^1.2.6" - } - }, - "modern-normalize": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/modern-normalize/-/modern-normalize-1.1.0.tgz", - "integrity": "sha512-2lMlY1Yc1+CUy0gw4H95uNN7vjbpoED7NNRSBHE25nWfLBdmMzFCsPshlzbxHz+gYMcBEUN8V4pU16prcdPSgA==", - "dev": true - }, - "mri": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", - "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==" - }, - "mrmime": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-1.0.0.tgz", - "integrity": "sha512-a70zx7zFfVO7XpnQ2IX1Myh9yY4UYvfld/dikWRnsXxbyvMcfz+u6UfgNAtH+k2QqtJuzVpv6eLTx1G2+WKZbQ==" - }, - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - }, - "nanoid": { - "version": "3.3.4", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", - "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", - "dev": true - }, - "natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", - "dev": true - }, - "node-emoji": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz", - "integrity": "sha512-wo2DpQkQp7Sjm2A0cq+sN7EHKO6Sl0ctXeBdFZrL9T9+UywORbufTcTZxom8YqpLQt/FqNMUkOpkZrJVYSKD3A==", - "dev": true, - "requires": { - "lodash": "^4.17.21" - } - }, - "node-releases": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.4.tgz", - "integrity": "sha512-gbMzqQtTtDz/00jQzZ21PQzdI9PyLYqUSvD0p3naOhX4odFji0ZxYdnVwPTxmSwkmxhcFImpozceidSG+AgoPQ==", - "dev": true - }, - "normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true - }, - "normalize-range": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", - "integrity": "sha1-LRDAa9/TEuqXd2laTShDlFa3WUI=", - "dev": true - }, - "object-hash": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz", - "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==", - "dev": true - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "dev": true, - "requires": { - "wrappy": "1" - } - }, - "opener": { - "version": "1.5.2", - "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", - "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", - "dev": true - }, - "optionator": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", - "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", - "dev": true, - "requires": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.3" - } - }, - "opts": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/opts/-/opts-2.0.2.tgz", - "integrity": "sha512-k41FwbcLnlgnFh69f4qdUfvDQ+5vaSDnVPFI/y5XuhKRq97EnVVneO9F1ESVCdiVu4fCS2L8usX3mU331hB7pg==", - "dev": true - }, - "parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "requires": { - "callsites": "^3.0.0" - } - }, - "parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", - "dev": true - }, - "path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true - }, - "path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true - }, - "path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "dev": true - }, - "picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", - "dev": true - }, - "picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true - }, - "postcss": { - "version": "8.4.14", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.14.tgz", - "integrity": "sha512-E398TUmfAYFPBSdzgeieK2Y1+1cpdxJx8yXbK/m57nRhKSmk1GB2tO4lbLBtlkfPQTDKfe4Xqv1ASWPpayPEig==", - "dev": true, - "requires": { - "nanoid": "^3.3.4", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" - } - }, - "postcss-js": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-3.0.3.tgz", - "integrity": "sha512-gWnoWQXKFw65Hk/mi2+WTQTHdPD5UJdDXZmX073EY/B3BWnYjO4F4t0VneTCnCGQ5E5GsCdMkzPaTXwl3r5dJw==", - "dev": true, - "requires": { - "camelcase-css": "^2.0.1", - "postcss": "^8.1.6" - } - }, - "postcss-load-config": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-3.1.4.tgz", - "integrity": "sha512-6DiM4E7v4coTE4uzA8U//WhtPwyhiim3eyjEMFCnUpzbrkK9wJHgKDT2mR+HbtSrd/NubVaYTOpSpjUl8NQeRg==", - "dev": true, - "requires": { - "lilconfig": "^2.0.5", - "yaml": "^1.10.2" - }, - "dependencies": { - "yaml": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", - "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", - "dev": true - } - } - }, - "postcss-nested": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-5.0.6.tgz", - "integrity": "sha512-rKqm2Fk0KbA8Vt3AdGN0FB9OBOMDVajMG6ZCf/GoHgdxUJ4sBFp0A/uMIRm+MJUdo33YXEtjqIz8u7DAp8B7DA==", - "dev": true, - "requires": { - "postcss-selector-parser": "^6.0.6" - } - }, - "postcss-selector-parser": { - "version": "6.0.10", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", - "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==", - "dev": true, - "requires": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - } - }, - "postcss-value-parser": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", - "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", - "dev": true - }, - "prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true - }, - "prettier": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.6.2.tgz", - "integrity": "sha512-PkUpF+qoXTqhOeWL9fu7As8LXsIUZ1WYaJiY/a7McAQzxjk82OF0tibkFXVCDImZtWxbvojFjerkiLb0/q8mew==", - "dev": true - }, - "prettier-plugin-svelte": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/prettier-plugin-svelte/-/prettier-plugin-svelte-2.7.0.tgz", - "integrity": "sha512-fQhhZICprZot2IqEyoiUYLTRdumULGRvw0o4dzl5jt0jfzVWdGqeYW27QTWAeXhoupEZJULmNoH3ueJwUWFLIA==", - "dev": true - }, - "pretty-hrtime": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz", - "integrity": "sha1-t+PqQkNaTJsnWdmeDyAesZWALuE=", - "dev": true - }, - "punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "dev": true - }, - "purgecss": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/purgecss/-/purgecss-4.1.3.tgz", - "integrity": "sha512-99cKy4s+VZoXnPxaoM23e5ABcP851nC2y2GROkkjS8eJaJtlciGavd7iYAw2V84WeBqggZ12l8ef44G99HmTaw==", - "dev": true, - "requires": { - "commander": "^8.0.0", - "glob": "^7.1.7", - "postcss": "^8.3.5", - "postcss-selector-parser": "^6.0.6" - } - }, - "queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true - }, - "quick-lru": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", - "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==", - "dev": true - }, - "randombytes": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", - "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", - "dev": true, - "requires": { - "safe-buffer": "^5.1.0" - } - }, - "readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "dev": true, - "requires": { - "picomatch": "^2.2.1" - } - }, - "reduce-css-calc": { - "version": "2.1.8", - "resolved": "https://registry.npmjs.org/reduce-css-calc/-/reduce-css-calc-2.1.8.tgz", - "integrity": "sha512-8liAVezDmUcH+tdzoEGrhfbGcP7nOV4NkGE3a74+qqvE7nt9i4sKLGBuZNOnpI4WiGksiNPklZxva80061QiPg==", - "dev": true, - "requires": { - "css-unit-converter": "^1.1.1", - "postcss-value-parser": "^3.3.0" - }, - "dependencies": { - "postcss-value-parser": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.1.tgz", - "integrity": "sha512-pISE66AbVkp4fDQ7VHBwRNXzAAKJjw4Vw7nWI/+Q3vuly7SNfgYXvm6i5IgFylHGK5sP/xHAbB7N49OS4gWNyQ==", - "dev": true - } - } - }, - "regexpp": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", - "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", - "dev": true - }, - "require-relative": { - "version": "0.8.7", - "resolved": "https://registry.npmjs.org/require-relative/-/require-relative-0.8.7.tgz", - "integrity": "sha1-eZlTn8ngR6N5KPoZb44VY9q9Nt4=", - "dev": true - }, - "resolve": { - "version": "1.22.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.0.tgz", - "integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==", - "dev": true, - "requires": { - "is-core-module": "^2.8.1", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - } - }, - "resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true - }, - "reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", - "dev": true - }, - "rgb-regex": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/rgb-regex/-/rgb-regex-1.0.1.tgz", - "integrity": "sha1-wODWiC3w4jviVKR16O3UGRX+rrE=", - "dev": true - }, - "rgba-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/rgba-regex/-/rgba-regex-1.0.0.tgz", - "integrity": "sha1-QzdOLiyglosO8VI0YLfXMP8i7rM=", - "dev": true - }, - "rimraf": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", - "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", - "dev": true, - "requires": { - "glob": "^7.1.3" - } - }, - "rollup": { - "version": "2.74.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.74.1.tgz", - "integrity": "sha512-K2zW7kV8Voua5eGkbnBtWYfMIhYhT9Pel2uhBk2WO5eMee161nPze/XRfvEQPFYz7KgrCCnmh2Wy0AMFLGGmMA==", - "dev": true, - "requires": { - "fsevents": "~2.3.2" - } - }, - "rollup-plugin-css-only": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-css-only/-/rollup-plugin-css-only-3.1.0.tgz", - "integrity": "sha512-TYMOE5uoD76vpj+RTkQLzC9cQtbnJNktHPB507FzRWBVaofg7KhIqq1kGbcVOadARSozWF883Ho9KpSPKH8gqA==", - "dev": true, - "requires": { - "@rollup/pluginutils": "4" - }, - "dependencies": { - "@rollup/pluginutils": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.0.tgz", - "integrity": "sha512-2WUyJNRkyH5p487pGnn4tWAsxhEFKN/pT8CMgHshd5H+IXkOnKvKZwsz5ZWz+YCXkleZRAU5kwbfgF8CPfDRqA==", - "dev": true, - "requires": { - "estree-walker": "^2.0.1", - "picomatch": "^2.2.2" - } - } - } - }, - "rollup-plugin-livereload": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/rollup-plugin-livereload/-/rollup-plugin-livereload-2.0.5.tgz", - "integrity": "sha512-vqQZ/UQowTW7VoiKEM5ouNW90wE5/GZLfdWuR0ELxyKOJUIaj+uismPZZaICU4DnWPVjnpCDDxEqwU7pcKY/PA==", - "dev": true, - "requires": { - "livereload": "^0.9.1" - } - }, - "rollup-plugin-serve": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-serve/-/rollup-plugin-serve-1.1.0.tgz", - "integrity": "sha512-pYkSsuA0/psKqhhictkJw1c2klya5b+LlCvipWqI9OE1aG2M97mRumZCbBlry5CMEOzYBBgSDgd1694sNbmyIw==", - "dev": true, - "requires": { - "mime": ">=2.4.6", - "opener": "1" - } - }, - "rollup-plugin-string": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-string/-/rollup-plugin-string-3.0.0.tgz", - "integrity": "sha512-vqyzgn9QefAgeKi+Y4A7jETeIAU1zQmS6VotH6bzm/zmUQEnYkpIGRaOBPY41oiWYV4JyBoGAaBjYMYuv+6wVw==", - "dev": true, - "requires": { - "rollup-pluginutils": "^2.4.1" - } - }, - "rollup-plugin-svelte": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-svelte/-/rollup-plugin-svelte-7.1.0.tgz", - "integrity": "sha512-vopCUq3G+25sKjwF5VilIbiY6KCuMNHP1PFvx2Vr3REBNMDllKHFZN2B9jwwC+MqNc3UPKkjXnceLPEjTjXGXg==", - "dev": true, - "requires": { - "require-relative": "^0.8.7", - "rollup-pluginutils": "^2.8.2" - } - }, - "rollup-plugin-terser": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-7.0.2.tgz", - "integrity": "sha512-w3iIaU4OxcF52UUXiZNsNeuXIMDvFrr+ZXK6bFZ0Q60qyVfq4uLptoS4bbq3paG3x216eQllFZX7zt6TIImguQ==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.10.4", - "jest-worker": "^26.2.1", - "serialize-javascript": "^4.0.0", - "terser": "^5.0.0" - } - }, - "rollup-pluginutils": { - "version": "2.8.2", - "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", - "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", - "dev": true, - "requires": { - "estree-walker": "^0.6.1" - }, - "dependencies": { - "estree-walker": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", - "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", - "dev": true - } - } - }, - "run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "requires": { - "queue-microtask": "^1.2.2" - } - }, - "sade": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", - "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", - "requires": { - "mri": "^1.1.0" - } - }, - "safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true - }, - "sander": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/sander/-/sander-0.5.1.tgz", - "integrity": "sha1-dB4kXiMfB8r7b98PEzrfohalAq0=", - "dev": true, - "requires": { - "es6-promise": "^3.1.2", - "graceful-fs": "^4.1.3", - "mkdirp": "^0.5.1", - "rimraf": "^2.5.2" - } - }, - "semiver": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz", - "integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==" - }, - "semver": { - "version": "7.3.7", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", - "integrity": "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==", - "dev": true, - "requires": { - "lru-cache": "^6.0.0" - } - }, - "serialize-javascript": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-4.0.0.tgz", - "integrity": "sha512-GaNA54380uFefWghODBWEGisLZFj00nS5ACs6yHa9nLqlLpVLO8ChDGeKRjZnV4Nh4n0Qi7nhYZD/9fCPzEqkw==", - "dev": true, - "requires": { - "randombytes": "^2.1.0" - } - }, - "shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "requires": { - "shebang-regex": "^3.0.0" - } - }, - "shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true - }, - "simple-swizzle": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", - "integrity": "sha1-pNprY1/8zMoz9w0Xy5JZLeleVXo=", - "dev": true, - "requires": { - "is-arrayish": "^0.3.1" - }, - "dependencies": { - "is-arrayish": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", - "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==", - "dev": true - } - } - }, - "sirv": { - "version": "1.0.19", - "resolved": "https://registry.npmjs.org/sirv/-/sirv-1.0.19.tgz", - "integrity": "sha512-JuLThK3TnZG1TAKDwNIqNq6QA2afLOCcm+iE8D1Kj3GA40pSPsxQjjJl0J8X3tsR7T+CP1GavpzLwYkgVLWrZQ==", - "requires": { - "@polka/url": "^1.0.0-next.20", - "mrmime": "^1.0.0", - "totalist": "^1.0.0" - } - }, - "sirv-cli": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/sirv-cli/-/sirv-cli-1.0.14.tgz", - "integrity": "sha512-yyUTNr984ANKDloqepkYbBSqvx3buwYg2sQKPWjSU+IBia5loaoka2If8N9CMwt8AfP179cdEl7kYJ//iWJHjQ==", - "requires": { - "console-clear": "^1.1.0", - "get-port": "^3.2.0", - "kleur": "^3.0.0", - "local-access": "^1.0.1", - "sade": "^1.6.0", - "semiver": "^1.0.0", - "sirv": "^1.0.13", - "tinydate": "^1.0.0" - } - }, - "slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true - }, - "sorcery": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/sorcery/-/sorcery-0.10.0.tgz", - "integrity": "sha1-iukK19fLBfxZ8asMY3hF1cFaUrc=", - "dev": true, - "requires": { - "buffer-crc32": "^0.2.5", - "minimist": "^1.2.0", - "sander": "^0.5.0", - "sourcemap-codec": "^1.3.0" - } - }, - "source-map": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", - "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", - "dev": true - }, - "source-map-js": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", - "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", - "dev": true - }, - "source-map-support": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", - "dev": true, - "requires": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - }, - "dependencies": { - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true - } - } - }, - "sourcemap-codec": { - "version": "1.4.8", - "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", - "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", - "dev": true - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.1" - } - }, - "strip-indent": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", - "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", - "dev": true, - "requires": { - "min-indent": "^1.0.0" - } - }, - "strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true - }, - "style-mod": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.0.0.tgz", - "integrity": "sha512-OPhtyEjyyN9x3nhPsu76f52yUGXiZcgvsrFVtvTkyGRQJ0XK+GPc6ov1z+lRpbeabka+MYEQxOYRnt5nF30aMw==" - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "^3.0.0" - } - }, - "supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true - }, - "svelte": { - "version": "3.48.0", - "resolved": "https://registry.npmjs.org/svelte/-/svelte-3.48.0.tgz", - "integrity": "sha512-fN2YRm/bGumvjUpu6yI3BpvZnpIm9I6A7HR4oUNYd7ggYyIwSA/BX7DJ+UXXffLp6XNcUijyLvttbPVCYa/3xQ==" - }, - "svelte-check": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-1.6.0.tgz", - "integrity": "sha512-nQTlbFJWhwoeLY5rkhgbjzGQSwk5F1pRdEXait0EFaQSrE/iJF+PIjrQlk0BjL/ogk9HaR9ZI0DQSYrl7jl3IQ==", - "dev": true, - "requires": { - "chalk": "^4.0.0", - "chokidar": "^3.4.1", - "glob": "^7.1.6", - "import-fresh": "^3.2.1", - "minimist": "^1.2.5", - "sade": "^1.7.4", - "source-map": "^0.7.3", - "svelte-preprocess": "^4.0.0", - "typescript": "*" - }, - "dependencies": { - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } - }, - "chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - } - }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - } - } - }, - "svelte-fa": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/svelte-fa/-/svelte-fa-2.4.0.tgz", - "integrity": "sha512-0bnbMGbsE1LUnlioDcf27tl2O8kjuXlTXMXzIxC7LoIOWmqn0D+zd539HfLiQbdLuOHGTaynwN9V+4ehhEu1Jw==" - }, - "svelte-preprocess": { - "version": "4.10.6", - "resolved": "https://registry.npmjs.org/svelte-preprocess/-/svelte-preprocess-4.10.6.tgz", - "integrity": "sha512-I2SV1w/AveMvgIQlUF/ZOO3PYVnhxfcpNyGt8pxpUVhPfyfL/CZBkkw/KPfuFix5FJ9TnnNYMhACK3DtSaYVVQ==", - "dev": true, - "requires": { - "@types/pug": "^2.0.4", - "@types/sass": "^1.16.0", - "detect-indent": "^6.0.0", - "magic-string": "^0.25.7", - "sorcery": "^0.10.0", - "strip-indent": "^3.0.0" - } - }, - "svelte-promisable-stores": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/svelte-promisable-stores/-/svelte-promisable-stores-0.1.3.tgz", - "integrity": "sha512-fDRKHXSq1tnf6TTxL63P8gnoV4i1C2Kt5rE5yZHO7s3EftZuPhuz2p21d21QlCSVl0ffdy/QTgAknVSv5/R8IA==", - "requires": { - "svelte": "^3.24.1" - } - }, - "tailwindcss": { - "version": "2.2.19", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-2.2.19.tgz", - "integrity": "sha512-6Ui7JSVtXadtTUo2NtkBBacobzWiQYVjYW0ZnKaP9S1ZCKQ0w7KVNz+YSDI/j7O7KCMHbOkz94ZMQhbT9pOqjw==", - "dev": true, - "requires": { - "arg": "^5.0.1", - "bytes": "^3.0.0", - "chalk": "^4.1.2", - "chokidar": "^3.5.2", - "color": "^4.0.1", - "cosmiconfig": "^7.0.1", - "detective": "^5.2.0", - "didyoumean": "^1.2.2", - "dlv": "^1.1.3", - "fast-glob": "^3.2.7", - "fs-extra": "^10.0.0", - "glob-parent": "^6.0.1", - "html-tags": "^3.1.0", - "is-color-stop": "^1.1.0", - "is-glob": "^4.0.1", - "lodash": "^4.17.21", - "lodash.topath": "^4.5.2", - "modern-normalize": "^1.1.0", - "node-emoji": "^1.11.0", - "normalize-path": "^3.0.0", - "object-hash": "^2.2.0", - "postcss-js": "^3.0.3", - "postcss-load-config": "^3.1.0", - "postcss-nested": "5.0.6", - "postcss-selector-parser": "^6.0.6", - "postcss-value-parser": "^4.1.0", - "pretty-hrtime": "^1.0.3", - "purgecss": "^4.0.3", - "quick-lru": "^5.1.1", - "reduce-css-calc": "^2.1.8", - "resolve": "^1.20.0", - "tmp": "^0.2.1" - }, - "dependencies": { - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } - }, - "chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "requires": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - } - }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, - "glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "requires": { - "is-glob": "^4.0.3" - } - }, - "has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - } - } - }, - "terser": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.12.1.tgz", - "integrity": "sha512-NXbs+7nisos5E+yXwAD+y7zrcTkMqb0dEJxIGtSKPdCBzopf7ni4odPul2aechpV7EXNvOudYOX2bb5tln1jbQ==", - "dev": true, - "requires": { - "acorn": "^8.5.0", - "commander": "^2.20.0", - "source-map": "~0.7.2", - "source-map-support": "~0.5.20" - }, - "dependencies": { - "acorn": { - "version": "8.7.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz", - "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==", - "dev": true - }, - "commander": { - "version": "2.20.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", - "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", - "dev": true - } - } - }, - "text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", - "dev": true - }, - "tinydate": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/tinydate/-/tinydate-1.3.0.tgz", - "integrity": "sha512-7cR8rLy2QhYHpsBDBVYnnWXm8uRTr38RoZakFSW7Bs7PzfMPNZthuMLkwqZv7MTu8lhQ91cOFYS5a7iFj2oR3w==" - }, - "tmp": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz", - "integrity": "sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ==", - "dev": true, - "requires": { - "rimraf": "^3.0.0" - }, - "dependencies": { - "rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "dev": true, - "requires": { - "glob": "^7.1.3" - } - } - } - }, - "to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "requires": { - "is-number": "^7.0.0" - } - }, - "totalist": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/totalist/-/totalist-1.1.0.tgz", - "integrity": "sha512-gduQwd1rOdDMGxFG1gEvhV88Oirdo2p+KjoYFU7k2g+i7n6AFFbDQ5kMPUsW0pNbfQsB/cwXvT1i4Bue0s9g5g==" - }, - "tslib": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", - "dev": true - }, - "tsutils": { - "version": "3.21.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", - "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", - "dev": true, - "requires": { - "tslib": "^1.8.1" - }, - "dependencies": { - "tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "dev": true - } - } - }, - "type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "requires": { - "prelude-ls": "^1.2.1" - } - }, - "type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true - }, - "typescript": { - "version": "4.6.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.6.4.tgz", - "integrity": "sha512-9ia/jWHIEbo49HfjrLGfKbZSuWo9iTMwXO+Ca3pRsSpbsMbc7/IU8NKdCZVRRBafVPGnoJeFL76ZOAA84I9fEg==", - "dev": true - }, - "universalify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", - "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==", - "dev": true - }, - "uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, - "requires": { - "punycode": "^2.1.0" - } - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", - "dev": true - }, - "v8-compile-cache": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", - "integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==", - "dev": true - }, - "w3c-keyname": { - "version": "2.2.4", - "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.4.tgz", - "integrity": "sha512-tOhfEwEzFLJzf6d1ZPkYfGj+FWhIpBux9ppoP3rlclw3Z0BZv3N7b7030Z1kYth+6rDuAsXUFr+d0VE6Ed1ikw==" - }, - "which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "requires": { - "isexe": "^2.0.0" - } - }, - "word-wrap": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", - "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==", - "dev": true - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", - "dev": true - }, - "ws": { - "version": "7.5.7", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.7.tgz", - "integrity": "sha512-KMvVuFzpKBuiIXW3E4u3mySRO2/mCHSyZDJQM5NQ9Q9KHWHWh0NHgfbRMLLrceUK5qAL4ytALJbpRMjixFZh8A==", - "dev": true - }, - "xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "dev": true - }, - "yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - } - } -} diff --git a/pyscriptjs/package.json b/pyscriptjs/package.json deleted file mode 100644 index 9f1c7f2e9cd..00000000000 --- a/pyscriptjs/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "pyscript", - "version": "0.0.1", - "scripts": { - "build-min": "NODE_ENV=production rollup -c", - "build": "rollup -c", - "dev": "rollup -c -w", - "start": "sirv public --no-clear --port 8080", - "validate": "svelte-check", - "format:check": "prettier --check './src/**/*.{js,svelte,html,ts}'", - "format": "prettier --write './src/**/*.{js,svelte,html,ts}'", - "lint": "eslint './src/**/*.{js,svelte,html,ts}'", - "lint:fix": "eslint --fix './src/**/*.{js,svelte,html,ts}'", - "xprelint": "npm run format" - }, - "devDependencies": { - "@rollup/plugin-commonjs": "^17.0.0", - "@rollup/plugin-node-resolve": "^11.0.0", - "@rollup/plugin-typescript": "^8.3.2", - "@tsconfig/svelte": "^1.0.0", - "@types/js-yaml": "^4.0.5", - "@typescript-eslint/eslint-plugin": "^5.20.0", - "@typescript-eslint/parser": "^5.20.0", - "autoprefixer": "^10.4.7", - "eslint": "^8.14.0", - "eslint-plugin-svelte3": "^3.4.1", - "postcss": "^8.4.13", - "prettier": "^2.6.2", - "prettier-plugin-svelte": "^2.7.0", - "rollup": "^2.71.1", - "rollup-plugin-css-only": "^3.1.0", - "rollup-plugin-livereload": "^2.0.0", - "rollup-plugin-serve": "^1.1.0", - "rollup-plugin-string": "^3.0.0", - "rollup-plugin-svelte": "^7.0.0", - "rollup-plugin-terser": "^7.0.0", - "svelte": "^3.48.0", - "svelte-check": "^1.0.0", - "svelte-preprocess": "^4.10.6", - "tailwindcss": "^2.0.2", - "tslib": "^2.4.0", - "typescript": "^4.6.4" - }, - "dependencies": { - "@codemirror/basic-setup": "^0.19.1", - "@codemirror/lang-python": "^0.19.5", - "@codemirror/state": "^0.19.9", - "@codemirror/theme-one-dark": "^0.19.1", - "@fortawesome/free-solid-svg-icons": "^6.0.0", - "codemirror": "^5.65.3", - "js-yaml": "^4.1.0", - "sirv-cli": "^1.0.0", - "svelte-fa": "^2.4.0", - "svelte-promisable-stores": "^0.1.3" - } -} diff --git a/pyscriptjs/public/.gitkeep b/pyscriptjs/public/.gitkeep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/pyscriptjs/rollup.config.js b/pyscriptjs/rollup.config.js deleted file mode 100644 index 2e0b117f9af..00000000000 --- a/pyscriptjs/rollup.config.js +++ /dev/null @@ -1,67 +0,0 @@ -import svelte from "rollup-plugin-svelte"; -import commonjs from "@rollup/plugin-commonjs"; -import resolve from "@rollup/plugin-node-resolve"; -import livereload from "rollup-plugin-livereload"; -import { terser } from "rollup-plugin-terser"; -import sveltePreprocess from "svelte-preprocess"; -import typescript from "@rollup/plugin-typescript"; -import css from "rollup-plugin-css-only"; -import serve from "rollup-plugin-serve"; -import { string } from "rollup-plugin-string"; - -const production = !process.env.ROLLUP_WATCH || (process.env.NODE_ENV === "production"); - -export default { - input: "src/main.ts", - output:[ - { - sourcemap: true, - format: "iife", - name: "app", - file: "examples/build/pyscript.js", - }, - { - file: "examples/build/pyscript.min.js", - format: "iife", - sourcemap: true, - plugins: [terser()], - }, - ], - plugins: [ - svelte({ - // add postcss config with tailwind - preprocess: sveltePreprocess({ - postcss: { - plugins: [require("tailwindcss"), require("autoprefixer")], - }, - }), - compilerOptions: { - dev: !production, - }, - }), - css({ output: "pyscript.css" }), - // Bundle all the Python files into the output file - string({ - include: "./src/**/*.py", - }), - resolve({ - browser: true, - dedupe: ["svelte"], - }), - commonjs(), - typescript({ - sourceMap: !production, - inlineSources: !production, - }), - !production && serve(), - !production && livereload("public"), - // production && terser(), - !production && serve({ - port: 8080, - contentBase: 'examples'} - ) - ], - watch: { - clearScreen: false, - }, -}; diff --git a/pyscriptjs/src/App.svelte b/pyscriptjs/src/App.svelte deleted file mode 100644 index ab118c58c6c..00000000000 --- a/pyscriptjs/src/App.svelte +++ /dev/null @@ -1,39 +0,0 @@ - - - - - diff --git a/pyscriptjs/src/Tailwind.svelte b/pyscriptjs/src/Tailwind.svelte deleted file mode 100644 index b7fa654a31d..00000000000 --- a/pyscriptjs/src/Tailwind.svelte +++ /dev/null @@ -1,5 +0,0 @@ - diff --git a/pyscriptjs/src/components/base.ts b/pyscriptjs/src/components/base.ts deleted file mode 100644 index 31b6e47d8cc..00000000000 --- a/pyscriptjs/src/components/base.ts +++ /dev/null @@ -1,369 +0,0 @@ -import { loadedEnvironments, mode, pyodideLoaded } from '../stores'; -import { guidGenerator, addClasses, removeClasses } from '../utils'; -// Premise used to connect to the first available pyodide interpreter -let runtime; -let environments; -let currentMode; -let Element; - -pyodideLoaded.subscribe(value => { - runtime = value; -}); -loadedEnvironments.subscribe(value => { - environments = value; -}); - -mode.subscribe(value => { - currentMode = value; -}); - -// TODO: use type declaractions -type PyodideInterface = { - registerJsModule(name: string, module: object): void; -}; - -export class BaseEvalElement extends HTMLElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - code: string; - source: string; - btnConfig: HTMLElement; - btnRun: HTMLElement; - outputElement: HTMLElement; - errorElement: HTMLElement; - theme: string; - appendOutput: boolean; - - constructor() { - super(); - - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - this.setOutputMode("append"); - } - - addToOutput(s: string) { - this.outputElement.innerHTML += '
' + s + '
'; - this.outputElement.hidden = false; - } - - setOutputMode(defaultMode = "append") { - const mode = this.hasAttribute('output-mode') ? this.getAttribute('output-mode') : defaultMode; - - switch (mode) { - case "append": - this.appendOutput = true; - break; - case "replace": - this.appendOutput = false; - break; - default: - console.log(`${this.id}: custom output-modes are currently not implemented`); - } - } - - // subclasses should overwrite this method to define custom logic - // before code gets evaluated - preEvaluate(): void { - return null; - } - - // subclasses should overwrite this method to define custom logic - // after code has been evaluated - postEvaluate(): void { - return null; - } - - checkId() { - if (!this.id) this.id = 'py-' + guidGenerator(); - } - - getSourceFromElement(): string { - return ''; - } - - async getSourceFromFile(s: string): Promise { - const response = await fetch(s); - this.code = await response.text(); - return this.code; - } - - protected async _register_esm(pyodide: PyodideInterface): Promise { - const imports: { [key: string]: unknown } = {}; - - for (const node of document.querySelectorAll("script[type='importmap']")) { - const importmap = (() => { - try { - return JSON.parse(node.textContent); - } catch { - return null; - } - })(); - - if (importmap?.imports == null) continue; - - for (const [name, url] of Object.entries(importmap.imports)) { - if (typeof name != 'string' || typeof url != 'string') continue; - - try { - // XXX: pyodide doesn't like Module(), failing with - // "can't read 'name' of undefined" at import time - imports[name] = { ...(await import(url)) }; - } catch { - console.error(`failed to fetch '${url}' for '${name}'`); - } - } - } - - pyodide.registerJsModule('esm', imports); - } - - async evaluate(): Promise { - console.log('evaluate'); - this.preEvaluate(); - - const pyodide = runtime; - let source: string; - let output; - try { - source = this.source ? await this.getSourceFromFile(this.source) - : this.getSourceFromElement(); - - await this._register_esm(pyodide); - - if (source.includes('asyncio')) { - await pyodide.runPythonAsync( - `output_manager.change(out="${this.outputElement.id}", err="${this.errorElement.id}", append=${this.appendOutput ? 'True' : 'False'})`, - ); - output = await pyodide.runPythonAsync(source); - await pyodide.runPythonAsync(`output_manager.revert()`); - } else { - output = pyodide.runPython( - `output_manager.change(out="${this.outputElement.id}", err="${this.errorElement.id}", append=${this.appendOutput ? 'True' : 'False'})`, - ); - output = pyodide.runPython(source); - pyodide.runPython(`output_manager.revert()`); - } - - if (output !== undefined) { - if (Element === undefined) { - Element = pyodide.globals.get('Element'); - } - const out = Element(this.outputElement.id); - out.write.callKwargs(output, { append: this.appendOutput }); - - this.outputElement.hidden = false; - this.outputElement.style.display = 'block'; - } - - // check if this REPL contains errors, delete them and remove error classes - const errorElements = document.querySelectorAll(`div[id^='${this.errorElement.id}'][error]`); - if (errorElements.length > 0) { - for (const errorElement of errorElements) { - errorElement.classList.add('hidden'); - if (this.hasAttribute('std-err')) { - this.errorElement.hidden = true; - this.errorElement.style.removeProperty('display'); - } - } - } - removeClasses(this.errorElement, ['bg-red-200', 'p-2']); - - this.postEvaluate(); - } catch (err) { - if (Element === undefined) { - Element = pyodide.globals.get('Element'); - } - const out = Element(this.errorElement.id); - - addClasses(this.errorElement, ['bg-red-200', 'p-2']); - out.write.callKwargs(err, { append: this.appendOutput }); - - this.errorElement.children[this.errorElement.children.length - 1].setAttribute('error', ''); - this.errorElement.hidden = false; - this.errorElement.style.display = 'block'; - } - } // end evaluate - - async eval(source: string): Promise { - let output; - const pyodide = runtime; - - try { - output = await pyodide.runPythonAsync(source); - if (output !== undefined) { - console.log(output); - } - } catch (err) { - console.log(err); - } - } // end eval -} - -function createWidget(name: string, code: string, klass: string) { - class CustomWidget extends HTMLElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - - name: string = name; - klass: string = klass; - code: string = code; - proxy: any; - proxyClass: any; - - constructor() { - super(); - - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - } - - connectedCallback() { - // TODO: we are calling with a 2secs delay to allow pyodide to load - // ideally we can just wait for it to load and then run. To do - // so we need to replace using the promise and actually using - // the interpreter after it loads completely - // setTimeout(async () => { - // await this.eval(this.code); - // this.proxy = this.proxyClass(this); - // console.log('proxy', this.proxy); - // this.proxy.connect(); - // this.registerWidget(); - // }, 2000); - pyodideLoaded.subscribe(value => { - console.log('RUNTIME READY', value); - if ('runPythonAsync' in value) { - runtime = value; - setTimeout(async () => { - await this.eval(this.code); - this.proxy = this.proxyClass(this); - console.log('proxy', this.proxy); - this.proxy.connect(); - this.registerWidget(); - }, 1000); - } - }); - } - - registerWidget() { - const pyodide = runtime; - console.log('new widget registered:', this.name); - pyodide.globals.set(this.id, this.proxy); - } - - async eval(source: string): Promise { - let output; - const pyodide = runtime; - try { - output = await pyodide.runPythonAsync(source); - this.proxyClass = pyodide.globals.get(this.klass); - if (output !== undefined) { - console.log(output); - } - } catch (err) { - console.log(err); - } - } - } -} - -export class PyWidget extends HTMLElement { - shadow: ShadowRoot; - name: string; - klass: string; - outputElement: HTMLElement; - errorElement: HTMLElement; - wrapper: HTMLElement; - theme: string; - source: string; - code: string; - - constructor() { - super(); - - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - - if (this.hasAttribute('src')) { - this.source = this.getAttribute('src'); - } - - if (this.hasAttribute('name')) { - this.name = this.getAttribute('name'); - } - - if (this.hasAttribute('klass')) { - this.klass = this.getAttribute('klass'); - } - } - - async connectedCallback() { - if (this.id === undefined) { - throw new ReferenceError( - `No id specified for component. Components must have an explicit id. Please use id="" to specify your component id.`, - ); - } - - const mainDiv = document.createElement('div'); - mainDiv.id = this.id + '-main'; - this.appendChild(mainDiv); - console.log('reading source'); - this.code = await this.getSourceFromFile(this.source); - createWidget(this.name, this.code, this.klass); - } - - initOutErr(): void { - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - - // in this case, the default output-mode is append, if hasn't been specified - if (!this.hasAttribute('output-mode')) { - this.setAttribute('output-mode', 'append'); - } - } else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - this.outputElement = document.createElement('div'); - this.outputElement.classList.add('output'); - this.outputElement.hidden = true; - this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); - } - - if (this.hasAttribute('std-err')) { - this.errorElement = document.getElementById(this.getAttribute('std-err')); - } else { - this.errorElement = this.outputElement; - } - } - } - - async getSourceFromFile(s: string): Promise { - const pyodide = runtime; - const response = await fetch(s); - return await response.text(); - } - - async eval(source: string): Promise { - let output; - const pyodide = runtime; - try { - output = await pyodide.runPythonAsync(source); - if (output !== undefined) { - console.log(output); - } - } catch (err) { - console.log(err); - } - } -} diff --git a/pyscriptjs/src/components/pybox.ts b/pyscriptjs/src/components/pybox.ts deleted file mode 100644 index 6c3782c2e1d..00000000000 --- a/pyscriptjs/src/components/pybox.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { addClasses } from '../utils'; - -export class PyBox extends HTMLElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - theme: string; - widths: Array; - - constructor() { - super(); - - // attach shadow so we can preserve the element original innerHtml content - this.shadow = this.attachShadow({ mode: 'open' }); - - this.wrapper = document.createElement('slot'); - this.shadow.appendChild(this.wrapper); - } - - connectedCallback() { - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['flex', 'mx-8']); - - // Hack: for some reason when moving children, the editor box duplicates children - // meaning that we end up with 2 editors, if there's a inside the - // so, if we have more than 2 children with the cm-editor class, we remove one of them - while (this.childNodes.length > 0) { - console.log(this.firstChild); - if (this.firstChild.nodeName == 'PY-REPL') { - // in this case we need to remove the child and create a new one from scratch - const replDiv = document.createElement('div'); - // we need to put the new repl inside a div so that if the repl has auto-generate true - // it can replicate itself inside that constrained div - replDiv.appendChild(this.firstChild.cloneNode()); - mainDiv.appendChild(replDiv); - this.firstChild.remove(); - } else { - if (this.firstChild.nodeName != '#text') { - mainDiv.appendChild(this.firstChild); - } else { - this.firstChild.remove(); - } - } - } - - // now we need to set widths - this.widths = []; - if (this.hasAttribute('widths')) { - for (const w of this.getAttribute('widths').split(';')) { - this.widths.push(`w-${w}`); - } - } else { - this.widths = [...this.widths, ...[`w-1/${mainDiv.childNodes.length}`]]; - } - - this.widths.forEach((width, index) => { - const node: ChildNode = mainDiv.childNodes[index]; - addClasses(node as HTMLElement, [width, 'mx-1']); - }); - - this.appendChild(mainDiv); - console.log('py-box connected'); - } -} diff --git a/pyscriptjs/src/components/pybutton.ts b/pyscriptjs/src/components/pybutton.ts deleted file mode 100644 index 0d1d3484e5b..00000000000 --- a/pyscriptjs/src/components/pybutton.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { BaseEvalElement } from './base'; -import { addClasses, htmlDecode } from '../utils'; - -export class PyButton extends BaseEvalElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - theme: string; - widths: Array; - label: string; - class: Array; - defaultClass: Array; - mount_name: string; - constructor() { - super(); - - this.defaultClass = ['p-2', 'text-white', 'bg-blue-600', 'border', 'border-blue-600', 'rounded']; - - if (this.hasAttribute('label')) { - this.label = this.getAttribute('label'); - } - - // Styling does the same thing as class in normal HTML. Using the name "class" makes the style to malfunction - if (this.hasAttribute('styling')) { - const klass = this.getAttribute('styling').trim(); - if (klass === '') { - this.class = this.defaultClass; - } else { - // trim each element to remove unnecessary spaces which makes the button style to malfunction - this.class = klass - .split(' ') - .map(x => x.trim()) - .filter(x => x !== ''); - } - } else { - this.class = this.defaultClass; - } - } - - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - - const mainDiv = document.createElement('button'); - mainDiv.innerHTML = this.label; - addClasses(mainDiv, this.class); - - mainDiv.id = this.id; - this.id = `${this.id}-container`; - - this.appendChild(mainDiv); - this.code = this.code.split('self').join(this.mount_name); - let registrationCode = `from pyodide import create_proxy`; - registrationCode += `\n${this.mount_name} = Element("${mainDiv.id}")`; - if (this.code.includes('def on_focus')) { - this.code = this.code.replace('def on_focus', `def on_focus_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('focus', create_proxy(on_focus_${this.mount_name}))`; - } - - if (this.code.includes('def on_click')) { - this.code = this.code.replace('def on_click', `def on_click_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('click', create_proxy(on_click_${this.mount_name}))`; - } - - // now that we appended and the element is attached, lets connect with the event handlers - // defined for this widget - setTimeout(async () => { - await this.eval(this.code); - await this.eval(registrationCode); - console.log('registered handlers'); - }, 4000); - - console.log('py-button connected'); - } -} diff --git a/pyscriptjs/src/components/pyconfig.ts b/pyscriptjs/src/components/pyconfig.ts deleted file mode 100644 index c0333bcaf79..00000000000 --- a/pyscriptjs/src/components/pyconfig.ts +++ /dev/null @@ -1,195 +0,0 @@ -import * as jsyaml from 'js-yaml'; -import { BaseEvalElement } from './base'; -import { - initializers, - loadedEnvironments, - mode, - postInitializers, - pyodideLoaded, - scriptsQueue, - globalLoader, - appConfig, - Initializer, -} from '../stores'; -import { loadInterpreter } from '../interpreter'; -import type { PyScript } from './pyscript'; - -const DEFAULT_RUNTIME = { - src: 'https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js', - name: 'pyodide-default', - lang: 'python', -}; - -export type Runtime = { - src: string; - name?: string; - lang?: string; -}; - -export type AppConfig = { - autoclose_loader: boolean; - name?: string; - version?: string; - runtimes?: Array; -}; - -let appConfig_: AppConfig = { - autoclose_loader: true, -}; - -appConfig.subscribe((value: AppConfig) => { - if (value) { - appConfig_ = value; - } - console.log('config set!'); -}); - -let initializers_: Initializer[]; -initializers.subscribe((value: Initializer[]) => { - initializers_ = value; - console.log('initializers set'); -}); - -let postInitializers_: Initializer[]; -postInitializers.subscribe((value: Initializer[]) => { - postInitializers_ = value; - console.log('post initializers set'); -}); - -let scriptsQueue_: PyScript[]; -scriptsQueue.subscribe((value: PyScript[]) => { - scriptsQueue_ = value; - console.log('post initializers set'); -}); - -let mode_: string; -mode.subscribe((value: string) => { - mode_ = value; - console.log('post initializers set'); -}); - -let pyodideReadyPromise; -let loader; - -globalLoader.subscribe(value => { - loader = value; -}); - -export class PyodideRuntime extends Object { - src: string; - - constructor(url: string) { - super(); - this.src = url; - } - - async initialize() { - loader.log('Loading runtime...'); - pyodideReadyPromise = loadInterpreter(this.src); - const pyodide = await pyodideReadyPromise; - const newEnv = { - id: 'a', - promise: pyodideReadyPromise, - runtime: pyodide, - state: 'loading', - }; - pyodideLoaded.set(pyodide); - - // Inject the loader into the runtime namespace - pyodide.globals.set('pyscript_loader', loader); - - loader.log('Runtime created...'); - loadedEnvironments.update((value: any): any => { - value[newEnv['id']] = newEnv; - }); - - // now we call all initializers before we actually executed all page scripts - loader.log('Initializing components...'); - for (const initializer of initializers_) { - await initializer(); - } - - // now we can actually execute the page scripts if we are in play mode - loader.log('Initializing scripts...'); - if (mode_ == 'play') { - for (const script of scriptsQueue_) { - script.evaluate(); - } - scriptsQueue.set([]); - } - - // now we call all post initializers AFTER we actually executed all page scripts - loader.log('Running post initializers...'); - - if (appConfig_ && appConfig_.autoclose_loader) { - loader.close(); - console.log('------ loader closed ------'); - } - - setTimeout(() => { - for (const initializer of postInitializers_) { - initializer(); - } - }, 3000); - } -} - -export class PyConfig extends BaseEvalElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - theme: string; - widths: Array; - label: string; - mount_name: string; - details: HTMLElement; - operation: HTMLElement; - code: string; - values: AppConfig; - constructor() { - super(); - } - - connectedCallback() { - this.code = this.innerHTML; - this.innerHTML = ''; - - const loadedValues = jsyaml.load(this.code); - if (loadedValues === undefined) { - this.values = { - autoclose_loader: true, - }; - } else { - this.values = Object.assign({}, ...loadedValues); - } - if (this.values.runtimes === undefined) { - this.values.runtimes = [DEFAULT_RUNTIME]; - } - appConfig.set(this.values); - console.log('config set', this.values); - - this.loadRuntimes(); - } - - log(msg: string) { - const newLog = document.createElement('p'); - newLog.innerText = msg; - this.details.appendChild(newLog); - } - - close() { - this.remove(); - } - - loadRuntimes() { - console.log('Initializing runtimes...'); - for (const runtime of this.values.runtimes) { - const script = document.createElement('script'); // create a script DOM node - const runtimeSpec = new PyodideRuntime(runtime.src); - script.src = runtime.src; // set its src to the provided URL - script.addEventListener('load', () => { - void runtimeSpec.initialize(); - }); - document.head.appendChild(script); - } - } -} diff --git a/pyscriptjs/src/components/pyenv.ts b/pyscriptjs/src/components/pyenv.ts deleted file mode 100644 index 84be82935e0..00000000000 --- a/pyscriptjs/src/components/pyenv.ts +++ /dev/null @@ -1,80 +0,0 @@ -import * as jsyaml from 'js-yaml'; - -import { pyodideLoaded, addInitializer } from '../stores'; -import { loadPackage, loadFromFile } from '../interpreter'; -import { handleFetchError } from '../utils'; - -// Premise used to connect to the first available pyodide interpreter -let pyodideReadyPromise; -let runtime; - -pyodideLoaded.subscribe(value => { - runtime = value; - console.log('RUNTIME READY'); -}); - -export class PyEnv extends HTMLElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - code: string; - environment: unknown; - runtime: any; - env: string[]; - paths: string[]; - - constructor() { - super(); - - this.shadow = this.attachShadow({ mode: 'open' }); - this.wrapper = document.createElement('slot'); - } - - connectedCallback() { - this.code = this.innerHTML; - this.innerHTML = ''; - - const env: string[] = []; - const paths: string[] = []; - - this.environment = jsyaml.load(this.code); - if (this.environment === undefined) return; - - for (const entry of Array.isArray(this.environment) ? this.environment : []) { - if (typeof entry == 'string') { - env.push(entry); - } else if (entry && typeof entry === 'object') { - const obj = >entry; - for (const path of Array.isArray(obj.paths) ? obj.paths : []) { - if (typeof path === 'string') { - paths.push(path); - } - } - } - } - - this.env = env; - this.paths = paths; - - async function loadEnv() { - await loadPackage(env, runtime); - console.log('environment loaded'); - } - - async function loadPaths() { - for (const singleFile of paths) { - console.log(`loading ${singleFile}`); - try { - await loadFromFile(singleFile, runtime); - } catch (e) { - //Should we still export full error contents to console? - handleFetchError(e, singleFile); - } - } - console.log('paths loaded'); - } - - addInitializer(loadEnv); - addInitializer(loadPaths); - console.log('environment loading...', this.env); - } -} diff --git a/pyscriptjs/src/components/pyinputbox.ts b/pyscriptjs/src/components/pyinputbox.ts deleted file mode 100644 index e86a721fb12..00000000000 --- a/pyscriptjs/src/components/pyinputbox.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { BaseEvalElement } from './base'; -import { addClasses, htmlDecode } from '../utils'; - -export class PyInputBox extends BaseEvalElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - theme: string; - widths: Array; - label: string; - mount_name: string; - constructor() { - super(); - - if (this.hasAttribute('label')) { - this.label = this.getAttribute('label'); - } - } - - connectedCallback() { - this.checkId(); - this.code = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - - const mainDiv = document.createElement('input'); - mainDiv.type = 'text'; - addClasses(mainDiv, ['border', 'flex-1', 'w-full', 'mr-3', 'border-gray-300', 'p-2', 'rounded']); - - mainDiv.id = this.id; - this.id = `${this.id}-container`; - this.appendChild(mainDiv); - - // now that we appended and the element is attached, lets connect with the event handlers - // defined for this widget - this.appendChild(mainDiv); - this.code = this.code.split('self').join(this.mount_name); - let registrationCode = `from pyodide import create_proxy`; - registrationCode += `\n${this.mount_name} = Element("${mainDiv.id}")`; - if (this.code.includes('def on_keypress')) { - this.code = this.code.replace('def on_keypress', `def on_keypress_${this.mount_name}`); - registrationCode += `\n${this.mount_name}.element.addEventListener('keypress', create_proxy(on_keypress_${this.mount_name}))`; - } - - // TODO: For now we delay execution to allow pyodide to load but in the future this - // should really wait for it to load.. - setTimeout(async () => { - await this.eval(this.code); - await this.eval(registrationCode); - console.log('registered handlers'); - }, 4000); - } -} diff --git a/pyscriptjs/src/components/pyloader.ts b/pyscriptjs/src/components/pyloader.ts deleted file mode 100644 index e8909331c78..00000000000 --- a/pyscriptjs/src/components/pyloader.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { BaseEvalElement } from './base'; - -export class PyLoader extends BaseEvalElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - theme: string; - widths: Array; - label: string; - mount_name: string; - details: HTMLElement; - operation: HTMLElement; - constructor() { - super(); - } - - connectedCallback() { - this.innerHTML = `
-
-
-
-
-
-
`; - this.mount_name = this.id.split('-').join('_'); - this.operation = document.getElementById('pyscript-operation'); - this.details = document.getElementById('pyscript-operation-details'); - } - - log(msg: string) { - const newLog = document.createElement('p'); - newLog.innerText = msg; - this.details.appendChild(newLog); - } - - close() { - this.remove(); - } -} diff --git a/pyscriptjs/src/components/pyrepl.ts b/pyscriptjs/src/components/pyrepl.ts deleted file mode 100644 index c6ccd34f93d..00000000000 --- a/pyscriptjs/src/components/pyrepl.ts +++ /dev/null @@ -1,231 +0,0 @@ -import { basicSetup, EditorState, EditorView } from '@codemirror/basic-setup'; -import { python } from '@codemirror/lang-python'; -import { Compartment, StateCommand } from '@codemirror/state'; -import { keymap } from '@codemirror/view'; -import { defaultKeymap } from '@codemirror/commands'; -import { oneDarkTheme } from '@codemirror/theme-one-dark'; - -import { componentDetailsNavOpen, loadedEnvironments, mode, pyodideLoaded } from '../stores'; -import { addClasses } from '../utils'; -import { BaseEvalElement } from './base'; - -// Premise used to connect to the first available pyodide interpreter - -let pyodideReadyPromise; -let environments; -let currentMode; - -pyodideLoaded.subscribe(value => { - pyodideReadyPromise = value; -}); - -loadedEnvironments.subscribe(value => { - environments = value; -}); - -let propertiesNavOpen; -componentDetailsNavOpen.subscribe(value => { - propertiesNavOpen = value; -}); - -mode.subscribe(value => { - currentMode = value; -}); - -function createCmdHandler(el: PyRepl): StateCommand { - // Creates a codemirror cmd handler that calls the el.evaluate when an event - // triggers that specific cmd - return () => { - void el.evaluate(); - return true; - }; -} - -let initialTheme: string; -function getEditorTheme(el: BaseEvalElement): string { - return initialTheme || (initialTheme = el.getAttribute('theme')); -} - -export class PyRepl extends BaseEvalElement { - editor: EditorView; - editorNode: HTMLElement; - - constructor() { - super(); - - // add an extra div where we can attach the codemirror editor - this.editorNode = document.createElement('div'); - addClasses(this.editorNode, ['editor-box', 'border', 'border-gray-300', 'group', 'relative']); - this.shadow.appendChild(this.wrapper); - } - - connectedCallback() { - this.checkId(); - this.code = this.innerHTML; - this.innerHTML = ''; - const languageConf = new Compartment(); - - const extensions = [ - basicSetup, - languageConf.of(python()), - keymap.of([ - ...defaultKeymap, - { key: 'Ctrl-Enter', run: createCmdHandler(this) }, - { key: 'Shift-Enter', run: createCmdHandler(this) }, - ]), - ]; - - if (getEditorTheme(this) === 'dark') { - extensions.push(oneDarkTheme); - } - - this.editor = new EditorView({ - state: EditorState.create({ - doc: this.code.trim(), - extensions, - }), - parent: this.editorNode, - }); - - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['parentBox', 'flex', 'flex-col', 'mt-2', 'mx-8', 'relative']); - - // Styles that we use to hide the labels whilst also keeping it accessible for screen readers - const labelStyle = 'overflow:hidden; display:block; width:1px; height:1px'; - - // Code editor Label - this.editorNode.id = 'code-editor'; - const editorLabel = document.createElement('label'); - editorLabel.innerHTML = 'Python Script Area'; - editorLabel.setAttribute('style', labelStyle); - editorLabel.htmlFor = 'code-editor'; - - mainDiv.append(editorLabel); - - // add Editor to main PyScript div - mainDiv.appendChild(this.editorNode); - - // Play Button - this.btnRun = document.createElement('button'); - this.btnRun.id = 'btnRun'; - this.btnRun.innerHTML = - ''; - addClasses(this.btnRun, ['absolute', 'right-1', 'bottom-1', 'opacity-0', 'group-hover:opacity-100']); - - // Play Button Label - const btnLabel = document.createElement('label'); - btnLabel.innerHTML = 'Python Script Run Button'; - btnLabel.setAttribute('style', labelStyle); - btnLabel.htmlFor = 'btnRun'; - - this.editorNode.appendChild(btnLabel); - this.editorNode.appendChild(this.btnRun); - - this.btnRun.addEventListener('click', () => { - void this.evaluate(); - }); - - if (!this.id) { - console.log( - "WARNING: define with an id. should always have an id. More than one on a page won't work otherwise!", - ); - } - - if (!this.hasAttribute('exec-id')) { - this.setAttribute('exec-id', '1'); - } - - if (!this.hasAttribute('root')) { - this.setAttribute('root', this.id); - } - - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - } else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - this.outputElement = document.createElement('div'); - this.outputElement.classList.add('output', 'font-mono', 'ml-8', 'text-sm'); - this.outputElement.hidden = true; - this.outputElement.id = this.id + '-' + this.getAttribute('exec-id'); - - // add the output div id if there's not output pre-defined - mainDiv.appendChild(this.outputElement); - } - - this.errorElement = this.hasAttribute('std-err') - ? document.getElementById(this.getAttribute('std-err')) - : this.outputElement; - } - - this.appendChild(mainDiv); - this.editor.focus(); - console.log('connected'); - } - - addToOutput(s: string): void { - this.outputElement.innerHTML += '
' + s + '
'; - this.outputElement.hidden = false; - } - - preEvaluate(): void { - this.setOutputMode("replace"); - if(!this.appendOutput) { - this.outputElement.innerHTML = ''; - } - } - - postEvaluate(): void { - this.outputElement.hidden = false; - this.outputElement.style.display = 'block'; - - if (this.hasAttribute('auto-generate')) { - const allPyRepls = document.querySelectorAll(`py-repl[root='${this.getAttribute('root')}'][exec-id]`); - const lastRepl = allPyRepls[allPyRepls.length - 1]; - const lastExecId = lastRepl.getAttribute('exec-id'); - const nextExecId = parseInt(lastExecId) + 1; - - const newPyRepl = document.createElement('py-repl'); - newPyRepl.setAttribute('root', this.getAttribute('root')); - newPyRepl.id = this.getAttribute('root') + '-' + nextExecId.toString(); - - if(this.hasAttribute('auto-generate')) { - newPyRepl.setAttribute('auto-generate', ''); - this.removeAttribute('auto-generate'); - } - - if(this.hasAttribute('output-mode')) { - newPyRepl.setAttribute('output-mode', this.getAttribute('output-mode')); - } - - const addReplAttribute = (attribute: string) => { - if (this.hasAttribute(attribute)) { - newPyRepl.setAttribute(attribute, this.getAttribute(attribute)); - } - }; - - addReplAttribute('output'); - addReplAttribute('std-out'); - addReplAttribute('std-err'); - - newPyRepl.setAttribute('exec-id', nextExecId.toString()); - this.parentElement.appendChild(newPyRepl); - } - } - - getSourceFromElement(): string { - const sourceStrings = [ - `output_manager.change(out="${this.outputElement.id}", append=True)`, - ...this.editor.state.doc.toString().split('\n'), - ]; - - return sourceStrings.join('\n'); - } - - render() { - console.log('rendered'); - } -} diff --git a/pyscriptjs/src/components/pyscript.ts b/pyscriptjs/src/components/pyscript.ts deleted file mode 100644 index bf13da167f4..00000000000 --- a/pyscriptjs/src/components/pyscript.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { - addInitializer, - addPostInitializer, - addToScriptsQueue, - loadedEnvironments, - mode, - pyodideLoaded, -} from '../stores'; -import { addClasses, htmlDecode } from '../utils'; -import { BaseEvalElement } from './base'; - -// Premise used to connect to the first available pyodide interpreter -let pyodideReadyPromise; -let environments; -let currentMode; - -pyodideLoaded.subscribe(value => { - pyodideReadyPromise = value; -}); -loadedEnvironments.subscribe(value => { - environments = value; -}); - -mode.subscribe(value => { - currentMode = value; -}); - -// TODO: use type declaractions -type PyodideInterface = { - registerJsModule(name: string, module: object): void; -}; - -export class PyScript extends BaseEvalElement { - constructor() { - super(); - - // add an extra div where we can attach the codemirror editor - this.shadow.appendChild(this.wrapper); - } - - connectedCallback() { - this.checkId(); - this.code = this.innerHTML; - this.innerHTML = ''; - - const mainDiv = document.createElement('div'); - addClasses(mainDiv, ['parentBox', 'flex', 'flex-col', 'mx-8']); - // add Editor to main PyScript div - - if (this.hasAttribute('output')) { - this.errorElement = this.outputElement = document.getElementById(this.getAttribute('output')); - - // in this case, the default output-mode is append, if hasn't been specified - if (!this.hasAttribute('output-mode')) { - this.setAttribute('output-mode', 'append'); - } - } else { - if (this.hasAttribute('std-out')) { - this.outputElement = document.getElementById(this.getAttribute('std-out')); - } else { - // In this case neither output or std-out have been provided so we need - // to create a new output div to output to - - // Let's check if we have an id first and create one if not - this.outputElement = document.createElement('div'); - const exec_id = this.getAttribute('exec-id'); - this.outputElement.id = this.id + (exec_id ? '-' + exec_id : ''); - - // add the output div id if there's not output pre-defined - mainDiv.appendChild(this.outputElement); - } - - if (this.hasAttribute('std-err')) { - this.errorElement = document.getElementById(this.getAttribute('std-err')); - } else { - this.errorElement = this.outputElement; - } - } - - if (currentMode == 'edit') { - // TODO: We need to build a plan for this - this.appendChild(mainDiv); - } else { - this.appendChild(mainDiv); - addToScriptsQueue(this); - } - - console.log('connected'); - - if (this.hasAttribute('src')) { - this.source = this.getAttribute('src'); - } - } - - protected async _register_esm(pyodide: PyodideInterface): Promise { - for (const node of document.querySelectorAll("script[type='importmap']")) { - const importmap = (() => { - try { - return JSON.parse(node.textContent); - } catch { - return null; - } - })(); - - if (importmap?.imports == null) continue; - - for (const [name, url] of Object.entries(importmap.imports)) { - if (typeof name != 'string' || typeof url != 'string') continue; - - let exports: object; - try { - // XXX: pyodide doesn't like Module(), failing with - // "can't read 'name' of undefined" at import time - exports = { ...(await import(url)) }; - } catch { - console.warn(`failed to fetch '${url}' for '${name}'`); - continue; - } - - pyodide.registerJsModule(name, exports); - } - } - } - - getSourceFromElement(): string { - return htmlDecode(this.code); - } -} - -/** Defines all possible pys-on* and their corresponding event types */ -const pysAttributeToEvent: Map = new Map([ - ["pys-onClick", "click"], - ["pys-onKeyDown", "keydown"] -]); - -/** Initialize all elements with pys-on* handlers attributes */ -async function initHandlers() { - console.log('Collecting nodes...'); - const pyodide = await pyodideReadyPromise; - for (const pysAttribute of pysAttributeToEvent.keys()) { - await createElementsWithEventListeners(pyodide, pysAttribute); - } -} - -/** Initializes an element with the given pys-on* attribute and its handler */ -async function createElementsWithEventListeners(pyodide: any, pysAttribute: string) { - const matches: NodeListOf = document.querySelectorAll(`[${pysAttribute}]`); - for (const el of matches) { - if (el.id.length === 0) { - throw new TypeError(`<${el.tagName.toLowerCase()}> must have an id attribute, when using the ${pysAttribute} attribute`) - } - const handlerCode = el.getAttribute(pysAttribute); - const event = pysAttributeToEvent.get(pysAttribute); - const source = ` - from pyodide import create_proxy - Element("${el.id}").element.addEventListener("${event}", create_proxy(${handlerCode})) - `; - await pyodide.runPythonAsync(source); - - // TODO: Should we actually map handlers in JS instead of Python? - // el.onclick = (evt: any) => { - // console.log("click"); - // new Promise((resolve, reject) => { - // setTimeout(() => { - // console.log('Inside') - // }, 300); - // }).then(() => { - // console.log("resolved") - // }); - // // let handlerCode = el.getAttribute('pys-onClick'); - // // pyodide.runPython(handlerCode); - // } - } - -} - -/** Mount all elements with attribute py-mount into the Python namespace */ -async function mountElements() { - console.log('Collecting nodes to be mounted into python namespace...'); - const pyodide = await pyodideReadyPromise; - const matches: NodeListOf = document.querySelectorAll('[py-mount]'); - - let source = ''; - for (const el of matches) { - const mountName = el.getAttribute('py-mount') || el.id.split('-').join('_'); - source += `\n${mountName} = Element("${el.id}")`; - } - await pyodide.runPythonAsync(source); -} -addInitializer(mountElements); -addPostInitializer(initHandlers); diff --git a/pyscriptjs/src/components/pytitle.ts b/pyscriptjs/src/components/pytitle.ts deleted file mode 100644 index ba9687d382c..00000000000 --- a/pyscriptjs/src/components/pytitle.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BaseEvalElement } from './base'; -import { addClasses, htmlDecode } from '../utils'; - -export class PyTitle extends BaseEvalElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - theme: string; - widths: Array; - label: string; - mount_name: string; - constructor() { - super(); - } - - connectedCallback() { - this.label = htmlDecode(this.innerHTML); - this.mount_name = this.id.split('-').join('_'); - this.innerHTML = ''; - - const mainDiv = document.createElement('div'); - const divContent = document.createElement('h1'); - - addClasses(mainDiv, ['text-center', 'w-full', 'mb-8']); - addClasses(divContent, ['text-3xl', 'font-bold', 'text-gray-800', 'uppercase', 'tracking-tight']); - divContent.innerHTML = this.label; - - mainDiv.id = this.id; - this.id = `${this.id}-container`; - mainDiv.appendChild(divContent); - this.appendChild(mainDiv); - } -} diff --git a/pyscriptjs/src/interpreter.ts b/pyscriptjs/src/interpreter.ts deleted file mode 100644 index b70d049312d..00000000000 --- a/pyscriptjs/src/interpreter.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { getLastPath } from './utils'; -// eslint-disable-next-line -// @ts-ignore -import pyscript from './pyscript.py'; - -let pyodideReadyPromise; -let pyodide; - -const loadInterpreter = async function (indexUrl: string): Promise { - console.log('creating pyodide runtime'); - // eslint-disable-next-line - // @ts-ignore - pyodide = await loadPyodide({ - // indexURL: indexUrl, - stdout: console.log, - stderr: console.log, - fullStdLib: false, - }); - - // now that we loaded, add additional convenience functions - console.log('loading micropip'); - await pyodide.loadPackage('micropip'); - - console.log('loading pyscript...'); - await pyodide.runPythonAsync(pyscript); - - console.log('done setting up environment'); - return pyodide; -}; - -const loadPackage = async function (package_name: string[] | string, runtime: any): Promise { - if (package_name.length > 0){ - const micropip = pyodide.globals.get('micropip'); - await micropip.install(package_name); - micropip.destroy(); - } -}; - -const loadFromFile = async function (s: string, runtime: any): Promise { - const filename = getLastPath(s); - await runtime.runPythonAsync( - ` - from pyodide.http import pyfetch - from js import console - - try: - response = await pyfetch("` + - s + - `") - except Exception as err: - console.warn("PyScript: Access to local files (using 'Paths:' in py-env) is not available when directly opening a HTML file; you must use a webserver to serve the additional files. See https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062 on starting a simple webserver with Python.") - raise(err) - content = await response.bytes() - with open("` + - filename + - `", "wb") as f: - f.write(content) - `, - ); -}; - -export { loadInterpreter, pyodideReadyPromise, loadPackage, loadFromFile }; diff --git a/pyscriptjs/src/main.ts b/pyscriptjs/src/main.ts deleted file mode 100644 index 6c0f4c0701d..00000000000 --- a/pyscriptjs/src/main.ts +++ /dev/null @@ -1,42 +0,0 @@ -import App from './App.svelte'; - -import { PyScript } from './components/pyscript'; -import { PyRepl } from './components/pyrepl'; -import { PyEnv } from './components/pyenv'; -import { PyBox } from './components/pybox'; -import { PyButton } from './components/pybutton'; -import { PyTitle } from './components/pytitle'; -import { PyInputBox } from './components/pyinputbox'; -import { PyWidget } from './components/base'; -import { PyLoader } from './components/pyloader'; -import { globalLoader } from './stores'; -import { PyConfig } from './components/pyconfig'; - -const xPyScript = customElements.define('py-script', PyScript); -const xPyRepl = customElements.define('py-repl', PyRepl); -const xPyEnv = customElements.define('py-env', PyEnv); -const xPyBox = customElements.define('py-box', PyBox); -const xPyButton = customElements.define('py-button', PyButton); -const xPyTitle = customElements.define('py-title', PyTitle); -const xPyInputBox = customElements.define('py-inputbox', PyInputBox); -const xPyWidget = customElements.define('py-register-widget', PyWidget); -const xPyLoader = customElements.define('py-loader', PyLoader); -const xPyConfig = customElements.define('py-config', PyConfig); - -// As first thing, loop for application configs -const config: PyConfig = document.querySelector('py-config'); -if (!config) { - const loader = document.createElement('py-config'); - document.body.append(loader); -} - -// add loader to the page body -const loader = document.createElement('py-loader'); -document.body.append(loader); -globalLoader.set(loader); - -const app = new App({ - target: document.body, -}); - -export default app; diff --git a/pyscriptjs/src/pyscript.py b/pyscriptjs/src/pyscript.py deleted file mode 100644 index 3fdf57a8d33..00000000000 --- a/pyscriptjs/src/pyscript.py +++ /dev/null @@ -1,437 +0,0 @@ -import asyncio -import base64 -import io -import sys -import time -from textwrap import dedent - -import micropip # noqa: F401 -from js import console, document - -loop = asyncio.get_event_loop() - -MIME_METHODS = { - "__repr__": "text/plain", - "_repr_html_": "text/html", - "_repr_markdown_": "text/markdown", - "_repr_svg_": "image/svg+xml", - "_repr_png_": "image/png", - "_repr_pdf_": "application/pdf", - "_repr_jpeg_": "image/jpeg", - "_repr_latex": "text/latex", - "_repr_json_": "application/json", - "_repr_javascript_": "application/javascript", - "savefig": "image/png", -} - - -def render_image(mime, value, meta): - data = f"data:{mime};charset=utf-8;base64,{value}" - attrs = " ".join(['{k}="{v}"' for k, v in meta.items()]) - return f'' - - -def identity(value, meta): - return value - - -MIME_RENDERERS = { - "text/plain": identity, - "text/html": identity, - "image/png": lambda value, meta: render_image("image/png", value, meta), - "image/jpeg": lambda value, meta: render_image("image/jpeg", value, meta), - "image/svg+xml": identity, - "application/json": identity, - "application/javascript": lambda value, meta: f"", -} - - -def eval_formatter(obj, print_method): - """ - Evaluates a formatter method. - """ - if print_method == "__repr__": - return repr(obj) - elif hasattr(obj, print_method): - if print_method == "savefig": - buf = io.BytesIO() - obj.savefig(buf, format="png") - buf.seek(0) - return base64.b64encode(buf.read()).decode("utf-8") - return getattr(obj, print_method)() - elif print_method == "_repr_mimebundle_": - return {}, {} - return None - - -def format_mime(obj): - """ - Formats object using _repr_x_ methods. - """ - if isinstance(obj, str): - return obj, "text/plain" - - mimebundle = eval_formatter(obj, "_repr_mimebundle_") - if isinstance(mimebundle, tuple): - format_dict, _ = mimebundle - else: - format_dict = mimebundle - - output, not_available = None, [] - for method, mime_type in reversed(MIME_METHODS.items()): - if mime_type in format_dict: - output = format_dict[mime_type] - else: - output = eval_formatter(obj, method) - - if output is None: - continue - elif mime_type not in MIME_RENDERERS: - not_available.append(mime_type) - continue - break - if output is None: - if not_available: - console.warning( - f"Rendered object requested unavailable MIME renderers: {not_available}" - ) - output = repr(output) - mime_type = "text/plain" - elif isinstance(output, tuple): - output, meta = output - else: - meta = {} - return MIME_RENDERERS[mime_type](output, meta), mime_type - - -class PyScript: - loop = loop - - @staticmethod - def run_until_complete(f): - _ = loop.run_until_complete(f) - - @staticmethod - def write(element_id, value, append=False, exec_id=0): - """Writes value to the element with id "element_id""" - Element(element_id).write(value=value, append=append) - console.warn( - dedent( - """PyScript Deprecation Warning: PyScript.write is - marked as deprecated and will be removed sometime soon. Please, use - Element().write instead.""" - ) - ) - - -class Element: - def __init__(self, element_id, element=None): - self._id = element_id - self._element = element - - @property - def id(self): - return self._id - - @property - def element(self): - """Return the dom element""" - if not self._element: - self._element = document.querySelector(f"#{self._id}") - return self._element - - @property - def value(self): - return self.element.value - - @property - def innerHtml(self): - return self.element.innerHtml - - def write(self, value, append=False): - console.log(f"Element.write: {value} --> {append}") - - out_element_id = self.id - - html, mime_type = format_mime(value) - if html == "\n": - return - - if append: - child = document.createElement("div") - exec_id = self.element.childElementCount + 1 - out_element_id = child.id = f"{self.id}-{exec_id}" - self.element.appendChild(child) - - out_element = document.querySelector(f"#{out_element_id}") - - if mime_type in ("application/javascript", "text/html"): - script_element = document.createRange().createContextualFragment(html) - out_element.appendChild(script_element) - else: - out_element.innerHTML = html - - def clear(self): - if hasattr(self.element, "value"): - self.element.value = "" - else: - self.write("", append=False) - - def select(self, query, from_content=False): - el = self.element - if from_content: - el = el.content - - _el = el.querySelector(query) - if _el: - return Element(_el.id, _el) - else: - console.log(f"WARNING: can't find element matching query {query}") - - def clone(self, new_id=None, to=None): - if new_id is None: - new_id = self.element.id - - clone = self.element.cloneNode(True) - clone.id = new_id - - if to: - to.element.appendChild(clone) - - # Inject it into the DOM - self.element.after(clone) - - return Element(clone.id, clone) - - def remove_class(self, classname): - if isinstance(classname, list): - for cl in classname: - self.remove_class(cl) - else: - self.element.classList.remove(classname) - - def add_class(self, classname): - self.element.classList.add(classname) - - -def add_classes(element, class_list): - for klass in class_list.split(" "): - element.classList.add(klass) - - -def create(what, id_=None, classes=""): - element = document.createElement(what) - if id_: - element.id = id_ - add_classes(element, classes) - return Element(id_, element) - - -class PyWidgetTheme: - def __init__(self, main_style_classes): - self.main_style_classes = main_style_classes - - def theme_it(self, widget): - for klass in self.main_style_classes.split(" "): - widget.classList.add(klass) - - -class PyItemTemplate(Element): - label_fields = None - - def __init__(self, data, labels=None, state_key=None, parent=None): - self.data = data - - self.register_parent(parent) - - if not labels: - labels = list(self.data.keys()) - self.labels = labels - - self.state_key = state_key - - super().__init__(self._id) - - def register_parent(self, parent): - self._parent = parent - if parent: - self._id = f"{self._parent._id}-c-{len(self._parent._children)}" - self.data["id"] = self._id - else: - self._id = None - - def create(self): - console.log("creating section") - new_child = create("section", self._id, "task bg-white my-1") - console.log("creating values") - - console.log("creating innerHtml") - new_child._element.innerHTML = dedent( - f""" - - """ - ) - - console.log("returning") - return new_child - - def on_click(self, evt): - pass - - def pre_append(self): - pass - - def post_append(self): - self.element.click = self.on_click - self.element.onclick = self.on_click - - self._post_append() - - def _post_append(self): - pass - - def strike(self, value, extra=None): - if value: - self.add_class("line-through") - else: - self.remove_class("line-through") - - def render_content(self): - return " - ".join([self.data[f] for f in self.labels]) - - -class PyListTemplate: - theme = PyWidgetTheme("flex flex-col-reverse mt-8 mx-8") - item_class = PyItemTemplate - - def __init__(self, parent): - self.parent = parent - self._children = [] - self._id = self.parent.id - - @property - def children(self): - return self._children - - @property - def data(self): - return [c.data for c in self._children] - - def render_children(self): - binds = {} - for i, c in enumerate(self._children): - txt = c.element.innerHTML - rnd = str(time.time()).replace(".", "")[-5:] - new_id = f"{c.element.id}-{i}-{rnd}" - binds[new_id] = c.element.id - txt = txt.replace(">", f" id='{new_id}'>") - print(txt) - - def foo(evt): - console.log(evt) - evtEl = evt.srcElement - srcEl = Element(binds[evtEl.id]) - srcEl.element.onclick() - evtEl.classList = srcEl.element.classList - - for new_id in binds: - Element(new_id).element.onclick = foo - - def connect(self): - self.md = main_div = document.createElement("div") - main_div.id = self._id + "-list-tasks-container" - - if self.theme: - self.theme.theme_it(main_div) - - self.parent.appendChild(main_div) - - def add(self, *args, **kws): - if not isinstance(args[0], self.item_class): - child = self.item_class(*args, **kws) - else: - child = args[0] - child.register_parent(self) - return self._add(child) - - def _add(self, child_elem): - console.log("appending child", child_elem.element) - self.pre_child_append(child_elem) - child_elem.pre_append() - self._children.append(child_elem) - self.md.appendChild(child_elem.create().element) - child_elem.post_append() - self.child_appended(child_elem) - return child_elem - - def pre_child_append(self, child): - pass - - def child_appended(self, child): - """Overwrite me to define logic""" - pass - - -class OutputCtxManager: - def __init__(self, out=None, output_to_console=True, append=True): - self._out = out - self._prev = out - self.output_to_console = output_to_console - self._append = append - - def change(self, out=None, output_to_console=True, append=True): - self._prev = self._out - self._out = out - self.output_to_console = output_to_console - self._append = append - console.log("----> changed out to", self._out, self._append) - - def revert(self): - console.log("----> reverted") - self._out = self._prev - - def write(self, value): - console.log("writing to", self._out, value, self._append) - if self._out: - Element(self._out).write(value, self._append) - - if self.output_to_console: - console.log(self._out, value) - - -class OutputManager: - def __init__(self, out=None, err=None, output_to_console=True, append=True): - sys.stdout = self._out_manager = OutputCtxManager( - out=out, output_to_console=output_to_console, append=append - ) - sys.stderr = self._err_manager = OutputCtxManager( - out=err, output_to_console=output_to_console, append=append - ) - self.output_to_console = output_to_console - self._append = append - - def change(self, out=None, err=None, output_to_console=True, append=True): - self._out_manager.change( - out=out, output_to_console=output_to_console, append=append - ) - sys.stdout = self._out_manager - self._err_manager.change( - out=err, output_to_console=output_to_console, append=append - ) - sys.stderr = self._err_manager - self.output_to_console = output_to_console - self._append = append - - def revert(self): - self._out_manager.revert() - self._err_manager.revert() - sys.stdout = self._out_manager - sys.stderr = self._err_manager - console.log("----> reverted") - - -pyscript = PyScript() -output_manager = OutputManager() diff --git a/pyscriptjs/src/stores.ts b/pyscriptjs/src/stores.ts deleted file mode 100644 index 1b726a58806..00000000000 --- a/pyscriptjs/src/stores.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { writable } from 'svelte/store'; -import type { PyScript } from './components/pyscript'; - -export type Initializer = () => Promise; - -export const pyodideLoaded = writable({ - loaded: false, - premise: null, -}); - -export const loadedEnvironments = writable([{}]); -export const DEFAULT_MODE = 'play'; - -export const navBarOpen = writable(false); -export const componentsNavOpen = writable(false); -export const componentDetailsNavOpen = writable(false); -export const mainDiv = writable(null); -export const currentComponentDetails = writable([]); -export const mode = writable(DEFAULT_MODE); -export const scriptsQueue = writable([]); -export const initializers = writable([]); -export const postInitializers = writable([]); -export const globalLoader = writable(); -export const appConfig = writable(); - -let scriptsQueue_: PyScript[] = []; -let initializers_: Initializer[] = []; -let postInitializers_: Initializer[] = []; - -scriptsQueue.subscribe(value => { - scriptsQueue_ = value; -}); - -export const addToScriptsQueue = (script: PyScript) => { - scriptsQueue.set([...scriptsQueue_, script]); -}; - -initializers.subscribe(value => { - initializers_ = value; -}); - -export const addInitializer = (initializer: Initializer) => { - console.log('adding initializer', initializer); - initializers.set([...initializers_, initializer]); - console.log('added initializer', initializer); -}; - -postInitializers.subscribe(value => { - postInitializers_ = value; -}); - -export const addPostInitializer = (initializer: Initializer) => { - console.log('adding post initializer', initializer); - postInitializers.set([...postInitializers_, initializer]); - console.log('added post initializer', initializer); -}; diff --git a/pyscriptjs/src/utils.ts b/pyscriptjs/src/utils.ts deleted file mode 100644 index 365f9518bb3..00000000000 --- a/pyscriptjs/src/utils.ts +++ /dev/null @@ -1,83 +0,0 @@ -function addClasses(element: HTMLElement, classes: Array) { - for (const entry of classes) { - element.classList.add(entry); - } -} - -function removeClasses(element: HTMLElement, classes: Array) { - for (const entry of classes) { - element.classList.remove(entry); - } -} - -function getLastPath(str: string): string { - return str.split('\\').pop().split('/').pop(); -} - -function htmlDecode(input: string): string { - const doc = new DOMParser().parseFromString(ltrim(input), 'text/html'); - return doc.documentElement.textContent; -} - -function ltrim(code: string): string { - const lines = code.split('\n'); - if (lines.length == 0) return code; - - const lengths = lines - .filter(line => line.trim().length != 0) - .map(line => { - const [prefix] = line.match(/^\s*/); - return prefix.length; - }); - - const k = Math.min(...lengths); - - return k != 0 ? lines.map(line => line.substring(k)).join('\n') - : code; -} - -function guidGenerator(): string { - const S4 = function (): string { - return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); - }; - return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4(); -} - -/* - * Display a page-wide error message to show that something has gone wrong with - * PyScript or Pyodide during loading. Probably not be used for issues that occur within - * Python scripts, since stderr can be routed to somewhere in the DOM - */ -function showError(msg: string): void { - const warning = document.createElement('div'); - warning.style.backgroundColor = 'LightCoral'; - warning.style.alignContent = 'center'; - warning.style.margin = '4px'; - warning.style.padding = '4px'; - warning.innerHTML = msg; - document.body.prepend(warning); -} - -function handleFetchError(e: Error, singleFile: string) { - //Should we still export full error contents to console? - console.warn('Caught an error in loadPaths:\r\n' + e); - let errorContent: string; - if (e.message.includes('TypeError: Failed to fetch')) { - errorContent = `

PyScript: Access to local files - (using "Paths:" in <py-env>) - is not available when directly opening a HTML file; - you must use a webserver to serve the additional files. - See this reference - on starting a simple webserver with Python.

`; - } else if (e.message.includes('404')) { - errorContent = - `

PyScript: Loading from file ` + - singleFile + - ` failed with error 404 (File not Found). Are your filename and path are correct?

`; - } else { - errorContent = '

PyScript encountered an error while loading from file: ' + e.message + '

'; - } - showError(errorContent); -} - -export { addClasses, removeClasses, getLastPath, ltrim, htmlDecode, guidGenerator, showError, handleFetchError }; diff --git a/pyscriptjs/tailwind.config.js b/pyscriptjs/tailwind.config.js deleted file mode 100644 index 68e58667c9c..00000000000 --- a/pyscriptjs/tailwind.config.js +++ /dev/null @@ -1,29 +0,0 @@ -const { tailwindExtractor } = require("tailwindcss/lib/lib/purgeUnusedStyles"); - -module.exports = { - purge: { - content: ["src/**/*.svelte", "public/index.html"], - options: { - defaultExtractor: (content) => [ - ...tailwindExtractor(content), - ...[...content.matchAll(/(?:class:)*([\w\d-/:%.]+)/gm)].map( - ([_match, group, ..._rest]) => group - ), - ], - keyframes: true, - }, - }, - darkMode: false, // or 'media' or 'class' - theme: { - extend: {}, - container: { - center: true - } - }, - variants: { - extend: { - display: ['group-hover'] - }, - }, - plugins: [], -}; diff --git a/pyscriptjs/tests/__init__.py b/pyscriptjs/tests/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/pyscriptjs/tests/conftest.py b/pyscriptjs/tests/conftest.py deleted file mode 100644 index 2a195364403..00000000000 --- a/pyscriptjs/tests/conftest.py +++ /dev/null @@ -1,44 +0,0 @@ -"""All data required for testing examples""" -import os -import threading -from http.server import HTTPServer as SuperHTTPServer -from http.server import SimpleHTTPRequestHandler -from pathlib import Path - -import pytest - -my_path = Path.cwd() / "examples" -os.chdir(my_path) - - -class HTTPServer(SuperHTTPServer): - """ - Class for wrapper to run SimpleHTTPServer on Thread. - Ctrl +Only Thread remains dead when terminated with C. - Keyboard Interrupt passes. - """ - - def run(self): - try: - self.serve_forever() - except KeyboardInterrupt: - pass - finally: - self.server_close() - - -@pytest.fixture(scope="session") -def http_server(): - host, port = "127.0.0.1", 8080 - base_url = f"http://{host}:{port}" - - # serve_Run forever under thread - server = HTTPServer((host, port), SimpleHTTPRequestHandler) - thread = threading.Thread(None, server.run) - thread.start() - - yield base_url # Transition to test here - - # End thread - server.shutdown() - thread.join() diff --git a/pyscriptjs/tests/test_examples.py b/pyscriptjs/tests/test_examples.py deleted file mode 100644 index 8340d912e7a..00000000000 --- a/pyscriptjs/tests/test_examples.py +++ /dev/null @@ -1,203 +0,0 @@ -"""Each example requires the same three tests: - -- Test that the initial markup loads properly (currently done by testing the - tag's content) -- Testing that pyodide is loading properly -- Testing that the page contains appropriate content after rendering - -The single function iterates through the examples, instantiates one playwright browser -session per example, and runs all three of each example's tests in that same browser -session. - """ - -import math -import re -import time -from urllib.parse import urljoin - -import pytest -from playwright.sync_api import sync_playwright - -MAX_TEST_TIME = 30 # Number of seconds allowed for checking a testing condition -TEST_TIME_INCREMENT = 0.25 # 1/4 second, the length of each iteration -TEST_ITERATIONS = math.ceil( - MAX_TEST_TIME / TEST_TIME_INCREMENT -) # 120 iters of 1/4 second - -# Content that is displayed in the page while pyodide loads -LOADING_MESSAGES = [ - "Loading runtime...", - "Runtime created...", - "Initializing components...", - "Initializing scripts...", -] - -EXAMPLES = [ - "altair", - "bokeh", - "bokeh_interactive", - "d3", - "folium", - "hello_world", - "matplotlib", - "numpy_canvas_fractals", - "panel", - "panel_deckgl", - "panel_kmeans", - "panel_stream", - "repl", - "repl2", - "simple_clock", - "todo", - "todo_pylist", - "toga_freedom", - "webgl_raycaster_index", -] - -TEST_PARAMS = { - "altair": { - "file": "altair.html", - "pattern": '<canvas.*?class=\\"marks\\".*?>', - "title": "Altair", - }, - "bokeh": { - "file": "bokeh.html", - "pattern": '<div.*class=\\"bk\\".*>', - "title": "Bokeh Example", - }, - "bokeh_interactive": { - "file": "bokeh_interactive.html", - "pattern": '<div.*?class=\\"bk\\".*?>', - "title": "Bokeh Example", - }, - "d3": { - "file": "d3.html", - "pattern": "<svg.*?>", - "title": "d3: JavaScript & PyScript visualizations side-by-side", - }, - "folium": {"file": "folium.html", "pattern": "<iframe srcdoc=", "title": "Folium"}, - "hello_world": { - "file": "hello_world.html", - "pattern": "\\d+/\\d+/\\d+, \\d+:\\d+:\\d+", - "title": "PyScript Hello World", - }, - "matplotlib": { - "file": "matplotlib.html", - "pattern": "<img src=['\"]data:image", - "title": "Matplotlib", - }, - "numpy_canvas_fractals": { - "file": "numpy_canvas_fractals.html", - "pattern": "<div.*?id=['\"](mandelbrot|julia|newton)['\"].*?>", - "title": "Visualization of Mandelbrot, Julia and " - "Newton sets with NumPy and HTML5 canvas", - }, - "panel": { - "file": "panel.html", - "pattern": "<div.*?class=['\"]bk-root['\"].*?>", - "title": "Panel Example", - }, - "panel_deckgl": { - "file": "panel_deckgl.html", - "pattern": "<div.*?class=['\"]bk-root['\"].*?>", - "title": "PyScript/Panel DeckGL Demo", - }, - "panel_kmeans": { - "file": "panel_kmeans.html", - "pattern": "<div.*?class=['\"]bk-root['\"].*?>", - "title": "Pyscript/Panel KMeans Demo", - }, - "panel_stream": { - "file": "panel_stream.html", - "pattern": "<div.*?class=['\"]bk-root['\"].*?>", - "title": "PyScript/Panel Streaming Demo", - }, - "repl": {"file": "repl.html", "pattern": "<py-repl.*?>", "title": "REPL"}, - "repl2": { - "file": "repl2.html", - "pattern": "<py-repl.*?>", - "title": "Custom REPL Example", - }, - "simple_clock": { - "file": "simple_clock.html", - "pattern": "\\d+/\\d+/\\d+, \\d+:\\d+:\\d+", - "title": "Simple Clock Demo", - }, - "todo": { - "file": "todo.html", - "pattern": "<input.*?id=['\"]new-task-content['\"].*?>", - "title": "Todo App", - }, - "todo_pylist": { - "file": "todo-pylist.html", - "pattern": "<input.*?id=['\"]new-task-content['\"].*?>", - "title": "Todo App", - }, - "toga_freedom": { - "file": "toga/freedom.html", - "pattern": "<(main|div).*?id=['\"]toga_\\d+['\"].*?>", - "title": ["Loading...", "Freedom Units"], - }, - "webgl_raycaster_index": { - "file": "webgl/raycaster/index.html", - "pattern": "<canvas.*?>", - "title": "Raycaster", - }, -} - - -@pytest.mark.parametrize("example", EXAMPLES) -def test_examples(example, http_server): - - base_url = http_server - example_path = urljoin(base_url, TEST_PARAMS[example]["file"]) - - # Invoke playwright - with sync_playwright() as p: - browser = p.chromium.launch() - page = browser.new_page() - page.goto(example_path) - - # STEP 1: Check page title proper initial loading of the example page - - expected_title = TEST_PARAMS[example]["title"] - if isinstance(expected_title, list): - # One example's title changes so expected_title is a list of possible - # titles in that case - assert page.title() in expected_title # nosec - else: - assert page.title() == expected_title # nosec - - # STEP 2: Test that pyodide is loading via messages displayed during loading - - pyodide_loading = False # Flag to be set to True when condition met - - for _ in range(TEST_ITERATIONS): - time.sleep(TEST_TIME_INCREMENT) - content = page.text_content("*") - for message in LOADING_MESSAGES: - if message in content: - pyodide_loading = True - if pyodide_loading: - break - - assert pyodide_loading # nosec - - # STEP 3: - # Assert that rendering inserts data into the page as expected: search the - # DOM from within the timing loop for a string that is not present in the - # initial markup but should appear by way of rendering - - re_sub_content = re.compile(TEST_PARAMS[example]["pattern"]) - py_rendered = False # Flag to be set to True when condition met - - for _ in range(TEST_ITERATIONS): - time.sleep(TEST_TIME_INCREMENT) - content = page.inner_html("*") - if re_sub_content.search(content): - py_rendered = True - break - - assert py_rendered # nosec - - browser.close() diff --git a/pyscriptjs/tsconfig.json b/pyscriptjs/tsconfig.json deleted file mode 100644 index 5b80dad3746..00000000000 --- a/pyscriptjs/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "display": "Svelte", - "_version": "3.0.0", - - "include": ["src/**/*"], - "exclude": ["node_modules/*", "__sapper__/*", "public/*"], - "compilerOptions": { - "moduleResolution": "node", - "target": "es2017", - "module": "esnext", - /** - Svelte Preprocess cannot figure out whether you have a value or a type, so tell TypeScript - to enforce using `import type` instead of `import` for Types. - */ - "importsNotUsedAsValues": "error", - "isolatedModules": true, - /** - To have warnings/errors of the Svelte compiler at the correct position, - enable source maps by default. - */ - "sourceMap": true, - /** Requests the runtime types from the svelte modules by default. Needed for TS files or else you get errors. */ - "types": ["svelte"], - "strict": false, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true - } -} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000000..c76bb6c4259 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +black==24.10.0 +pre-commit==3.7.1 +python-minifier==2.11.0 +setuptools==72.1.0 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 0116aeb3587..00000000000 --- a/setup.cfg +++ /dev/null @@ -1,9 +0,0 @@ -[codespell] -skip = pyscriptjs/node_modules/*,*.js,*.json - -[flake8] -builtins=Element,PyItemTemplate,PyListTemplate,pyscript -max-complexity = 10 -max-line-length = 100 -show-source = True -statistics = True