diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index 2c19cbee348..2e178927525 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -11,7 +11,9 @@ body: 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. + + 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 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 9c29589f1ef..591e81853a0 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,13 +1,12 @@ ## Description -Please describe the changes in your pull request in few words here. + -### Changes +## Changes -List the changes done to fix a bug or introducing a new feature. + ## Checklist -- [ ] All tests pass locally -- [ ] I have updated `docs/changelog.md` -- [ ] I have created documentation for this(if applicable) +- [ ] 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/workflows/build-unstable.yml b/.github/workflows/build-unstable.yml deleted file mode 100644 index 7eec186e097..00000000000 --- a/.github/workflows/build-unstable.yml +++ /dev/null @@ -1,139 +0,0 @@ -name: "[CI] Build Unstable" - -on: - push: # Only run on merges into main that modify files under pyscriptjs/ and examples/ - branches: - - main - paths: - - pyscriptjs/** - - examples/** - - .github/workflows/build-unstable.yml # Test that workflow works when changed - - pull_request: # Run on any PR that modifies files under pyscriptjs/ and examples/ - branches: - - main - paths: - - pyscriptjs/** - - examples/** - - .github/workflows/build-unstable.yml # Test that workflow works when changed - workflow_dispatch: - -jobs: - BuildAndTest: - runs-on: ubuntu-latest - defaults: - run: - working-directory: pyscriptjs - env: - MINICONDA_PYTHON_VERSION: py38 - MINICONDA_VERSION: 4.11.0 - 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 - run: make build - - - name: TypeScript Tests - run: make test-ts - - - name: Python Tests - run: make test-py - - - name: Integration Tests - run: make test-integration-parallel - - - uses: actions/upload-artifact@v3 - with: - name: pyscript - path: | - pyscriptjs/build/ - if-no-files-found: error - retention-days: 7 - - - uses: actions/upload-artifact@v3 - if: success() || failure() - with: - name: test_results - path: pyscriptjs/test_results - if-no-files-found: error - eslint: - runs-on: ubuntu-latest - defaults: - run: - working-directory: pyscriptjs - 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: npm install - run: npm install - - - name: Eslint - run: npx eslint src -c .eslintrc.js - - Deploy: - runs-on: ubuntu-latest - needs: BuildAndTest - if: github.ref == 'refs/heads/main' # Only deploy on merge into main - permissions: - contents: read - id-token: write - - steps: - - uses: actions/download-artifact@v3 - with: - name: pyscript - path: ./build/ - - # 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: Sync to S3 - run: aws s3 sync --quiet ./build/ s3://pyscript.net/unstable/ diff --git a/.github/workflows/docs-release.yml b/.github/workflows/docs-release.yml deleted file mode 100644 index 2978d7a971b..00000000000 --- a/.github/workflows/docs-release.yml +++ /dev/null @@ -1,62 +0,0 @@ -name: "[Docs] Build Release" - -on: - release: - types: [published] - -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-${{ 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: Sync to S3 - run: aws s3 sync --quiet ./docs/_build/html/ s3://docs.pyscript.net/${{ github.ref_name }}/ - - # Make sure to remove the latest folder so we sync the full docs upon release - - name: Delete latest directory - run: aws s3 rm --recursive s3://docs.pyscript.net/latest/ - - # Note that the files are the same as above, but we want to have folders with - # // AND /latest/ which latest will always point to the latest release - - name: Sync to /latest - run: aws s3 sync --quiet ./docs/_build/html/ s3://docs.pyscript.net/latest/ diff --git a/.github/workflows/docs-review.yml b/.github/workflows/docs-review.yml deleted file mode 100644 index 37ba5b13678..00000000000 --- a/.github/workflows/docs-review.yml +++ /dev/null @@ -1,53 +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: - if: github.repository_owner == 'pyscript' - 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/ diff --git a/.github/workflows/docs-unstable.yml b/.github/workflows/docs-unstable.yml deleted file mode 100644 index 943b1262924..00000000000 --- a/.github/workflows/docs-unstable.yml +++ /dev/null @@ -1,54 +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 }} - - # Sync will only copy changed files - - name: Sync to S3 - run: aws s3 sync --quiet ./docs/_build/html/ s3://docs.pyscript.net/unstable/ diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index 944eeef1100..43fe719dbf1 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -1,32 +1,43 @@ -name: "[CI] Prepare Release" +name: "Prepare Release" on: push: tags: - "[0-9][0-9][0-9][0-9].[0-9][0-9].[0-9]+" # YYYY.MM.MICRO -env: - MINICONDA_PYTHON_VERSION: py38 - MINICONDA_VERSION: 4.11.0 - defaults: run: - working-directory: pyscriptjs + working-directory: ./core jobs: - build: + prepare-release: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install node - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: - node-version: 18.x + 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@v3 + uses: actions/cache@v4 env: cache-name: cache-node-modules with: @@ -38,20 +49,21 @@ jobs: ${{ runner.os }}-build- ${{ runner.os }}- - - name: setup Miniconda - uses: conda-incubator/setup-miniconda@v2 + - name: NPM Install + run: npm install && npx playwright install chromium - - name: Setup Environment - run: make setup + - name: Build + run: npm run build - - name: Build and Test - run: make test + - 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 build folder - run: zip -r -q ./build.zip ./build + - name: Zip dist folder + run: zip -r -q ./build.zip ./dist - name: Prepare Release - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 with: draft: true prerelease: true diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 304fc7592cc..5c605299dbc 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -1,34 +1,45 @@ -name: "[CI] Publish Release" +name: "Publish Release" on: release: types: [published] -env: - MINICONDA_PYTHON_VERSION: py38 - MINICONDA_VERSION: 4.11.0 - defaults: run: - working-directory: pyscriptjs + working-directory: ./core jobs: - build: + publish-release: runs-on: ubuntu-latest permissions: - contents: read id-token: write + contents: read steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install node - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: - node-version: 18.x + 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@v3 + uses: actions/cache@v4 env: cache-name: cache-node-modules with: @@ -40,18 +51,22 @@ jobs: ${{ runner.os }}-build- ${{ runner.os }}- - - name: setup Miniconda - uses: conda-incubator/setup-miniconda@v2 + - name: npm install + run: npm install && npx playwright install chromium + + - name: build + run: npm run build - - name: Setup Environment - run: make setup + - 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: Build and Test - run: make test + - name: Generate release.tar from snapshot and put it in dist/ + working-directory: . + run: tar -cvf ../release.tar * && mv ../release.tar . - # Upload to S3 - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v1.6.1 + uses: aws-actions/configure-aws-credentials@v4 with: aws-region: ${{ secrets.AWS_REGION }} role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }} @@ -59,5 +74,5 @@ jobs: - name: Sync to S3 run: | # Update /latest and create an explicitly versioned directory under releases/YYYY.MM.MICRO/ - aws s3 sync --quiet ./build/ s3://pyscript.net/latest/ - aws s3 sync --quiet ./build/ s3://pyscript.net/releases/${{ github.ref_name }}/ + 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 index e2ef5c982c3..b7f51d52ae7 100644 --- a/.github/workflows/publish-snapshot.yml +++ b/.github/workflows/publish-snapshot.yml @@ -1,5 +1,4 @@ -name: "[CI] Publish Snapshot" -# Copy /unstable/ to /snapshots/2022.09.1.RC1/ +name: "Publish Snapshot" on: workflow_dispatch: @@ -9,18 +8,69 @@ on: type: string required: true +defaults: + run: + working-directory: ./core + jobs: - snapshot: + 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@v1.6.1 + 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 + + - 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 s3://pyscript.net/unstable/ s3://pyscript.net/snapshots/${{ inputs.snapshot_version }}/ + 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 d8ed32b8e22..00000000000 --- a/.github/workflows/sync-examples.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: "[CI] Sync Examples" - -on: - release: - types: [published] - -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/.github/workflows/test_report.yml b/.github/workflows/test_report.yml deleted file mode 100644 index dacbc8e7732..00000000000 --- a/.github/workflows/test_report.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Test Report -on: - workflow_run: - workflows: ['\[CI\] Build Unstable'] - types: - - completed -jobs: - report: - runs-on: ubuntu-latest - steps: - - uses: dorny/test-reporter@v1.6.0 - with: - artifact: test_results - name: Test reports - path: "*.xml" - reporter: java-junit diff --git a/.gitignore b/.gitignore index cc7325e3cee..6ccef40cf9e 100644 --- a/.gitignore +++ b/.gitignore @@ -51,7 +51,6 @@ coverage.xml *.py,cover .hypothesis/ .pytest_cache/ -pyscriptjs/examples # Translations *.mo @@ -141,3 +140,13 @@ 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 ebb46baccd8..b18b22ee168 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,60 +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] + #skip: [eslint] autoupdate_schedule: monthly -default_stages: [commit] +default_stages: [pre-commit] repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + 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 + 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: \.min\.js$ + exclude: core/dist|\.min\.js$ - id: trailing-whitespace - - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.0.257 - hooks: - - id: ruff - args: [--fix] - - repo: https://github.com/psf/black - rev: 23.1.0 + 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.2.4 + 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"] - - - repo: https://github.com/pre-commit/mirrors-eslint - rev: v8.36.0 - hooks: - - id: eslint - files: pyscriptjs/src/.*\.[jt]sx?$ # *.js, *.jsx, *.ts and *.tsx - types: [file] - additional_dependencies: - - eslint@8.25.0 - - typescript@4.8.4 - - "@typescript-eslint/eslint-plugin@5.39.0" - - "@typescript-eslint/parser@5.39.0" diff --git a/.prettierignore b/.prettierignore index 4514e1d7eb6..32b310b5153 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,3 @@ ISSUE_TEMPLATE *.min.* package-lock.json -docs diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index b5324a7e886..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 4fc34f49a0e..8ce2c517a45 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,81 +1,4 @@ # Contributing to PyScript -Thank you for wanting to contribute to the PyScript project! - -## Table of contents - -- [Contributing to PyScript](#contributing-to-pyscript) - - [Table of contents](#table-of-contents) -- [Code of Conduct](#code-of-conduct) -- [Contributing](#contributing) - - [Reporting bugs](#reporting-bugs) - - [Creating useful issues](#creating-useful-issues) - - [Reporting security issues](#reporting-security-issues) - - [Asking questions](#asking-questions) - - [Setting up your local environment and developing](#setting-up-your-local-environment-and-developing) - - [Developing](#developing) - - [Rebasing changes](#rebasing-changes) - - [Building the docs](#building-the-docs) - - [Places to start](#places-to-start) - - [Setting up your local environment and developing](#setting-up-your-local-environment-and-developing) - - [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). - -## 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. - -## Setting up your local environment and developing - -If you would like to contribute to PyScript, you will need to set up a local development environment. The [following instructions](https://docs.pyscript.net/latest/development/setting-up-environment.html) will help you get started. - -You can also read about PyScript's [development process](https://docs.pyscript.net/latest/development/developing.html) to learn how to contribute code to PyScript, how to run tests and what's the PR etiquette of the community! - -## 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/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 d42ec747b0b..ab141aa6186 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -9,13 +9,14 @@ This document lists the Maintainers of the Project. Maintainers may be added onc | Philipp Rudiger | Anaconda, Inc | | Peter Wang | Anaconda, Inc | | Kevin Goldsmith | Anaconda, Inc | -| Mariana Meireles | Anaconda, Inc | +| Mariana Meireles | | | Nicholas H.Tollervey | Anaconda, Inc | | Madhur Tandon | Anaconda, Inc | | Ted Patrick | Anaconda, Inc | -| Jeff Glass | --- | -| Paul Everitt | --- | -| Fabio Rosado | --- | +| Jeff Glass | | +| Paul Everitt | | +| Fabio Rosado | Anaconda, Inc | +| Andrea Giammarchi | Anaconda, Inc | --- 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 15dd62e9b15..130a20e6cbe 100644 --- a/README.md +++ b/README.md @@ -1,56 +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 framework that allows users to create rich Python applications in the browser using HTML's interface and the power of [Pyodide](https://pyodide.org/en/stable/), [WASM](https://webassembly.org/), and modern web technologies. +```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 +For example applications, see [here](https://pyscript.com/@examples). -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. +Other useful resources: -## Try PyScript +- 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 . -To try PyScript, import the appropriate pyscript files into the `` tag of your html page with: +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. -```html - - - - -``` +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. -You can then use PyScript components in your html page. PyScript currently implements the following elements: +For more details on how to join the calls and up to date schedule, consult the +official calendar: -- ``: 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 +- [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). -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. +## Contribute -## How to Contribute +For technical details of the code, please see the [README](core/README.md) in +the `core` directory. -Read the [contributing guide](CONTRIBUTING.md) to learn about our development process, reporting bugs and improvements, creating issues and asking questions. +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. -Check out the [developing process](https://docs.pyscript.net/latest/development/developing.html) documentation for more information on how to setup your development environment. +Check out the [development process](https://docs.pyscript.net/latest/developers/) +documentation for more information on how to setup your development environment. -## Resources - -- [Official docs](https://docs.pyscript.net) -- [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) -- [Discord Channel](https://discord.gg/BYB2kvyFwm) +## Governance -## Notes +The [PyScript organization governance](https://github.com/pyscript/governance) +is documented in a separate repository. -- This is an extremely experimental project, so expect things to break! -- PyScript has been only tested on Chrome at the moment. +## Supporters -## Governance +PyScript is an independent open source project. -The [PyScript organization governance](https://github.com/pyscript/governance) is documented in a separate repository. +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/TROUBLESHOOTING.md b/TROUBLESHOOTING.md deleted file mode 100644 index 4f480bb3b04..00000000000 --- a/TROUBLESHOOTING.md +++ /dev/null @@ -1,19 +0,0 @@ -# Troubleshooting - -This page is meant for troubleshooting common problems with PyScript. - -## Table of contents: - -- [Make Setup](#make-setup) - -## Make setup - -A lot of problems related to `make setup` are related to node and npm being outdated. Once npm and node are updated, `make setup` should work. You can follow the steps on the [npm documentation](https://docs.npmjs.com/try-the-latest-stable-version-of-npm) to update npm (the update command for Linux should work for Mac as well). Once npm has been updated you can continue to the instructions to update node below. - -To update Node run the following commands in order (Most likely you'll be prompted for your user password, this is normal): - -``` -sudo npm cache clean -f -sudo npm install -g n -sudo n stable -``` 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 af47bc08f96..00000000000 --- a/docs/Makefile +++ /dev/null @@ -1,46 +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: html - @echo 'visit docs at http://localhost:8080' - python -m http.server -d "$(BUILDDIR)/html/" 8080 - -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 59dd0d2ac40..00000000000 --- a/docs/README.md +++ /dev/null @@ -1,54 +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) - -## Documentation Principles - -The PyScript documentation is based on a documentation framework called [Diátaxis](https://diataxis.fr/). This framework helps to solve the problem of structure in technical documentation and identifies four modes of documentation - **tutorials, how-to guides, technical reference and explanation**. Each one of these modes answers to a different user need, fulfills a different purpose and requires a different approach to its creation. - -The picture below gives a good visual representation of that separation of concerns: - -![pyodide-pyscript](./img/diataxis.png) - -So, please keep that in mind when contributing to the project documentation. For more information on, make sure to check [their website](https://diataxis.fr/). - -### 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 -static files like templates and themes, to build the static end result. - -### Build - -To learn how to build the docs, head over the [CONTRIBUTING](../CONTRIBUTING.md) page. - - -## Cross-referencing - -You can link to other pages in the documentation by using the `{doc}` role. For example, to link to the `docs/README.md` file, you would use: - -```markdown -{doc}`docs/README.md` -``` - -You can also cross-reference the python glossary by using the `{term}` role. For example, to link to the `iterable` term, you would use: - -```markdown -{term}`iterable` -``` - -You can also cross-reference functions, methods or data attributes by using the `{attr}` for example: - -```markdown -{py:func}`repr` -``` - -This would link to the `repr` function in the python builtins. diff --git a/docs/_static/examples/what-is-pyscript.html b/docs/_static/examples/what-is-pyscript.html deleted file mode 100644 index 368cef2032d..00000000000 --- a/docs/_static/examples/what-is-pyscript.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - -

Let's plot random numbers

-
-
-

❰py❱

-
-
- - - packages = [ - "numpy", - "matplotlib" - ] - - - -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/pyscript.svg b/docs/_static/images/pyscript.svg deleted file mode 100644 index 8d32dcac5c7..00000000000 --- a/docs/_static/images/pyscript.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - 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/changelog.md b/docs/changelog.md deleted file mode 100644 index 323f34e1151..00000000000 --- a/docs/changelog.md +++ /dev/null @@ -1,78 +0,0 @@ -# Release Notes - -2023.XX.X -========= - - -Features --------- - -- The `py-mount` attribute on HTML elements has been deprecated, and will be removed in a future release. - - -### <py-terminal> -- Added a `docked` field and attribute for the `` custom element, enabled by default when the terminal is in `auto` mode, and able to dock the terminal at the bottom of the page with auto scroll on new code execution. - -### <py-script> -- Restored the `output` attribute of `py-script` tags to route `sys.stdout` to a DOM element with the given ID. ([#1063](https://github.com/pyscript/pyscript/pull/1063)) -- Added a `stderr` attribute of `py-script` tags to route `sys.stderr` to a DOM element with the given ID. ([#1063](https://github.com/pyscript/pyscript/pull/1063)) - -### <py-repl> -- The `output` attribute of `py-repl` tags now specifies the id of the DOM element that `sys.stdout`, `sys.stderr`, and the results of a REPL execution are written to. It no longer affects the location of calls to `display()` -- Added a `stderr` attribute of `py-repl` tags to route `sys.stderr` to a DOM element with the given ID. ([#1106](https://github.com/pyscript/pyscript/pull/1106)) -- Resored the `output-mode` attribute of `py-repl` tags. If `output-mode` == 'append', the DOM element where output is printed is _not_ cleared before writing new results. - -### Plugins -- Plugins may now implement the `beforePyReplExec()` and `afterPyReplExec()` hooks, which are called immediately before and after code in a `py-repl` tag is executed. ([#1106](https://github.com/pyscript/pyscript/pull/1106)) - -Bug fixes ---------- - -- Fixes [#1280](https://github.com/pyscript/pyscript/issues/1280), which describes the errors on the PyRepl tests related to having auto-gen tags that shouldn't be there. - -Enhancements ------------- - -- Py-REPL tests now run on both osx and non osx OSs -- migrated from *rollup* to *esbuild* to create artifacts -- updated `@codemirror` dependency to its latest - -Docs ----- - -- Add docs for event handlers - -2023.01.1 -========= - - -Features --------- - -Bug fixes ---------- - -- Fixed an issue where `pyscript` would not be available when using the minified version of PyScript. ([#1054](https://github.com/pyscript/pyscript/pull/1054)) -- Fixed missing closing tag when rendering an image with `display`. ([#1058](https://github.com/pyscript/pyscript/pull/1058)) -- Fixed a bug where Python plugins methods were being executed twice. ([#1064](https://github.com/pyscript/pyscript/pull/1064)) - -Enhancements ------------- - -- When adding a `py-` attribute to an element but didn't added an `id` attribute, PyScript will now generate a random ID for the element instead of throwing an error which caused the splash screen to not shutdown. ([#1122](https://github.com/pyscript/pyscript/pull/1122)) -- You can now disable the splashscreen by setting `enabled = false` in your `py-config` under the `[splashscreen]` configuration section. ([#1138](https://github.com/pyscript/pyscript/pull/1138)) - -Documentation -------------- - -- Fixed 'Direct usage of document is deprecated' warning in the getting started guide. ([#1052](https://github.com/pyscript/pyscript/pull/1052)) -- Added reference documentation for the `py-splashscreen` plugin ([#1138](https://github.com/pyscript/pyscript/pull/1138)) -- Adds doc for installing tests ([#1156](https://github.com/pyscript/pyscript/pull/1156)) -- Adds docs for custom Pyscript attributes (`py-*`) that allow you to add event listeners to an element ([#1125](https://github.com/pyscript/pyscript/pull/1125)) - -Deprecations and Removals -------------------------- - -- The py-config `runtimes` to specify an interpreter has been deprecated. The `interpreters` config should be used instead. ([#1082](https://github.com/pyscript/pyscript/pull/1082)) -- The attributes `pys-onClick` and `pys-onKeyDown` have been deprecated, but the warning was only shown in the console. An alert banner will now be shown on the page if the attributes are used. They will be removed in the next release. ([#1084](https://github.com/pyscript/pyscript/pull/1084)) -- The pyscript elements `py-button`, `py-inputbox`, `py-box` and `py-title` have now completed their deprecation cycle and have been removed. ([#1084](https://github.com/pyscript/pyscript/pull/1084)) 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 15df7f675a4..00000000000 --- a/docs/concepts/what-is-pyscript.md +++ /dev/null @@ -1,33 +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 ---- -``` - -::: - -:::{tab-item} Preview - -```{raw} html - -``` - -::: -:::: diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index 872b204f908..00000000000 --- a/docs/conf.py +++ /dev/null @@ -1,108 +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", - "sphinx.ext.intersphinx", -] - -intersphinx_mapping = { - "python": ("https://docs.python.org/3.10", None), -} - -# 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/pyscript.svg" - -# 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/development/deprecation-cycle.md b/docs/development/deprecation-cycle.md deleted file mode 100644 index 679fa82c76a..00000000000 --- a/docs/development/deprecation-cycle.md +++ /dev/null @@ -1,38 +0,0 @@ -# Deprecation Cycle - -Pyscript is under heavy development, which means that some things may change, and some features might need to be deprecated so you can use different alternative implementations. - -This page describes the deprecation cycle for pyscript. - -## Deprecation Steps - -1. Remove usage of deprecated features from all examples. -2. Add warnings to all elements/features marked for deprecation. -3. Release a new version of pyscript with the deprecation warnings. -4. Next release, remove the deprecated features. - -## Deprecation Warnings - -Deprecation warnings are added to the codebase using the `showWarning` function from the `pyscriptjs.utils` module. - -This function creates a warning banner on the page if any of the deprecated features was used. You can use HTML to write the message; ideally, you should provide an alternative to the deprecated feature. - -### Example - -```js -import {showWarning} from './utils' - -showWarning(` -

- The py-deprecated tag is deprecated. Please use the py-actual tag instead. Please refer to this documentation page for more information. -

-`, "html") -``` - -## Deprecation History - -This section tracks deprecations of specific features, both for historical record and to help the development team remember to actually remove deprecated features in future releases. - -|Attribute/Object/Functionality|Deprecated In|Removed In| -|-|-|-| -|`py-mount` attribute | (Release following 2023.03.1) | -| diff --git a/docs/development/developing.md b/docs/development/developing.md deleted file mode 100644 index 780b855922c..00000000000 --- a/docs/development/developing.md +++ /dev/null @@ -1,231 +0,0 @@ -# Development Process - -This document is intended to help you get started in developing software for the PyScript project. It assumes that you have [a working development environment](setting-up-environment.md). It also assumes you have a remote named `upstream` pointing to PyScript's repository and one named `origin` pointing to your own repository. - -* First, make sure you are using the latest version of the pyscript main branch - -``` -git pull upstream main -``` - -* Update your fork with the latest changes - -``` -git push origin main -``` - -* Activate the conda environment (this environment will contain all the necessary dependencies) - -``` -conda activate pyscriptjs/env/ -``` -       **NOTE**: We are assuming you are in the root folder. If you are in the pyscriptjs you can run `conda activate env/` instead. - -* Install pre-commit (you only need to do this once) - -``` -pre-commit install -``` -       **NOTE**: On first run, pre-commit installs a bunch of hooks that will be run when you commit changes to your branch - this will make sure that your code is following our style (it will also lint your code automatically). - -* Create a branch for the issue that you want to work on - -``` -git checkout -b -``` - -* Work on your changes - -       **NOTE**: If you are working on a python file, you may encounter linting issues when pre-commit runs. Pyscript uses [black](https://black.readthedocs.io/en/stable/) to fix any linting problems automatically. All you need to do is add the changes again and commit using your previous commit message (the previous one that failed didn't complete due to black formatting files). - -* Run tests before pushing the changes - -``` -make test -``` - -To learn more about tests please refer to the session [Quick guide to pytest](## Quick guide to pytest). - -* When you make changes locally, double check that your contribution follows the PyScript formatting rules by running `npm run lint`. Note that in this case you're looking for the errors, **NOT** the warnings (Unless the warning is created by a local change). If an error is found by the linter you should fix it **before** creating a pull request. - -#### Rebasing changes - -Sometimes you might be asked to rebase the main branch into your local branch. Please refer to this [section on git rebase from GitHub docs](https://docs.github.com/en/get-started/using-git/about-git-rebase). - -If you need help with anything, feel free to reach out and ask for help! - - -## Updating the changelog - -As you work on your changes, please update the changelog file `changelog.md` with a short description of the changes you made. This will help us keep track of what has changed in each release. - -You can look at the [changelog](../changelog.md) for examples on how to add your changes to the changelog. But here's a quick example: - -``` -2023.02.01 -========= - -Bug fixes ---------- - -- Fixed a bug that was causing the app to crash when you tried to do something #PR_NUMBER - -Enhancements ------------- - -- Made awesome new feature #PR_NUMBER - -Documentation -------------- - -- Added a new section to the docs #PR_NUMBER - -``` - -## Quick guide to pytest - -We make heavy usage of `pytest`. Here is a quick guide and collection of -useful options: - -- To run all tests in the current directory and subdirectories: `pytest` - -- To run tests in a specific directory or file: `pytest path/to/dir/test_foo.py` - -- `-s`: disables output capturing - -- `--pdb`: in case of exception, enter a `(Pdb)` prompt so that you can - inspect what went wrong. - -- `-v`: verbose mode - -- `-x`: stop the execution as soon as one test fails - -- `-k foo`: run only the tests whose full name contains `foo` - -- `-k 'foo and bar'` - -- `-k 'foo and not bar'` - - -### Running integration tests under pytest - -`make test` is useful to run all the tests, but during the development is -useful to have more control on how tests are run. The following guide assumes -that you are in the directory `pyscriptjs/tests/integration/`. - -#### To run all the integration tests, single or multi core - -``` -$ pytest -xv -... - -test_00_support.py::TestSupport::test_basic[chromium] PASSED [ 0%] -test_00_support.py::TestSupport::test_console[chromium] PASSED [ 1%] -test_00_support.py::TestSupport::test_check_js_errors_simple[chromium] PASSED [ 2%] -test_00_support.py::TestSupport::test_check_js_errors_expected[chromium] PASSED [ 3%] -test_00_support.py::TestSupport::test_check_js_errors_expected_but_didnt_raise[chromium] PASSED [ 4%] -test_00_support.py::TestSupport::test_check_js_errors_multiple[chromium] PASSED [ 5%] -... -``` - -`-x` means "stop at the first failure". `-v` means "verbose", so that you can -see all the test names one by one. We try to keep tests in a reasonable order, -from most basic to most complex. This way, if you introduced some bug in very -basic things, you will notice immediately. - -If you have the `pytest-xdist` plugin installed, you can run all the -integration tests on 4 cores in parallel: -``` -$ pytest -n 4 -``` - -#### To run a single test, headless -``` -$ pytest test_01_basic.py -k test_pyscript_hello -s -... -[ 0.00 page.goto ] pyscript_hello.html -[ 0.01 request ] 200 - fake_server - http://fake_server/pyscript_hello.html -... -[ 0.17 console.info ] [py-loader] Downloading pyodide-0.22.1... -[ 0.18 request ] 200 - CACHED - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js -... -[ 3.59 console.info ] [pyscript/main] PyScript page fully initialized -[ 3.60 console.log ] hello pyscript -``` - -`-k` selects tests by pattern matching as described above. `-s` instructs -`pytest` to show the output to the terminal instead of capturing it. In the -output you can see various useful things, including network requests and JS -console messages. - -#### To run a single test, headed -``` -$ pytest test_01_basic.py -k test_pyscript_hello -s --headed -... -``` - -Same as above, but with `--headed` the browser is shown in a window, and you -can interact with it. The browser uses a fake server, which means that HTTP -requests are cached. - -Unfortunately, in this mode source maps does not seem to work, and you cannot -debug the original typescript source code. This seems to be a bug in -playwright, for which we have a workaround: - -``` -$ pytest test_01_basic.py -k test_pyscript_hello -s --headed --no-fake-server -... -``` - -As the name implies, `-no-fake-server` disables the fake server: HTTP requests -are not cached, but source-level debugging works. - -Finally: - -``` -$ pytest test_01_basic.py -k test_pyscript_hello -s --dev -... -``` - -`--dev` implies `--headed --no-fake-server`. In addition, it also -automatically open chrome dev tools. - - -## Fake server, HTTP cache - -By default, our test machinery uses a playwright router which intercepts and -cache HTTP requests, so that for example you don't have to download pyodide -again and again. This also enables the possibility of running tests in -parallel on multiple cores. - -The cache is stored using the `pytest-cache` plugin, which means that it -survives across sessions. - -If you want to temporarily disable the cache, the easiest thing is to use -`--no-fake-server`, which bypasses it completely. - -If you want to clear the cache, you can use the special option -`--clear-http-cache`: - -``` -$ pytest --clear-http-cache -... --------------------- SmartRouter HTTP cache -------------------- -Requests found in the cache: - https://raw.githubusercontent.com/pyscript/pyscript/main/README.md - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/repodata.json - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.asm.js - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/micropip-0.1-py3-none-any.whl - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.asm.data - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.asm.wasm - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide_py.tar - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyparsing-3.0.9-py3-none-any.whl - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/distutils.tar - https://cdn.jsdelivr.net/pyodide/v0.22.1/full/packaging-21.3-py3-none-any.whl -Cache cleared -``` - -**NOTE**: this works only if you are inside `tests/integration`, or if you -explicitly specify `tests/integration` from the command line. This is due to -how `pytest` decides to search for and load the various `conftest.py`. diff --git a/docs/development/index.md b/docs/development/index.md deleted file mode 100644 index 6e2226318db..00000000000 --- a/docs/development/index.md +++ /dev/null @@ -1,12 +0,0 @@ -# Development - -This section contains various topics related to pyscript development. - -```{toctree} ---- -maxdepth: 1 ---- -setting-up-environment -deprecation-cycle -developing -``` diff --git a/docs/development/setting-up-environment.md b/docs/development/setting-up-environment.md deleted file mode 100644 index 3334951721e..00000000000 --- a/docs/development/setting-up-environment.md +++ /dev/null @@ -1,125 +0,0 @@ -# Setting up your development environment - -* Fork the repository - [quicklink](https://github.com/pyscript/pyscript/fork) - -* Clone your fork of the project - -``` -git clone https://github.com//pyscript -``` - -* Add the original project as your upstream (this will allow you to pull the latest changes) - -```sh -git remote add upstream git@github.com:pyscript/pyscript.git -``` - -* cd into the `pyscriptjs` folder using the line below in your terminal (if your terminal is already in pyscript then use **cd pyscriptjs** instead) - -``` -cd pyscript/pyscriptjs -``` - -* Install the dependencies with the command below (you must have `nodejs` >=16 and `make`) - -``` -make setup -``` -       **NOTE**: If `make setup` gives a node/npm version required error then go to [troubleshooting](https://github.com/pyscript/pyscript/blob/main/TROUBLESHOOTING.md) - -* You can also run the examples locally by running the command below in your terminal - -``` -make examples -``` - -* 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 -``` -       **NOTE**: To access your local build paste `http://localhost:8080` into your browser - - -Now that node and npm have both been updated `make setup` should work, and you can continue [setting up your local environment](setting-up-environment.md) without problems (hopefully). - - -## Setting up and building the docs - -To build the documentation locally first make sure you are in the `docs` directory. - -You'll need `make` and `conda` installed in your machine. The rest of the environment should be automatically download and created for you once you use the command: - -``` -make setup -``` - -Use `conda activate $environment_name` to activate your environment. - -To add new information to the documentation make sure you conform with PyScript's code of conduct and with the general principles of Diataxis. Don't worry about reading too much on it, just do your best to keep your contributions on the correct axis. - -Write your documentation files using [Markedly Structured Text](https://myst-parser.readthedocs.io/en/latest/syntax/optional.html), which is very similar to vanilla Markdown but with some addons to create the documentation infrastructure. - -Once done, initialize a server to check your work: - -``` -make livehtml -``` - -Visible here: [http://127.0.0.1:8000](http://127.0.0.1:8000) - -## Setting up and building tests - -You'll need to install the following to have a functional test environment: `playwright`, `pytest-playwright`, `pillow`, `requests` and `numpy`. - -`pytest-playwright`is only available as a `pip` package so we recommend that you install `playwright` and `pytest` from `pip`. - -If you're interested to learn more about PyScript's testing framework, head over to the [development process](developing.md) page. - -# 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 - -For more information: - -* [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) -* [Discord Channel](https://discord.gg/BYB2kvyFwm) - -We use Discord as the main place for our discussions 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/error.md b/docs/error.md deleted file mode 100644 index 762b46d65b8..00000000000 --- a/docs/error.md +++ /dev/null @@ -1,3 +0,0 @@ -# Not found! - -The page that you looked for could not be found. If you think this is a mistake, please [open an issue](https://github.com/pyscript/pyscript/issues/new/) diff --git a/docs/guides/asyncio.md b/docs/guides/asyncio.md deleted file mode 100644 index 76183153abf..00000000000 --- a/docs/guides/asyncio.md +++ /dev/null @@ -1,35 +0,0 @@ -# Using Async/Await and Asyncio - -## {bdg-warning-line}`Deprecated` Implicit Coroutine Scheduling / Top-Level Await - -In PyScript versions 2022.09.1 and earlier, \ tags could be written in a way that enabled "Implicit Coroutine Scheduling." The keywords `await`, `async for` and `await with` were permitted to be used outside of `async` functions. Any \ tags with these keywords at the top level were compiled into coroutines and automatically scheuled to run in the browser's event loop. This functionality was deprecated, and these keywords are no longer allowed outside of `async` functions. - -To transition code from using top-level await statements to the currently-acceptable syntax, wrap the code into a coroutine using `async def()` and schedule it to run in the browser's event looping using `asyncio.ensure_future()` or `asyncio.create_task()`. - -The following two pieces of code are functionally equivalent - the first only works in versions 2022.09.1, the latter is the currently acceptable equivalent. - -```python -# This version is deprecated, since -# it uses 'await' outside an async function - -import asyncio - -for i in range(3): - print(i) - await asyncio.sleep(1) - -``` - -```python -# This version is acceptable - -import asyncio - -async def main(): - for i in range(3): - print(i) - await asyncio.sleep(1) - -asyncio.ensure_future(main()) - -``` diff --git a/docs/guides/custom-plugins.md b/docs/guides/custom-plugins.md deleted file mode 100644 index bbbc7e5f664..00000000000 --- a/docs/guides/custom-plugins.md +++ /dev/null @@ -1,225 +0,0 @@ -# Creating custom pyscript plugins - -Pyscript has a few built-in plugins, but you can also create your own ones. This guide will show you how to develop both Javascript and Python plugins. - -```{warning} -Pyscript plugins are currently under active development. The API is likely to go through breaking changes between releases. -``` - -You can add your custom plugins to the `` tag on your page. For example: - -```html - - plugins = ["http://example.com/hello-world.py"] - -``` - -Currently, only single files with the extension `.py` and `.js` files can be used as plugins. - -## Python plugins - -Python plugins allow you to write plugins in pure Python. We first need to import `Plugin` from `pyscript` and create a new instance of it. - -```python -from pyscript import Plugin - -plugin = Plugin("PyHelloWorld") -``` - -We can now create a new class containing our plugin code to add the text "Hello World" to the page. - -```python -from pyscript import Plugin, js - -plugin = Plugin("PyHelloWorld") - -class PyHelloWorld: - def __init__(self, element): - self.element = element - - - def connect(self): - self.element.innerHTML = "

Hello World!

" -``` - -Let's now create our `index.html` page and add the plugin. - -```html - - - - - - - Python Plugin - - - - - - - - plugins = ["./hello-world.py"] - - - -``` - -Now we need to start a live server to serve our page. You can use Python's `http.server` module for this. - -```bash -python -m http.server -``` - -Now you can open your browser and go to `http://localhost:8000` to see the page. You might be surprised that the text "Hello World" is not on the page. This is because we need to do a few more things to make our plugin work. - -First, we must create a custom element that our plugin will use. We can use a decorator in our `PyHelloWorld` class. - -```python -from pyscript import Plugin, js - -plugin = Plugin("PyHelloWorld") - -@plugin.register_custom_element("py-hello-world") -class PyHelloWorld: - def __init__(self, element): - self.element = element - - def connect(self): - self.element.innerHTML = "
Hello World!
" -``` - -Now that we have registered our custom element, we can use the custom tag `` to add our plugin to the page. - -```html - - - - - - - Python Plugin - - - - - - - - plugins = ["./hello-world.py"] - - - - - -``` - -Now, if you go to `http://localhost:8000` you should see the text "Hello World" on the page. - -Writing plugins in Python is an excellent way if you want to use PyScript's API's. However, if you want to write plugins in Javascript, you can do that too. - -## Javascript plugins - -Javascript plugins need to have a specific structure to be loaded by PyScript. The plugin export a default class with the following method, which may implement any, all, or none of the [Plugin lifecycle methods](https://github.com/pyscript/pyscript/blob/main/pyscriptjs/src/plugin.ts#L9-L65). These method will be called at the corresponding points in lifecycle of PyScript as it loads, configures itself and its Python interpreter, and executes `` and `` tags. - -```{note} -You need to specify the file extension `.js` when adding your custom plugin to the `` tag. -``` - -### Creating a Hello World plugin - -Let's create a simple plugin that will add the text "Hello World" to the page. We will create a `hello-world.js` file and write the plugin class. - -```js -export default class HelloWorldPlugin { - afterStartup(runtime) { - // Code goes here - } -} -``` - -Now we need to add the code that will add the text to the page. - -```js -export default class HelloWorldPlugin { - afterStartup(runtime) { - const elem = document.createElement("h1"); - elem.innerText = "Hello World"; - document.body.appendChild(elem); - } -} -``` - -Finally, we need to add the plugin to our page's `` tag. - -```html - - - - - - - Javascript Plugin - - - - - - - - plugins = ["./hello-world.js"] - - - -``` - -Now we need to start a live server to serve our page. You can use Python's `http.server` module for this. - -```bash -python -m http.server -``` - -Now you can open your browser and go to `http://localhost:8000` to see the page. You should see the text "Hello World" on the page. - -```{note} -Because we are using a local file, you must start a live server. Otherwise, Pyscript will not be able to fetch the file. -``` - -### Expanding the Hello World plugin - -As you can see, we could build all our plugin logic inside the `afterStartup` method. You may also want to create a custom html element for your plugin. Let's see how we can do that. - -First, we need to create a custom html element. Let's start by creating our `PyHelloWorld` class that extends the `HTMLElement` class. - - -```js -class PyHelloWorld extends HTMLElement { - constructor() { - super(); - } - - connectedCallback() { - this.innerHTML = `

Hello, world!

`; - this.mount_name = this.id; - } -} -``` - -We can now register our custom element in the `afterStartup` method of our `HelloWorldPlugin` class. We will also add the custom tag `py-hello-world` to the page. - -```js -export default class HelloWorldPlugin { - afterStartup(runtime) { - // Create a custom element called - customElements.define("py-hello-world", PyHelloWorld); - - // Add the custom element to the page so we can see it - const elem = document.createElement('py-hello-world'); - document.body.append(elem); - } -} -``` - -Now we can open our page and see the custom element on the page. - -By now, you should have a good idea for creating a custom plugin. Also, how powerful it can be to create custom elements that other users could use in their PyScript pages. diff --git a/docs/guides/event-handlers.md b/docs/guides/event-handlers.md deleted file mode 100644 index 7546ccc4321..00000000000 --- a/docs/guides/event-handlers.md +++ /dev/null @@ -1,179 +0,0 @@ -# Event handlers in PyScript - -PyScript offer two ways to subscribe to Javascript event handlers: - -## Subscribe to event with `py-*` attributes - -The value of the attribute contains python code which will be executed when the event is fired. A very common pattern is to call a function which does further work, for example: - -```html - - -``` - -```python - - def say_hello_no_param(): - print("Hello!") - - def say_hello_with_param(name): - print("Hello " + name + "!") - -``` - -Note that py-\* attributes need a _function call_ - -Supported py-\* attributes can be seen in the [PyScript API reference](<[../api-reference.md](https://github.com/pyscript/pyscript/blob/66b57bf812dcc472ed6ffee075ace5ced89bbc7c/pyscriptjs/src/components/pyscript.ts#L119-L260)>). - -## Subscribe to event with `addEventListener` - -You can also subscribe to an event using the `addEventListener` method of the DOM element. This is useful if you want to pass event object to the event handler. - -```html - -``` - -```python - - from js import console, document - from pyodide.ffi.wrappers import add_event_listener - - def hello_args(*args): - console.log(f"Hi! I got some args! {args}") - - add_event_listener(document.getElementById("two"), "click", hello_args) - -``` - -or using the `addEventListener` method of the DOM element: - -```html - -``` - -```python - - from js import console, document - from pyodide.ffi import create_proxy - - def hello_args(*args): - console.log(f"Hi! I got some args! {args}") - - document.getElementById("three").addEventListener("click", create_proxy(hello_args)) - -``` - -or using the PyScript Element class: - -```html - -``` - -```python - - from js import console - from pyodide.ffi import create_proxy - - def hello_args(*args): - console.log(f"Hi! I got some args! {args}") - - Element("four").element.addEventListener("click", create_proxy(hello_args)) - -``` - -## JavaScript to PyScript and From PyScript to JavaScript - -If you're wondering about how to pass objects from JavaScript to PyScript and/or the other way around head over to the [Passing Objects](passing-objects.md) page. - - -### Exporting all Global Python Objects - -We can use our new `createObject` function to "export" the entire Python global object dictionary as a JavaScript object: - -```python - - from js import createObject - from pyodide.ffi import create_proxy - createObject(create_proxy(globals()), "pyodideGlobals") - -``` - -This will make all Python global variables available in JavaScript with `pyodideGlobals.get('my_variable_name')`. - -(Since PyScript tags evaluate _after_ all JavaScript on the page, we can't just dump a `console.log(...)` into a ` -``` - -### Exporting Individual Python Objects - -We can also export individual Python objects to the JavaScript global scope if we wish. - -(As above, the following example uses a button to delay the execution of the ` -``` diff --git a/docs/guides/http-requests.md b/docs/guides/http-requests.md deleted file mode 100644 index bdcd0564d82..00000000000 --- a/docs/guides/http-requests.md +++ /dev/null @@ -1,224 +0,0 @@ -# How to make HTTP requests using `PyScript`, in pure Python - -[Pyodide](https://pyodide.org), the interpreter that underlies `PyScript`, does not have the `requests` module -(or other similar modules) available by default, which are traditionally used to make HTTP requests in Python. -However, it is possible to make HTTP requests in Pyodide using the modern `JavaScript` `fetch` API -([docs](https://developer.mozilla.org/en-US/docs/Web/API/fetch)). This example shows how to make common HTTP request -(GET, POST, PUT, DELETE) to an API, using only Python code! We will use asynchronous functions with -async/await syntax, as concurrent code is preferred for HTTP requests. - -The purpose of this guide is not to teach the basics of HTTP requests, but to show how to make them -from `PyScript` using Python, since currently, the common tools such as `requests` and `httpx` are not available. - -## Fetch - -The `fetch` API is a modern way to make HTTP requests. It is available in all modern browsers, and in Pyodide. - -Although there are two ways to use `fetch`: -1) using `JavaScript` from `PyScript` -2) using Pyodide's Python wrapper, -`pyodide.http.pyfetch` - -This example will only show how to use the Python wrapper. Still, the -[fetch documentation](https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters) is a useful reference, as its -parameters can be called from Python using the `pyfetch` wrapper. - -## Pyodide.http, pyfetch, and FetchResponse - -The [pyodide.http module](https://pyodide.org/en/stable/usage/api/python-api/http.html#module-pyodide.http) is a Python API -for dealing with HTTP requests. It provides the `pyfetch` function as a wrapper for the `fetch` API, -which returns a `FetchResponse` object whenever a request is made. Extra keyword arguments can be passed to `pyfetch` -which will be passed to the `fetch` API. - -The returned object `FetchResponse` has familiar methods and properties -for dealing with the response, such as `json()` or `status`. See the -[FetchResponse documentation](https://pyodide.org/en/stable/usage/api/python-api/http.html#pyodide.http.FetchResponse) -for more information. - -## Example - -We will make async HTTP requests to [JSONPlaceholder](https://jsonplaceholder.typicode.com/)'s fake API using `pyfetch`. -First we write a helper function in pure Python that makes a request and returns the response. This function -makes it easier to make specific types of requests with the most common parameters. - -## Python convenience function - -```python -from pyodide.http import pyfetch, FetchResponse -from typing import Optional, Any - -async def request(url: str, method: str = "GET", body: Optional[str] = None, - headers: Optional[dict[str, str]] = None, **fetch_kwargs: Any) -> FetchResponse: - """ - Async request function. Pass in Method and make sure to await! - Parameters: - url: str = URL to make request to - method: str = {"GET", "POST", "PUT", "DELETE"} from `JavaScript` global fetch()) - body: str = body as json string. Example, body=json.dumps(my_dict) - headers: dict[str, str] = header as dict, will be converted to string... - Example, headers=json.dumps({"Content-Type": "application/json"}) - fetch_kwargs: Any = any other keyword arguments to pass to `pyfetch` (will be passed to `fetch`) - Return: - response: pyodide.http.FetchResponse = use with .status or await.json(), etc. - """ - kwargs = {"method": method, "mode": "cors"} # CORS: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing - if body and method not in ["GET", "HEAD"]: - kwargs["body"] = body - if headers: - kwargs["headers"] = headers - kwargs.update(fetch_kwargs) - - response = await pyfetch(url, **kwargs) - return response -``` - -This function is a wrapper for `pyfetch`, which is a wrapper for the `fetch` API. It is a coroutine function, -so it must be awaited. It also has type hints, which are not required, but are useful for IDEs and other tools. -The basic idea is that the `PyScript` will import and call this function, then await the response. Therefore, -the script containing this function must be importable by `PyScript`. - -For this example, we will name the file containing the Python code `request.py` and place it in the same directory as the file -containing the html code, which is described below. - -## `PyScript` HTML code - -In this How-to, the HTML code is split into separate code blocks to enable context highlighting (coloring of the Python -code inside the html code block), but in reality it is all in the same file. The first part is a bare bones `PyScript` -html page, using the [community examples](https://github.com/pyscript/pyscript-collective/) set-up. The second part is -the actual Python code for HTTP requests, which is wrapped in `` tags, while the third block has the -concluding html code. - -```html - - - - - - - GET, POST, PUT, DELETE example - - - - - - - [[fetch]] - files = ["/request.py"] - - - -

- Hello world request example!
- Here is the output of your request: -

- - import asyncio - import json - from request import request # import our request function. - - async def main(): - baseurl = "https://jsonplaceholder.typicode.com" - - # GET - headers = {"Content-type": "application/json"} - response = await request(f"{baseurl}/posts/2", method="GET", headers=headers) - print(f"GET request=> status:{response.status}, json:{await response.json()}") - - # POST - body = json.dumps({"title": "test_title", "body": "test body", "userId": 1}) - new_post = await request(f"{baseurl}/posts", body=body, method="POST", headers=headers) - print(f"POST request=> status:{new_post.status}, json:{await new_post.json()}") - - # PUT - body = json.dumps({"id": 1, "title": "test_title", "body": "test body", "userId": 2}) - new_post = await request(f"{baseurl}/posts/1", body=body, method="PUT", headers=headers) - print(f"PUT request=> status:{new_post.status}, json:{await new_post.json()}") - - # DELETE - new_post = await request(f"{baseurl}/posts/1", method="DELETE", headers=headers) - print(f"DELETE request=> status:{new_post.status}, json:{await new_post.json()}") - - asyncio.ensure_future(main()) - - -
-

- You can also use other methods. See fetch documentation:
- https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters -

-
-
-

- See pyodide documentation for what to do with a FetchResponse object:
- https://pyodide.org/en/stable/usage/api/python-api.html#pyodide.http.FetchResponse -

-
- - -``` - -## Explanation -### `py-config` tag for importing our Python code -The very first thing to notice is the `py-config` tag. This tag is used to import Python files into the `PyScript`. -In this case, we are importing the `request.py` file, which contains the `request` function we wrote above. - -### `py-script` tag for making async HTTP requests - -Next, the `py-script` tag contains the actual Python code where we import `asyncio` and `json`, -which are required or helpful for the `request` function. -The `# GET`, `# POST`, `# PUT`, `# DELETE` blocks show examples of how to use the `request` function to make basic -HTTP requests. The `await` keyword is required not only for the `request` function, but also for certain methods of the -`FetchResponse` object, such as `json()`, meaning that the code is asynchronous and slower requests will not block the -faster ones. - -### HTTP Requests - -HTTP requests are a very common way to communicate with a server. They are used for everything from getting data from -a database, to sending emails, to authorization, and more. Due to safety concerns, files loaded from the -local file system are not accessible by `PyScript`. Therefore, the proper way to load data into `PyScript` is also -through HTTP requests. - -In our example, we show how to pass in a request `body`, `headers`, and specify the request `method`, in order to make -`GET`, `POST`, `PUT`, and `DELETE` requests, although methods such as `PATCH` are also available. Additional -parameters for the `fetch` API are also available, which can be specified as keyword arguments passed to our helper -function or to `pyfetch`. See the -[fetch documentation](https://developer.mozilla.org/en-US/docs/Web/API/fetch#parameters) for more information. -HTTP requests are defined by standards-setting bodies in [RFC 1945](https://www.rfc-editor.org/info/rfc1945) and -[RFC 9110](https://www.rfc-editor.org/info/rfc9110). - -## Conclusion - -This tutorial demonstrates how to make HTTP requests using `pyfetch` and the `FetchResponse` objects. Importing Python -code/files into the `PyScript` using the `py-config` tag is also covered. - -Although a simple example, the principals here can be used to create complex web applications inside of `PyScript`, -or load data into `PyScript` for use by an application, all served as a static HTML page, which is pretty amazing! - -## API Quick Reference - -## pyodide.http.pyfetch - -### pyfetch Usage - -```python -await pyodide.http.pyfetch(url: str, **kwargs: Any) -> FetchResponse -``` - -Use `pyfetch` to make HTTP requests in `PyScript`. This is a wrapper around the `fetch` API. Returns a `FetchResponse`. - -- [`pyfetch` Docs.](https://pyodide.org/en/stable/usage/api/python-api/http.html#pyodide.http.pyfetch) - -## pyodide.http.FetchResponse - -### FetchResponse Usage - -```python -response: pyodide.http.FetchResponse = await -status = response.status -json = await response.json() -``` - -Class for handling HTTP responses. This is a wrapper around the `JavaScript` fetch `Response`. Contains common (async) -methods and properties for handling HTTP responses, such as `json()`, `url`, `status`, `headers`, etc. - -- [`FetchResponse` Docs.](https://pyodide.org/en/stable/usage/api/python-api/http.html#pyodide.http.FetchResponse) diff --git a/docs/guides/index.md b/docs/guides/index.md deleted file mode 100644 index b39f23414c5..00000000000 --- a/docs/guides/index.md +++ /dev/null @@ -1,22 +0,0 @@ -# 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:' ---- -passing-objects -http-requests -asyncio -custom-plugins -event-handlers -``` diff --git a/docs/guides/passing-objects.md b/docs/guides/passing-objects.md deleted file mode 100644 index f7ef966c5df..00000000000 --- a/docs/guides/passing-objects.md +++ /dev/null @@ -1,295 +0,0 @@ -# How to Pass Objects from PyScript to Javascript (and Vice Versa) - -[Pyodide](https://pyodide.org), the interpreter that underlies PyScript, does a lot of work under the hood to translate objects between Python and JavaScript. This allows code in one language to access objects defined in the other. - -This guide discusses how to pass objects between JavaScript and Python within PyScript. For more details on how Pyodide handles translating and proxying objects between the two languages, see the [Pyodide Type Translations Page](https://pyodide.org/en/stable/usage/type-conversions.html). - -For our purposes, an 'object' is anything that can be bound to a variable (a number, string, object, [function](https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function), etc). - -## JavaScript to PyScript - -We can use the syntax `from js import ...` to import JavaScript objects directly into PyScript. Simple JavaScript objects are converted to equivalent Python types; these are called [implicit conversions](https://pyodide.org/en/stable/usage/type-conversions.html#implicit-conversions). More complicated objects are wrapped in [JSProxy](https://pyodide.org/en/stable/usage/type-conversions.html) objects to make them behave like Python objects. - -`import js` and `from js import ...` [in Pyodide](https://pyodide.org/en/stable/usage/type-conversions.html#type-translations-using-js-obj-from-py) get objects from the [JavaScript globalThis scope](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis), so keep the[ rules of JavaScript variable scoping](https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/) in mind. - -```html - -``` -```python - - # Import and use JS function and variable into Python - from js import name, addTwoNumbers - - print(f"Hello {name}") - print("Adding 1 and 2 in Javascript: " + str(addTwoNumbers(1, 2))) - -``` - -## PyScript to JavaScript - -### Using Pyodide's globals access - -The [PyScript JavaScript module](../reference/modules/pyscript.md) exposes its underlying Pyodide interpreter as `PyScript.interpreter`, and maintains a reference to the [globals()](https://docs.python.org/3/library/functions.html#globals) dictionary of the Python namespace. Thus, any global variables in python are accessible in JavaScript at `PyScript.interpreter.globals.get('my_variable_name')` - -```html - - x = 42 - - - - -``` - -Since [everything is an object](https://docs.python.org/3/reference/datamodel.html) in Python, this applies not only to user created variables, but also to classes, functions, built-ins, etc. If we want, we can even apply Python functions to JavaScript data and variables: - -```html - - - - - -``` - -### Using JavaScript's eval() - -There may be some situations where it isn't possible or ideal to use `PyScript.interpreter.globals.get()` to retrieve a variable from the Pyodide global dictionary. For example, some JavaScript frameworks may take a function/Callable as an html attribute in a context where code execution isn't allowed (i.e. `get()` fails). In these cases, you can create JavaScript proxies of Python objects more or less "manually" using [JavaScript's eval() function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval), which executes a string as code much like [Python's eval()](https://docs.python.org/3/library/functions.html#eval). - -First, we create a JS function `createObject` which takes an object and a string, then uses `eval()` to create a variable named after the string and bind it to that object. By calling this function from PyScript (where we have access to the Pyodide global namespace), we can bind JavaScript variables to Python objects without having direct access to that global namespace. - -Include the following script tag anywhere in your html document: - -```html - -``` - -This function takes a Python Object and creates a variable pointing to it in the JavaScript global scope. - -### Exporting all Global Python Objects - -We can use our new `createObject` function to "export" the entire Python global object dictionary as a JavaScript object: - -```python - - from js import createObject - from pyodide.ffi import create_proxy - createObject(create_proxy(globals()), "pyodideGlobals") - -``` -This will make all Python global variables available in JavaScript with `pyodideGlobals.get('my_variable_name')`. - -(Since PyScript tags evaluate _after_ all JavaScript on the page, we can't just dump a `console.log(...)` into a ` -``` - -#### Full example - -```html - - - - - - - Exporting all Global Python Objects - - - - - - - - - - - from js import createObject - from pyodide.ffi import create_proxy - - createObject(create_proxy(globals()), "pyodideGlobals") - - # create some Python objects: - symbols = {'pi': 3.1415926, 'e': 2.7182818} - - def rough_exponential(x): - return symbols['e']**x - - class Circle(): - def __init__(self, radius): - self.radius = radius - - @property - def area(self): - return symbols['pi'] * self.radius**2 - - - - -``` - - -### Exporting Individual Python Objects - -We can also export individual Python objects to the JavaScript global scope if we wish. - -(As above, the following example uses a button to delay the execution of the ` -``` - -#### Full example - -```html - - - - - - - Exporting Individual Python Objects - - - - - - - - - - import js - from pyodide.ffi import create_proxy - - # Create 3 python objects - language = "Python 3" - animals = ['dog', 'cat', 'bird'] - multiply3 = lambda a, b, c: a * b * c - - # js object can be named the same as Python objects... - js.createObject(language, "language") - - # ...but don't have to be - js.createObject(create_proxy(animals), "animals_from_py") - - # functions are objects too, in both Python and Javascript - js.createObject(create_proxy(multiply3), "multiply") - - - - - - -``` diff --git a/docs/img/diataxis.png b/docs/img/diataxis.png deleted file mode 100644 index a9518ce5da7..00000000000 Binary files a/docs/img/diataxis.png and /dev/null differ diff --git a/docs/img/pyodide-pyscript.png b/docs/img/pyodide-pyscript.png deleted file mode 100644 index 300d8a7cc70..00000000000 Binary files a/docs/img/pyodide-pyscript.png and /dev/null differ diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index 72aa2342669..00000000000 --- a/docs/index.md +++ /dev/null @@ -1,58 +0,0 @@ -# PyScript - -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} [Guides](guides/index.md) - -You already know the basics and want to learn specifics! - -[Passing Objects between JavaScript and Python](guides/passing-objects.md) - -[Making async HTTP requests in pure Python](guides/http-requests.md) - -[Async/Await and Asyncio](guides/asyncio.md) - -::: -:::{grid-item-card} [Concepts](concepts/index.md) - -[What is PyScript?](concepts/what-is-pyscript.md) - -::: -:::{grid-item-card} [Reference](reference/index.md) - -[Frequently asked questions](reference/faq.md) - -[The PyScript JS Module](reference/modules/pyscript.md) - -:::{toctree} -:maxdepth: 1 - -::: -:::: - -```{toctree} ---- -maxdepth: 1 -hidden: ---- -tutorials/index -guides/index -concepts/index -reference/index -changelog -``` 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/API/__version__.md b/docs/reference/API/__version__.md deleted file mode 100644 index aa649480dba..00000000000 --- a/docs/reference/API/__version__.md +++ /dev/null @@ -1,8 +0,0 @@ -# `__version__` - -`PyScript.__version__` is a `str` representing the current version of PyScript in a human-readable form. For a structured version more suitable to comparisons, and for details of what each part of the version number represents, see [`version_info`](version_info.md) - -```shell ->>> pyscript.__version__ -'2023.02.1.dev' -``` diff --git a/docs/reference/API/attr_to_event.md b/docs/reference/API/attr_to_event.md deleted file mode 100644 index 5f026c38bf9..00000000000 --- a/docs/reference/API/attr_to_event.md +++ /dev/null @@ -1,87 +0,0 @@ -# List of PyScript Attributes to Events: - -PyScript provides a convenient syntax for mapping JavaScript events to PyScript events, making it easy to connect events to HTML tags. - -For example, you can use the following code to connect the click event to a button: - -``` - -``` - -Here is a list of all the available event mappings: - -| PyScript Event Name | DOM Event Name | -|-------------------|----------------| -| py-onClick | click | -| py-onKeyDown | keydown | -| py-afterprint | afterprint | -| py-beforeprint | beforeprint | -| py-beforeunload | beforeunload | -| py-error | error | -| py-hashchange | hashchange | -| py-load | load | -| py-message | message | -| py-offline | offline | -| py-online | online | -| py-pagehide | pagehide | -| py-pageshow | pageshow | -| py-popstate | popstate | -| py-resize | resize | -| py-storage | storage | -| py-unload | unload | -| py-blur | blur | -| py-change | change | -| py-contextmenu | contextmenu | -| py-focus | focus | -| py-input | input | -| py-invalid | invalid | -| py-reset | reset | -| py-search | search | -| py-select | select | -| py-submit | submit | -| py-keydown | keydown | -| py-keypress | keypress | -| py-keyup | keyup | -| py-click | click | -| py-dblclick | dblclick | -| py-mousedown | mousedown | -| py-mousemove | mousemove | -| py-mouseout | mouseout | -| py-mouseover | mouseover | -| py-mouseup | mouseup | -| py-mousewheel | mousewheel | -| py-wheel | wheel | -| py-drag | drag | -| py-dragend | dragend | -| py-dragenter | dragenter | -| py-dragleave | dragleave | -| py-dragover | dragover | -| py-dragstart | dragstart | -| py-drop | drop | -| py-scroll | scroll | -| py-copy | copy | -| py-cut | cut | -| py-paste | paste | -| py-abort | abort | -| py-canplay | canplay | -| py-canplaythrough | canplaythrough | -| py-cuechange | cuechange | -| py-durationchange | durationchange | -| py-emptied | emptied | -| py-ended | ended | -| py-loadeddata | loadeddata | -| py-loadedmetadata | loadedmetadata | -| py-loadstart | loadstart | -| py-pause | pause | -| py-play | play | -| py-playing | playing | -| py-progress | progress | -| py-ratechange | ratechange | -| py-seeked | seeked | -| py-seeking | seeking | -| py-stalled | stalled | -| py-suspend | suspend | -| py-timeupdate | timeupdate | -| py-volumechange | volumechange | -| py-waiting | waiting | -| py-toggle | toggle | diff --git a/docs/reference/API/display.md b/docs/reference/API/display.md deleted file mode 100644 index cae35ba2248..00000000000 --- a/docs/reference/API/display.md +++ /dev/null @@ -1,88 +0,0 @@ -# `display(*values, target=None, append=True)` - -## Parameters - -`*values` - the objects to be displayed. String objects are output as-written. For non-string objects, the default content to display is the the object's {py:func}`repr`. Objects may implement the following methods to indicate that they should be displayed as a different MIME type. MIME types with a * indicate that the content will be wrapped in the appropriate html tags and attributes before output: - - -| Method | Inferred MIME type | -|---------------------|------------------------| -| `__repr__` | text/plain | -| `_repr_html_` | text/html | -| `_repr_svg_` | image/svg+xml | -| `_repr_png_` | image/png* | -| `_repr_pdf_` | application/pdf | -| `_repr_jpeg_` | image/jpeg* | -| `_repr_json_` | application/json | -| `_repr_javascript_` | application/javascript*| -| `savefig` | image/png | -| | | - -`target` - Element's ID. The default value for `target` is the current `py-script` tag ID, it's possible to specify different IDs for this parameter - -`append` - `boolean` if the output is going to be appended or not to the `target`ed element. It creates a `
` tag if `True` and a `` tag with a random ID if `False`. The default value for `append` is `True`. - -### Description - -Display is the default function to display objects on the screen. Functions like the Python `print()` or JavaScript `console.log()` are now defaulted to only appear on the terminal. - -Display will throw an exception if the target is not clear. E.g. the following code is invalid: - -```html - - def display_hello(): - # this fails because we don't have any implicit target - # from event handlers - display('hello') - - -``` - -Because it's considered unclear if the `hello` string should be displayed underneath the `` tag or the ` -``` - -#### Using matplotlib with display - -`matplotlib` has two ways of plotting things as mentioned [here](https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interface/) - -- In case of using the `pyplot` interface, the graph can be shown using `display(plt)`. - -```python -import matplotlib.pyplot as plt -import numpy as np - -# Data for plotting -t = np.arange(0.0, 2.0, 0.01) -s = 1 + np.sin(2 * np.pi * t) -plt.plot(t,s) - -display(plt) -``` - -- In case of using the `object oriented` interface, the graph can be shown using `display(fig)` or `display(plt)` both. - -```python -import matplotlib.pyplot as plt -import numpy as np - -# Data for plotting -t = np.arange(0.0, 2.0, 0.01) -s = 1 + np.sin(2 * np.pi * t) - -fig, ax = plt.subplots() -ax.plot(t, s) - -display(fig) # but even display(plt) would have worked! -``` diff --git a/docs/reference/API/element.md b/docs/reference/API/element.md deleted file mode 100644 index 1d8e89e5f18..00000000000 --- a/docs/reference/API/element.md +++ /dev/null @@ -1,309 +0,0 @@ -# `Element` - -The `Element` API is a helpful way to create and manipulate elements in the DOM. It is a wrapper around the native DOM API, and is designed to be as intuitive as possible. - -## Methods and Properties - -| Property | Description | -|----------|-----------------------------------------| -| `element` | Returns the element with the given ID. | -| `id` | Returns the element's ID. | -| `value` | Returns the element's value. | -| `innerHtml` | Returns the element's inner HTML. | - - - -| Method | Description | -|----------------------|--------------------------------------------------------------| -| `write` | Writes `value` to element and handles various mime types. `append` defaults to `False`, if set to true, it will create a child element. | -| `clear` | Clears the element's value or content. | -| `select` | Select element from `query` which uses [Document.querySelector()](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector). | -| `clone` | Clones the with `new_id` if provided and `to` element if provided. | -| `remove_class` | Removes one or more class name from the element. | -| `add_class` | Adds one or more class name to the element. | - -## Element.element - -| Parameter | Default | Type | -|-----------|---------|------| -| | | | - -The `element` property returns the DOM element with the given ID. - -```html - from pyscript import Element - - my_div = Element('my-div') - print(my_div.element) -``` - -## Element.id - -| Parameter | Default | Type | -|-----------|---------|------| -| | | | - -Return the element's ID. - -```html - -
- - - from pyscript import Element - - my_div = Element('my-div') - print(my_div.id) # prints 'my-div' - -``` - -## Element.value - -| Parameter | Default | Type | -|-----------|---------|------| -| | | | - -Return the element's value. - -```html - - - - from pyscript import Element - - my_input = Element('my-input') - print(my_input.value) # prints 'hello world' - -``` - -## Element.innerHtml - -| Parameter | Default | Type | -|-----------|---------|------| -| | | | - -Return the element's inner HTML. - -```html -
- hello world -
- - - from pyscript import Element - - my_innerHtml = Element('my-innerHtml') - print(my_innerHtml.innerHtml) # prints hello world - -``` - -## Element.write - -| Parameter | Default | Type | -|-------------|---------|-----------------------------| -| `value` | | `str` or `__mime_type__` | -| `append` | False | `bool` | - -Writes `value` to element and handles various mime types. This method also contains a `append` parameter, which defaults to `False`. - -Currently, these are the MIME types that are supported when rendering content using this method - -| Method | Inferred MIME type | -|---------------------|------------------------| -| `__repr__` | text/plain | -| `_repr_html_` | text/html | -| `_repr_svg_` | image/svg+xml | -| `_repr_png_` | image/png* | -| `_repr_pdf_` | application/pdf | -| `_repr_jpeg_` | image/jpeg* | -| `_repr_json_` | application/json | -| `_repr_javascript_` | application/javascript*| -| `savefig` | image/png | - -```html -
- - - from pyscript import Element - el = Element("foo") - el.write("Hello!") - el.write("World!") # will replace the previous content - -``` - -If we set `append` to `True`, it will create a child element using a `div`. - -```html -
- - - from pyscript import Element - el = Element("foo") - el.write("Hello!", append=True) - - # This will create a child div with the id "foo-1" - el.write("World!", append=True) - -``` - -## Element.clear - -| Parameter | Default | Type | -|-----------|---------|------| -| | | | - -Clears the element's value or content. For example, we can clear the value of an input element. - -```html - - - - from pyscript import Element - el = Element("foo") - el.clear() # Removes value from input - -``` - -Or we can clear the content of a div element. - -```html -
Hello!
- - - from pyscript import Element - el = Element("foo") - el.clear() # Removes Hello from div content - -``` - -## Element.select - -Select element from `query`, it will look into the main Element if `from_content` is `True`. This method is a wrapper of [Document.querySelector()](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector). - -```html -
-
-
- - - from pyscript import Element - el = Element("foo") - bar = el.select("#bar") - print(bar.id) # prints 'bar' - -``` - -## Element.clone - -| Parameter | Default | Type | -|-------------|---------|-----------| -| `new_id` | None | `str` | -| `to` | None | `Element` | - -Clones the element to a new element. You can provide `new_id` to set a different id to the cloned element. You can also use a `to` element to append the cloned element to. - -```html -
- HI! -
- - - from pyscript import Element - - el = Element("foo") - # Creates two divs with the id "foo" and content "HI!" - el.clone() - -``` - -It's always a good idea to pass a new id to the element you are cloning to avoid confusion if you need to reference the element by id again. - -```html -
Hello!
- - - from pyscript import Element - el = Element("foo") - # Clones foo and its contents, but uses the id 'bar' - el.clone(new_id="bar") - -``` - -You can also clone an element into another element. - -```html -
- Bond -
-
- James -
- - from pyscript import Element - - bond_div = Element("bond") - james_div = Element("james") - - bond_div.clone(new_id="bond-2", to=james_div) - -``` - -## Element.remove_class - -| Parameter | Default | Type | -|-------------|---------|-----------------------| -| `classname` | None | `str` or `List[str]` | - -Removes one or more class names from the element. - -```html -
- - from pyscript import Element - - el = Element("foo") - el.remove_class("bar") - -``` - -You can also remove multiple classes by passing a list of strings. - -```html -
- - from pyscript import Element - - el = Element("foo") - el.remove_class(["bar", "baz"]) # Remove all classes from element - -``` - -## Element.add_class - -| Parameter | Default | Type | -|-------------|---------|-----------------------| -| `classname` | None | `str` or `List[str]` | - -Adds one or more class names to the element. - -```html - -
Hi!
- - from pyscript import Element - el = Element("foo") - el.add_class("red") - -``` - -You can also add multiple classes at once by passing a list of strings. - -```html - -
Hi!
- - from pyscript import Element - el = Element("foo") - el.add_class(["red", "bold"]) - -``` diff --git a/docs/reference/API/version_info.md b/docs/reference/API/version_info.md deleted file mode 100644 index dfba3c20f7a..00000000000 --- a/docs/reference/API/version_info.md +++ /dev/null @@ -1,16 +0,0 @@ -# `version_info` - -`PyScript.version_info` is a `namedtuple` representing the current version of PyScript. It can be used to compare whether current version precedes or follows a desired version. For a human-readable version of the same info, see [`__version__`](__version__.md) - -```sh ->>> pyscript.version_info -version_info(year=2023, month=2, minor=1, releaselevel='dev') -``` - -## Version Fields -| **parameter** | **CalVer equivalent field** | **example value** | **description** | -|-----------------|-----------------------------|---------------|------------------------------------------------------------------------------------------------------------------------------------------| -| `year` | Full year (YYYY) | 2023 | The year of the release; when printed or represented as a string, always written with 4 digits | -| `month` | Short Month (MM) | 2 | The month of the release; when printed or represented as a string, written with 1 or 2 digits as necessary | -| `minor` | | 1 | The incremental number of the release for this month; when printed or represented as a string, written with 1 or two digits as necessary | -| `releaselevel` | | 'dev' | A string representing the qualifications of this build | diff --git a/docs/reference/elements/py-config.md b/docs/reference/elements/py-config.md deleted file mode 100644 index 83397402760..00000000000 --- a/docs/reference/elements/py-config.md +++ /dev/null @@ -1,493 +0,0 @@ -# <py-config> - -Use the `` tag to set and configure general metadata along with declaring dependencies for your PyScript application. The configuration has to be set in either [TOML](https://toml.io/)(default) or [JSON](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON) format. - -If you are unfamiliar with TOML, consider [reading about it](https://learnxinyminutes.com/docs/toml/) or if you are unfamiliar with JSON, consider reading [freecodecamp's JSON for beginners](https://www.freecodecamp.org/news/what-is-json-a-json-file-example/) guide for more information. - -The `` element should be placed within the `` element. - -## Attributes - -| attribute | type | default | description | -|-----------|--------|---------|---------------------------------------------------------------------------------------------------------| -| **type** | string | "toml" | Syntax type of the ``. Value can be `json` or `toml`. Default: "toml" if type is unspecifed. | -| **src** | url | | Source url to an external configuration file. | - -## Examples - -### Defining an inline config - -- `` using TOML (default) - -```{note} -Reminder: when using TOML, any Arrays of Tables defined with double-brackets (like `[[interpreters]]` and `[[fetch]]` must come after individual keys (like `plugins = ...` and `packages=...`) -``` - -```html - - [splashscreen] - autoclose = true - - [[interpreters]] - src = "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js" - name = "pyodide-0.21.2" - lang = "python" - -``` - -- `` using JSON via `type` attribute - -```html - - { - "splashscreen": { - "autoclose": true - }, - "interpreters": [{ - "src": "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js", - "name": "pyodide-0.21.2", - "lang": "python" - }] - } - -``` - -### Defining a file based config - -- Use of the `src` attribute - -```html - -``` -where `custom.toml` contains - -```toml -[splashscreen] -autoclose = true - -[[interpreters]] -src = "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js" -name = "pyodide-0.21.2" -lang = "python" -``` - -- JSON using the `type` and `src` attribute - -```html - -``` -where `custom.json` contains - -```json -{ - "splashscreen": { - "autoclose": true, - }, - "interpreters": [{ - "src": "https://cdn.jsdelivr.net/pyodide/v0.21.2/full/pyodide.js", - "name": "pyodide-0.21.2", - "lang": "python" - }] -} -``` - -### Mixing inline and file based configs - -One can also use both i.e pass the config from `src` attribute as well as specify it as `inline`. So the following snippet is also valid: - -```html - - [[fetch]] - files = ["./utils.py"] - -``` - -This can also be done via JSON using the `type` attribute. - -```html - - { - "fetch": [{ - "files": ["./utils.py"] - }] - } - -``` - -Note: While the `` tag supports both TOML and JSON, one cannot mix the type of config passed from 2 different sources i.e. the case when inline config is in TOML format while config from src is in JSON format is NOT allowed. Similarly for the opposite case. - ---- - -This is helpful in cases where a number of applications share a common configuration (which can be supplied via `src`), but their specific keys need to be customised and overridden. - -The keys supplied through `inline` override the values present in config supplied via `src`. - -## Dependencies and Packages - -One can also declare dependencies so as to get access to many 3rd party OSS packages that are supported by PyScript. -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). - -Package dependencies in the `` can be declared by using the direct link to the package URL (whl or any other format supported by the chosen interpreter) or by just providing the package name [and version]. If only the name [and version] are provided, packages will be installed directly from what's provided by your interpreter or from PyPI. - -NOTICE that only pure python packages from PyPI will work and packages with C dependencies will not. These need to be built specifically for WASM (please, consult the Pyodide project for more information about what's supported and on how to build packages with C dependencies) - -```html - - packages = ["./static/wheels/travertino-0.1.3-py3-none-any.whl"] - -``` - -OR in JSON like - -```html - - { - "packages": ["./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 `display(fig, target="plot")`, which takes the graph and displays it in the element with the id `plot`. - - -```html - - - - - - - -

Let's plot random numbers

-
- - { - "packages": ["numpy", "matplotlib"] - } - - - 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) - display(fig, target="plot") - - - -``` - -## 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 -`files` key within the `fetch` section. Refer to the [fetch](#fetch) section for -more details. - -```html - - - - - - - -

Let's plot random numbers

-
- - packages = ["numpy", "matplotlib"] - - [[fetch]] - files = ["./data.py"] - - - 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) - display(fig, target="plot") - - - -``` - -## Supported configuration values - -The following optional values are supported by ``: -| Value | Type | Description | -| ------ | ---- | ----------- | -| `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. | -| `description` | string | Description 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. | -| `schema_version` | number | The version of the config schema which determines what all keys are supported. This can be supplied by the user so PyScript knows what to expect in the config. If not supplied, the latest version for the schema is automatically used. | -| `type` | string | Type of the project. The default is an "app" i.e. a user application | -| `author_name` | string | Name of the author. | -| `author_email` | string | Email of the author. | -| `license` | string | License to be used for the user application. | -| `autoclose_loader` | boolean | If false, PyScript will not close the loading splash screen when the startup operations finish. | -| `packages` | List of Packages | Dependencies on 3rd party OSS packages are specified here. The default value is an empty list. | -| `fetch` | List of Stuff to fetch | Local Python modules OR resources from the internet are to be specified here using a Fetch Configuration, described below. The default value is an empty list. | -| `plugins` | List of Plugins | List of Plugins are to be specified here. The default value is an empty list. | -| `interpreters` | List of Interpreters| List of Interpreter configurations, described below. The default value contains a single Pyodide based interpreter. **Note:** Currently, only a single interpreter is supported. | -| `runtimes` {bdg-warning-line}`Deprecated` | List of Runtimes | This value is deprecated, please use `interpreters`. List of runtime configurations, described below. The default value contains a single Pyodide based interpreter. | - -### Fetch - -A fetch configuration consists of the following: - -| Value | Type | Description | -|--------------|-----------------|-------------------------------------------------| -| `from` | string | Base URL for the resource to be fetched. | -| `to_folder` | string | Name of the folder to create in the filesystem. | -| `to_file` | string | Name of the target to create in the filesystem. | -| `files` | List of strings | List of files to be downloaded. | - -The parameters `to_file` and `files` shouldn't be supplied together. - -#### Mechanism - -The `fetch` mechanism works in the following manner: - -- If both `files` and `to_file` parameters are supplied: Error! -- `from` defaults to an empty string i.e. `""` to denote relative URLs of the serving directory -- `to_folder` defaults to `.` i.e. the current working directory of the filesystem -- If `files` is specified - - for each `file` present in the `files` array - - the `sourcePath` is calculated as `from + file` - - the `destination` is calculated as `to_folder + file` - - thus, the object is downloaded from `sourcePath` to `destination` -- Else i.e. `files` is NOT specified - - If `to_file` is specified - - the object is downloaded from `from` to `to_folder + to_file` - - Otherwise, calculate the `filename` at the end of `from` i.e. the part after last `/` - - the object is downloaded from `from` to `to_folder + filename at the end of 'from'` - -Learn more about `fetch` on PyScript [here](https://jeff.glass/post/whats-new-pyscript-2022-12-1) - -#### Use-Cases - -Assumptions: - -The directory being served has the following tree structure: - -``` -content/ - ├─ index.html <<< File with - ├─ info.txt - ├─ data/ - │ ├─ sensordata.csv - ├─ packages/ - │ ├─ my_package/ - │ │ ├─ __init__.py - │ │ ├─ helloworld/ - │ │ │ ├─ __init__.py - │ │ │ ├─ greetings.py -``` - -1. Fetching a single file - -```html - - [[fetch]] - files = ['info.txt'] - -``` - -```html - - with open('info.txt', 'r') as fp: - print(fp.read()) - -``` - -2. Single File with Renaming - -```html - - [[fetch]] - from = 'info.txt' - to_file = 'info_loaded_from_web.txt' - -``` - -```html - - with open('info_loaded_from_web.txt', 'r') as fp: - print(fp.read()) - -``` - -3. Single File to another Directory - -```html - - [[fetch]] - files = ['info.txt'] - to_folder = 'infofiles/loaded_info' - -``` - -```html - - with open('infofiles/loaded_info/info.txt', 'r') as fp: - print(fp.read()) - -``` - -4. Single File to another Directory with Renaming - -```html - - [[fetch]] - from = 'info.txt' - to_folder = 'infofiles/loaded_info' - to_file = 'info_loaded_from_web.txt' - -``` - -```html - - with open('infofiles/loaded_info/info_loaded_from_web.txt', 'r') as fp: - print(fp.read()) - -``` - -5. Single file from a folder to the current working directory - -```html - - [[fetch]] - from = 'data/' - files = ['sensordata.csv'] - -``` - -```html - - with open('./sensordata.csv', 'r') as fp: - print(fp.read()) - -``` - -6. Single file from a folder to another folder (i.e. not the current working directory) - -```html - - [[fetch]] - from = 'data/' - to_folder = './local_data' - files = ['sensordata.csv'] - -``` - -```html - - with open('./local_data/sensordata.csv', 'r') as fp: - print(fp.read()) - -``` - -7. Multiple files preserving directory structure - -```html - - [[fetch]] - from = 'packages/my_package/' - files = ['__init__.py', 'helloworld/greetings.py', 'helloworld/__init__.py'] - to_folder = 'custom_pkg' - -``` - -```html - - from custom_pkg.helloworld.greetings import say_hi - print(say_hi()) - -``` - -8. From an API endpoint which doesn't end in a filename - -```html - - [[fetch]] - from = 'https://catfact.ninja/fact' - to_file = './cat_fact.json' - -``` - -```html - - import json - with open("cat_fact.json", "r") as fp: - data = json.load(fp) - -``` - -### Interpreter - -An interpreter configuration consists of the following: - -| Value | Type | Description | -|--------|-------------------|-------------| -| `src` | string (Required) | URL to the interpreter source. | -| `name` | string | Name of the interpreter. 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 interpreter. This field can be used by the application author to provide clarification. It currently has no implications on how PyScript behaves. | - -#### Example - -- The default interpreter is `pyodide`, another version of which can be specified as following - -```html - - [[interpreters]] - src = "https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js" - name = "pyodide-0.20.0" - lang = "python" - -``` - -```{note} -Currently, PyScript supports a single interpreter, this may change in the future. -``` - -## Supplying extra information (or metadata) - -Besides the above schema, a user can also supply any extra keys and values that are relevant as metadata information or perhaps are being used within the application. - -For example, a valid config could also be with the snippet below: - -```html - - magic = "unicorn" - -``` - -OR in JSON like - -```html - - { - "magic": "unicorn" - } - -``` - -If this `"magic"` key is present in config supplied via `src` and also present in config supplied via `inline`, then the value in the inline config is given priority i.e. the overriding process also works for custom keys. diff --git a/docs/reference/elements/py-repl.md b/docs/reference/elements/py-repl.md deleted file mode 100644 index 244211e54d7..00000000000 --- a/docs/reference/elements/py-repl.md +++ /dev/null @@ -1,48 +0,0 @@ -# <py-repl> - -The `` element provides a REPL(Read Eval Print Loop) to evaluate multi-line Python and display output. - -## Attributes - -| attribute | type | default | description | -|-------------------|---------|---------|---------------------------------------| -| **auto-generate** | boolean | | Auto-generates REPL after evaluation | -| **output-mode** | string | "" | Determines whether the output element is cleared prior to writing output | -| **output** | string | | The id of the element to write `stdout` and `stderr` to | -| **stderr** | string | | The id of the element to write `stderr` to | - - -### `auto-generate` -If a \ tag has the `auto-generate` attribute, upon execution, another \ tag will be created and added to the DOM as a sibling of the current tag. - -### `output-mode` -By default, the element which displays the output from a REPL is cleared (`innerHTML` set to "") prior to each new execution of the REPL. If `output-mode` == "append", that element is not cleared, and the output is appended instead. - -### `output` -The ID of an element in the DOM that `stdout` (e.g. `print()`), `stderr`, and the results of executing the repl are written to. Defaults to an automatically-generated \ as the next sibling of the REPL itself. - -### `stderr` -The ID of an element in the DOM that `stderr` will be written to. Defaults to None, though writes to `stderr` will still appear in the location specified by `output`. - -## Examples - -### `` element set to auto-generate - -```html - -``` - -### `` element with output - -The following will write "Hello! World!" to the div with id `replOutput`. - -```html -
- - print("Hello!") - hello = "World!" - hello - -``` - -Note that if we `print` from the REPL (or otherwise write to `sys.stdout`), the output will be printed in the [`py-terminal`](../plugins/py-terminal.md) if is enabled. diff --git a/docs/reference/elements/py-script.md b/docs/reference/elements/py-script.md deleted file mode 100644 index 51996483cf0..00000000000 --- a/docs/reference/elements/py-script.md +++ /dev/null @@ -1,126 +0,0 @@ -# <py-script> - -The `` element lets you execute multi-line Python scripts both inline and via a src attribute. - -## Attributes - -| attribute | type | default | description | -|-----------|--------|---------|------------------------------| -| **src** | url | | You don't need to add long python code in py-script, you can provide url of the python source file in the py-script tag with the `src` attribute. When a Python file is referred with the `src` attribute it is executed, and then added to the namespace where it was referred. | -| **output**| string | | The id of a DOM element to route `sys.stdout` and `stderr` to, in addition to sending it to the ``| -| **stderr**| string | | The id of a DOM element to route just `sys.stderr` to, in addition to sending it to the ``| - -### output - -If the `output` attribute is provided, any output to [sys.stdout](https://docs.python.org/3/library/sys.html#sys.stdout) or [sys.stderr](https://docs.python.org/3/library/sys.html#sys.stderr) is written to the DOM element with the ID matching the attribute. If no DOM element is found with a matching ID, a warning is shown. The msg is output to the `innerHTML` of the HTML Element, with newlines (`\n'`) converted to breaks (``). - -This output is in addition to the output being written to the developer console and the `` if it is being used. - -### stderr - -If the `stderr` attribute is provided, any output to [sys.stderr](https://docs.python.org/3/library/sys.html#sys.stderr) is written to the DOM element with the ID matching the attribute. If no DOM element is found with a matching ID, a warning is shown. The msg is output to the `innerHTML` of the HTML Element, with newlines (`\n'`) converted to breaks (``). - -This output is in addition to the output being written to the developer console and the `` if it is being used. - - -## Examples - -### Inline `` element - -Let's execute this multi-line Python script to compute π and print it back onto the page - -```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) - - - -``` - -### Using `` element with `src` attribute - -we can also move our python code to its own file and reference it via the `src` attribute. - - -```python -# compute_pi.py -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) -``` - -Since both compute_pi.py and index.html are in the same directory, we can reference the python file with a relative path. - -```html - - - - - - - - - -``` - -### 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 can -use the `Element` class to create a python object for interacting with -page elements. Objects created from the `Element` class provide the `.write()` method -which enables you to send strings into the page elements referenced by those objects. - -For example, we'll add some style elements and provide placeholders for -the `` tag to write to. - -```html - - - - - - - - -

Today is

-
-
- - import datetime as dt - Element('today').write(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) - Element('pi').write(f'π is approximately {pi:.3f}') - - - -``` diff --git a/docs/reference/exceptions.md b/docs/reference/exceptions.md deleted file mode 100644 index a298e8af772..00000000000 --- a/docs/reference/exceptions.md +++ /dev/null @@ -1,52 +0,0 @@ -# Exceptions and error codes - -When creating pages with PyScript, you may encounter exceptions. Each handled exception will contain a specific code which will give you more information about it. -This reference guide contains the error codes you might find and a description of each of them. - -## User Errors - -| Error code | Description | Recommendation | -|------------|--------------------------------|--------------------| -| PY1000 | Invalid configuration supplied | Confirm that your `py-config` tag is using a valid `TOML` or `JSON` syntax and is using the correct configuration type. | -| PY1001 | Unable to install package(s) | Confirm that the package contains a pure Python 3 wheel or the name of the package is correct. | -| PY2000 | Invalid plugin file extension | Only `.js` and `.py` files can be used when loading user plugins. Please confirm your path contains the file extension. | -| PY2001 | Plugin doesn't contain a default export | Please add `export default` to the main plugin class. | -| PY9000 | Top level await is deprecated | Create a coroutine with your code and schedule it with `asyncio.ensure_future` or similar | - - - -## Fetch Errors - -These error codes are related to any exception raised when trying to fetch a resource. If, while trying to fetch a resource, we encounter a status code that is not 200, the error code will contain the HTTP status code and the `PY0` prefix. For example, if we encounter a 404 error, the error code will be `P02404`. - - -| Error Code | Description | -|------------|--------------------------------------------------------------| -| PY0001 | Generic fetch error, failed to fetch page from the server | -| PY0002 | Name supplied when trying to fetch resource is invalid | -| PY0401 | You are not authorized to access this resource. | -| PY0403 | You are not allowed to access this resource. | -| PY0404 | The page you are trying to fetch does not exist. | -| PY0500 | The server encountered an internal error. | -| PY0503 | The server is currently unavailable. | - -## PY1001 - -Pyscript cannot install the package(s) you specified in your `py-config` tag. This can happen for a few reasons: - -- The package does not exist -- The package does not contain a pure Python 3 wheel -- An error occurred while trying to install the package - -An error banner should appear on your page with the error code and a description of the error or a traceback. You can also check the developer console for more information. - -## PY2001 - -Javascript plugins must export a default class. This is required for PyScript to be able to load the plugin. Please add `export default` to the main plugin class. For example: - -```js -export default class HelloWorldPlugin { - afterStartup(runtime) { - console.log("Hello World from the plugin!"); - } -``` diff --git a/docs/reference/faq.md b/docs/reference/faq.md deleted file mode 100644 index bd459949be6..00000000000 --- a/docs/reference/faq.md +++ /dev/null @@ -1,160 +0,0 @@ -# Frequently asked questions - -As the world’s most popular programming language, Python is powerful in its capabilities and comparatively easy to learn, yet the limitations cannot be ignored: it’s hard to install Python and all necessary dependencies; it’s glued to the backend without the ability to make apps or websites; and it’s difficult to share your work. - -What if we could remove those limitations, making the power of Python accessible to the masses? The makers of PyScript set out to do just that by enabling Python in the browser for frontend web and application development. No more complicated installs. Projects can be shared with anyone, anywhere—all you need is a browser. - -We are fully leaning into the idea that the browser is the most ubiquitous VM by using Python to build a graphical, programmable OS on top to make and share applications. Harness the full power of canvas, webGL, WASI, and even in-browser support for P2P and CRDTs for serverless data sharing and collaboration. - -> “This is the exciting beginning for supporting new ways of programming, building, sharing, and deploying applications. Ultimately, we should be spending our time thinking and writing applications to solve the real problems we have, not dealing with mundane, hardware-induced challenges. Let's make programming more fun and simple.” - Fabio Pliger - -## Why PyScript? - -Exponentially expand accessibility and use cases for Python by enabling Python in the browser for building UIs. Reproduce environments without having to download Python or conda or install other packages. Projects can be shared with anyone and deployed anywhere—all you need is a browser and a web-accessible device (computer, tablet, or mobile). - -We are fully leaning into the idea that the browser is the most ubiquitous VM by using Python to build a graphical, programmable operating system on top of the browser to make and share applications. Harness the full power of canvas, webGL, WASI, and even in-browser support for P2P and CRDTs for serverless data sharing and collaboration. - -- [PyCon US 2022 Keynote with Peter Wang](https://anaconda.cloud/pyscript-pycon2022-peter-wang-keynote) -- [Example demos from Keynote](https://pyscript.net/examples/index.html) - -## What is PyScript? - -PyScript is a framework that allows users to create rich Python applications in the browser using HTML's interface and the power of [Pyodide — Version 0.20.0](https://pyodide.org/en/stable/), [WebAssembly](https://webassembly.org/), and modern web technologies. The PyScript framework provides users at every experience level with access to an expressive, easy-to-learn programming language with countless applications. - -What is PyScript? Well, here are some of the core components: - -- Python in the browser: Enable drop-in content, external file hosting, and application hosting without the reliance on server-side configuration - -- Python ecosystem: Run many popular packages of Python and the scientific stack (such as numpy, pandas, scikit-learn, and more) - -- Python with JavaScript: Bi-directional communication between Python and Javascript objects and namespaces - -- Environment management: Allow users to define what packages and files to include for the page code to run - -- Visual application development: Use readily available curated UI components, such as buttons, containers, text boxes, and more - -- Flexible framework: A flexible framework that can be leveraged to create and share new pluggable and extensible components directly in Python - -All that to say... PyScript is just HTML, only a bit (okay, maybe a lot) more powerful, thanks to the rich and accessible ecosystem of Python libraries. - -In short, our mission is to enable programming for the 99%. - -## How can a user get started? - -Leveraging Python in HTML is literally as simple as adding a few lines of code to your page. The best place to learn more, get started, and stay updated on all things PyScript is [Pyscript.net](http://pyscript.net/). Additional shareable resources below: - -- [PyScript Repo](https://github.com/pyscript/pyscript) -- [PyScript Announcement Blog](https://www.anaconda.com/blog/pyscript-python-in-the-browser) -- [PyScript Technical Blog](https://engineering.anaconda.com/2022/04/welcome-pyscript.html) -- [PyScript Nucleus Project](https://anaconda.cloud/s/pyscript) -- [PyScript Documentation](https://docs.pyscript.net/) - -## Why isn't this going to be as terrible as PHP? - -This comparison is based on both PHP and PyScript having a similar way of declaring things: put a tag on the page and the interpreter handles it. PHP works on the server side and is itself a whole different programming language that has its own directives and semantics. - -The choice of using tags to allow people to execute Python is explicit; even if this functionality is similar to PHP, it works differently. First of all, everything runs in the browser itself rather than going to the server side. Secondly, PyScript lives close to the text and allows changes to be made to the visual elements. The PyScript REPL can generate output, plus it provides additional visual elements like buttons, titles, and input boxes. PyScript functions as a framework that generates UIs that makes sense as a tag in the html code. - -Currently, both PHP and PyScript operate with only one namespace. However, PyScript will soon support multiple namespaces and different types of isolation of code (scope), along with support for languages beyond Python. - -## Why not just learn JavaScript? - -JavaScript is not only a different language from python, but a challenging language at that. With PyScript, you now have two languages to choose from, with even more on the roadmap. PyScript allows you to use both libraries and makes JavaScript and Python compatible with one another. - -Python is incredibly powerful, super intuitive, and easy to learn. By adding Python to your toolkit, you can use Numpy, SciPy, Pandas, and more, seamlessly. One tradeoff is longer download times, so it isn’t the right tool for everything—but where it is the right tool, it’s almost irreplaceable. - -Ultimately, PyScript will enable the use of a variety of languages, offer a standard set of components that is well linked to the REPLs, and allow you to do an introspection on the code base—you can have, for example, a *modifiable* chart as a python object. - -## Will PyScript replace JavaScript? - -No. PyScript allows Python to leverage HTML, CSS, and JavaScript conventions to build elegant UIs and address general web application building, packaging, distribution, and deployment challenges (a huge pain). We expect the popularity and adoption of HTML, CSS, and JavaScript to rise alongside Python, ultimately making the web a more friendly and hackable place for everyone. That said, we do believe: - -- PyScript will displace some use cases that people have to rely on Javascript for now -- PyScript will heavily leverage and interface with existing powerful, feature-full JS libraries, as appropriate -- PyScript will open up web programming to tens of millions of people who would otherwise not have touched JavaScript; so in this way, it will outpace JavaScript - -But none of these above scenarios lead to a situation where "PyScript replaces all existing JavaScript." Just as Python itself didn't replace C, C++, or Java. But, it did take a LOT of market share for new use cases where those languages would otherwise have been used. - -## What is the difference between PyScript and Pyodide? - -![pyodide-pyscript](../img/pyodide-pyscript.png) - -PyScript provides HTML tags for embedding and executing Python code in your browser. As a ‘glue’ framework, it sits on top of a variety of tools and provides users access to Pyodide, the WebAssembly port of CPython, which is compiled using Emscripten. In other words, Pyodide enables PyScript users to take advantage of real CPython on the browser. - -Together, PyScript and Pyodide allow users to author applications by turning the browser into a code deployment tool that anyone can learn to use. - -With respect to the UI, PyScript is opinionated and purposeful, while Pyodide is agnostic, unopinionated, and intended for more general use. - -## What packages can I use? Can I use anything from PyPI? - -You can use anything within the Pyodide library, and pure python packages from PyPi that do not contain C dependencies should be supported by Pyodide. - -There is a list of packages built in Pyodide in [Packages built in Pyodide — Version 0.20.0](https://pyodide.org/en/stable/usage/packages-in-pyodide.html) (these are mostly packages with C extensions). You can also install pure Python packages from PyPI or custom URLs, assuming they have a wheel. - -In general, Pyodide doesn’t support all Python features—not because of Pyodide itself, but because some concepts just work differently on the browser (think of sockets/websockets, IO, threading, etc.). If it’s a pure python package that doesn’t have any non-supported features, you should expect it to work. If it has C dependencies, etc., don’t expect it to work unless someone builds/ports them. A lot of the features that don’t work can be made to work, but it will take human power to fix. For example, the PyTorch community wanted those features to work, so they rallied around it to make it happen. Expect the set of libraries that work to grow quickly given the volume of package builds coming from the community. - -## This package XXX is not supported because it has C dependencies. How can I make it work? - -See [Creating a Pyodide package — Version 0.20.0](https://pyodide.org/en/stable/development/new-packages.html). - -## Why is PyScript loading so slowly? Why can’t we put things behind a CDN? - -Packages are already served from the JsDelivr CDN. This is not a downloading speed problem—it's WASM assembly time. PyScript loads slowly because the Python standard library and packages are large and WebAssembly code needs to be compiled and run by the browser after they are loaded for the first time. - -Currently, there are efforts to mitigate the problem, and Pyodide is currently working on a bundler, for instance. - -## Is PyScript owned by Anaconda? - -Anaconda doesn’t own PyScript. It is an open source project developed by Anaconda internally, and Anaconda team members are currently the main contributors, but the repo itself is public. We are working on a steering council to ensure the project stays public and owned by the community. - -See [Maintainers](../concepts/governance/maintainers.md). - -See [Governance Policy](../concepts/governance/policy.md). - -## What is the governing model for PyScript? - -See [Governance Policy](../concepts/governance/policy.md). - -## What is the license? - -PyScript uses the Apache-2.0 license. - -Pyodide uses MPL-2.0 license. Various packages are distributed under their corresponding license. - -## Is Pyodide a replacement for CPython? How does PyScript and Pyodide compare to CPython on WASM? - -No. They have different elements that do different things, both of which are additive. - -PyScript sits on top of everything. Pyodide came before the work on CPython and WASM. Patches were created in order for it to work, but now that CPython/WASM are progressing, Pyodide is able to remove a few of those patches. Additionally, CPython doesn’t deal with building Python packages for WASM. WASM related work on upstream CPython will integrate into Pyodide in the near future. - -For a list of differences from “standard” CPython, see [Pyodide Python compatibility — Version 0.20.0](https://pyodide.org/en/stable/usage/wasm-constraints.html). - -## Hasn’t this already been done before by Brython/skulpt? - -No. Brython and Skulpt accomplish different things than PyScript and Pyodide. - -Brython is client-side and functions as syntax on top of Javascript—it is a reimplementation of Python on top of Javascript, without support for packages or a file system. The extraction of a package in normal Python has been replaced completely by something else. You should be able to run code with minimal changes; however, that isn’t possible with Brython. - -Skulpt is a cross compiler from Python to Javascript, leveraged for compatibility with the Python ecosystem. If you want to do any more Python, you would have to send it over. - -Fairly similar syntax to normal Python, but not exactly the same. If Brython was an interpreter and a full Python implementation, it could be used with PyScript to leverage packages like Numpy, but that isn’t possible as it stands today. They do have the Python script tag, but it is a smaller API and not as feature rich—which is why PyScript is built on Pyodide, Emscripten, and WebAssembly. - -## How can I contribute/help? - -**PyScript** - we are currently working on building documentation and a contributing guide. In the meantime, just ask to help on the PyScript [discussions page](https://anaconda.cloud/s/pyscript) or in the [repo](http://github.com/pyscript/pyscript). - -**Pyodide** - refer to [Pyodide docs](https://pyodide.org/en/stable/development/contributing.html). - -## WebAssembly Security - -See [WebAssembly docs](https://webassembly.org/docs/security/). - -## Why don’t Requests and Black work? - -Requests and Black do not work out of the box because they weren’t meant for the browser. On the browser, sockets multiprocessing works differently, so there is work to be done to actually match things. - -For Black, it’s a design choice that can be patched. This is currently being addressed by the team at Pyodide. - -Requests do not work because of the sockets issue (sockets and websockets are two different things) and requests are blocking—which you don’t want in the browser. It’ll require putting the interpreter on a webworker and utilizing an assistant, but on the main thread it’s unlikely that it’ll work. - -There are options as a path forward. For example, Requests can be leveraged using javascript libraries, or building a python async version of Requests API or a python wrapper for fetch (pyfetch), etc. The websockets library has a client side that could be made to work—given that it has all asynchronous APIs, there’s nothing fundamentally difficult about getting it to work. diff --git a/docs/reference/index.md b/docs/reference/index.md deleted file mode 100644 index d52f247eb92..00000000000 --- a/docs/reference/index.md +++ /dev/null @@ -1,54 +0,0 @@ -# Reference - -```{toctree} ---- -maxdepth: 1 -glob: -caption: Elements ---- -elements/* -``` - -```{toctree} ---- -maxdepth: 1 -glob: -caption: Modules ---- -modules/* -``` - -```{toctree} ---- -maxdepth: 1 -glob: -caption: Plugins ---- -plugins/* -``` - -```{toctree} ---- -maxdepth: 1 -glob: -caption: API ---- -API/* -``` - -```{toctree} ---- -maxdepth: 2 -glob: -caption: Exceptions ---- -exceptions -``` - -```{toctree} ---- -maxdepth: 1 -caption: Miscellaneous ---- -faq -``` diff --git a/docs/reference/modules/pyscript.md b/docs/reference/modules/pyscript.md deleted file mode 100644 index 74033ff00b7..00000000000 --- a/docs/reference/modules/pyscript.md +++ /dev/null @@ -1,77 +0,0 @@ -# pyscript - -The code underlying PyScript is a TypeScript/JavaScript module, which is loaded and executed by the browser. This is what loads when you include, for example, ` -``` -```js -//example result -Object { year: 2022, month: 11, patch: 1, releaselevel: "dev" } -``` - -## pyscript.interpreter - -The Interpreter object which is responsible for executing Python code in the Browser. Currently, all interpreters are assumed to be Pyodide interpreters, but there is flexibility to expand this to other web-based Python interpreters in future versions. - -The Interpreter object has the following attributes - -| attribute | type | description | -|---------------------|-----------------------|---------------------------------------------------------------------------------| -| **src** | string | The URL from which the current interpreter was fetched | -| **interface** | InterpreterInterface | A reference to the interpreter object itself | -| **globals** | any | The globals dictionary of the interpreter, if applicable/accessible | -| **name (optional)** | string | A user-designated name for the interpreter | -| **lang (optional)** | string | A user-designation for the language the interpreter runs ('Python', 'C++', etc) | - -### pyscript.interpreter.src - -The URL from which the current interpreter was fetched. - -### pyscript.interpreter.interface - -A reference to the Interpreter wrapper that PyScript uses to execute code. object itself. This allows other frameworks, modules etc to interact with the same [(Pyodide) interpreter instance](https://pyodide.org/en/stable/usage/api/js-api.html) that PyScript uses. - -For example, assuming we've loaded Pyodide, we can access the methods of the Pyodide interpreter as follows: - -```html - - -``` - -### pyscript.interpreter.globals - -A proxy for the interpreter's `globals()` dictionary. For example: - -```html - - x = 42 - - - - -``` -### pyscript.interpreter.name - -A user-supplied string for the interpreter given at its creation. For user reference only - does not affect the operation of the interpreter or PyScript. - -### PyScript.interpreter.lang - -A user-supplied string for the language the interpreter uses given at its creation. For user reference only - does not affect the operation of the interpreter or PyScript. diff --git a/docs/reference/plugins/py-splashscreen.md b/docs/reference/plugins/py-splashscreen.md deleted file mode 100644 index 3c3e84ce48f..00000000000 --- a/docs/reference/plugins/py-splashscreen.md +++ /dev/null @@ -1,65 +0,0 @@ - -# <py-splashscreen> - -This is one of the core plugins in PyScript, which is active by default. The splashscreen is the first thing you see when you open a page with Pyscript while it is loading itself and all the necessary resources. - -## Configuration - -You can control how `` behaves by setting the value of the `splashscreen` configuration in your ``. - - -| parameter | default | description | -|-------------|-----------|-------------| -| `autoclose` | `true` | Whether to close the splashscreen automatically when the page is ready or not | -| `enabled` | `true` | Whether to show the splashscreen or not | - -### Examples - -#### Disabling the splashscreen - -If you don't want the splashscreen to show and log any loading messages, you can disable it by setting the splashscreen option `enabled` to `false`. - -```html - - [splashscreen] - enabled = false - -``` - -#### Disabling autoclose - -If you want to keep the splashscreen open even after the page is ready, you can disable autoclose by setting `autoclose` to `false`. - -```html - - [splashscreen] - autoclose = false - -``` - -## Adding custom messages - -You can add custom messages to the splashscreen. This is useful if you want to show the user that something is happening in the background for your PyScript app. - -There are two ways to add your custom messages to the splashscreen, either by dispatching a new custom event, `py-status-message` to the document: - - -```js -document.dispatchEvent(new CustomEvent("py-status-message", {detail: "Hello, world!"})) -``` - -Or by using the `log` method of the `py-splashscreen` tag directly: - -```js -const splashscreen = document.querySelector("py-splashscreen") -splashscreen.log("Hello, world!") -``` - -If you wish, you can also send messages directly to the splashscreen from your python code: - -```python -from js import document - -splashscreen = document.querySelector("py-splashscreen") -splashscreen.log("Hello, world!") -``` diff --git a/docs/reference/plugins/py-terminal.md b/docs/reference/plugins/py-terminal.md deleted file mode 100644 index 1b3b7265da4..00000000000 --- a/docs/reference/plugins/py-terminal.md +++ /dev/null @@ -1,57 +0,0 @@ -# <py-terminal> - -This is one of the core plugins in PyScript, which is active by default. With it, you can print to `stdout` and `stderr` from your python code, and the output will be displayed on the page in ``. - -## Configuration - -You can control how `` behaves by setting the value of the `terminal` configuration in your ``, together with the `docked` one. - -For the **terminal** field, these are the values: - -| value | description | -|-------|-------------| -| `false` | Don't add `` to the page | -| `true` | Automatically add a `` to the page | -| `"auto"` | This is the default. Automatically add a ``, to the page. The terminal is initially hidden and automatically shown as soon as something writes to `stdout` and/or `stderr` | - -For the **docked** field, these are the values: - -| value | description | -|-------|-------------| -| `false` | Don't dock `` to the page | -| `true` | Automatically dock a `` to the page | -| `"docked"` | This is the default. Automatically add a ``, to the page. The terminal, once visible, is automatically shown at the bottom of the page, covering the width of such page | - -Please note that **docked** mode is currently used as default only when `terminal="auto"`, or *terminal* default, is used. - -In all other cases it's up to the user decide if a terminal should be docked or not. - - -### Examples - -```html - - terminal = true - docked = false - - - - print("Hello, world!") - -``` - -This example will create a new ``, the value "Hello, world!" that was printed will show in it. - -You can also add one (or more) `` to the page manually. - -```html - - print("Hello, world!") - - - -``` - -```{note} -If you include a `` in the page, you can skip `terminal` from your ``. -``` 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/getting-started.md b/docs/tutorials/getting-started.md deleted file mode 100644 index 6e5456edaab..00000000000 --- a/docs/tutorials/getting-started.md +++ /dev/null @@ -1,269 +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/)) and a text editor, even though using your [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) of choice might be convenient. - -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](https://pyscript.net). - -If you want to download the source and build it yourself, follow -the instructions in the [README.md](https://github.com/pyscript/pyscript/blob/main/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!') - - - -``` - -## A more complex example - -Now that we know how you can create a simple 'Hello, World!' example, let's see a more complex example. This example will use the Demo created by [Cheuk Ting Ho](https://github.com/Cheukting). In this example, we will use more features from PyScript. - -### Setting up the base index file - -Let's create a new file called `index.html` and add the following content: - -```html - - - Ice Cream Picker - - - - - - - - -``` - -In this first step, we have created the index file, imported `pyscript.css` and `pyscript.js`. We are ready to start adding the elements we need for our application. - -### Importing the needed libraries - -For this example, we will need to install `pandas` and `matplotlib`. We can install libraries using the `` tag so we can import them later. Please refer to the [``](../reference/elements/py-config.md) documentation for more information. - -```html - - - Ice Cream Picker - - - - - - - - packages = ["matplotlib", "pandas"] - - - - -``` - -### Importing the data and exploring - -Now that we have installed the needed libraries, we can import and explore the data. In this step, we need to create a `` tag to import our dependencies, read the data with pandas and then use `py-repl` to explore the data. - -You may want to read the [``](../reference/elements/py-script.md) and [``](../reference/elements/py-repl.md) documentation for more information about these elements. - - -```html - - - Ice Cream Picker - - - - - - - - packages = ["matplotlib", "pandas"] - - - - import pandas as pd - - from pyodide.http import open_url - - url = ( - "https://raw.githubusercontent.com/Cheukting/pyscript-ice-cream/main/bj-products.csv" - ) - ice_data = pd.read_csv(open_url(url)) - - - - ice_data - - - -``` - -Note that we are adding `ice_data` to `py-repl` to pre-populate the REPL with this variable, so you don't have to type it yourself. - -### Creating the plot - -Now that we have the data, we can create the plot. We will use the `matplotlib` library to make the plot. We will use the `display` API to display the plot on the page. You may want to read the [`display`](../reference/API/display.md) documentation for more information. - -```html - - - Ice Cream Picker - - - - - - - - packages = ["matplotlib", "pandas"] - - - - import pandas as pd - import matplotlib.pyplot as plt - - from pyodide.http import open_url - - url = ( - "https://raw.githubusercontent.com/Cheukting/pyscript-ice-cream/main/bj-products.csv" - ) - ice_data = pd.read_csv(open_url(url)) - - def plot(data): - plt.rcParams["figure.figsize"] = (22,20) - fig, ax = plt.subplots() - bars = ax.barh(data["name"], data["rating"], height=0.7) - ax.bar_label(bars) - plt.title("Rating of ice cream flavours of your choice") - display(fig, target="graph-area", append=False) - - plot(ice_data) - - - - ice_data - - -
- - -``` - -### Select specific flavours - -Now that we have a way to explore the data using `py-repl` and a way to create the plot using all of the data, it's time for us to add a way to select specific flavours. - -```html - - - Ice Cream Picker - - - - - - - - packages = ["matplotlib", "pandas"] - - - - import js - import pandas as pd - import matplotlib.pyplot as plt - - from pyodide.http import open_url - from pyodide.ffi import create_proxy - - url = ( - "https://raw.githubusercontent.com/Cheukting/pyscript-ice-cream/main/bj-products.csv" - ) - ice_data = pd.read_csv(open_url(url)) - - current_selected = [] - flavour_elements = js.document.getElementsByName("flavour") - - def plot(data): - plt.rcParams["figure.figsize"] = (22,20) - fig, ax = plt.subplots() - bars = ax.barh(data["name"], data["rating"], height=0.7) - ax.bar_label(bars) - plt.title("Rating of ice cream flavours of your choice") - display(fig, target="graph-area", append=False) - - def select_flavour(event): - for ele in flavour_elements: - if ele.checked: - current_selected = ele.value - break - if current_selected == "ALL": - plot(ice_data) - else: - filter = ice_data.apply(lambda x: ele.value in x["ingredients"], axis=1) - plot(ice_data[filter]) - - ele_proxy = create_proxy(select_flavour) - - for ele in flavour_elements: - if ele.value == "ALL": - ele.checked = True - current_selected = ele.value - ele.addEventListener("change", ele_proxy) - - plot(ice_data) - - - -
- Select your 🍨 flavour:
- - - - - - - - - - - - -
- - - ice_data - - -
- - -``` diff --git a/docs/tutorials/index.md b/docs/tutorials/index.md deleted file mode 100644 index 457fab3efa4..00000000000 --- a/docs/tutorials/index.md +++ /dev/null @@ -1,39 +0,0 @@ -# Tutorials - -This section contains pyscript tutorials. Each tutorial is a self-contained document that will guide you through a specific topic. - -## Getting Started - -This tutorial will guide you through getting started with PyScript, from installation to writing your first PyScript application. The getting started will show you how to specify dependencies, read a csv file from the web, use `pandas` and `matplotlib` and how to handle user input. - -[Read the get started tutorial](getting-started.md) - - -## Basics - -This section contains tutorials about the basics of PyScript. - -```{toctree} ---- -maxdepth: 1 -glob: ---- -writing-to-page -py-click -requests -``` - -## PyScript Configuration - -This section contains tutorials about the PyScript configuration using the `` tag. - - -```{toctree} ---- -maxdepth: 1 -glob: ---- -py-config-fetch -py-config-interpreter -writing-to-page -``` diff --git a/docs/tutorials/py-click.md b/docs/tutorials/py-click.md deleted file mode 100644 index f17436e08a1..00000000000 --- a/docs/tutorials/py-click.md +++ /dev/null @@ -1,127 +0,0 @@ -# Handling click events - -This tutorial will show you how to use the `py-click` attribute to handle mouse clicks on elements on your page. The `py-click` attribute is a special attribute that allows you to specify a Python function that will be called when the element is clicked. - -## Development setup - -Let's start by building the base HTML page. We will create an HTML page with a button and a paragraph. When the button is clicked, the paragraph will show the current time. - - -```html - - - - - - - Current Time - - - - - - - -``` - -## Adding elements to the page - -Let's add a button and a paragraph to the page. The button will have the `py-click` attribute, and the paragraph will have the `id` attribute. The `id` attribute is used to identify the element on the page, and the `py-click` attribute will be used to specify the function that will be called when the button is clicked. - -```html - - - - - - - Current Time - - - - - - - -

- - -``` - -There are two things to note here: - -- You must specify an id for an element that uses any `py-*` attribute -- We used the `py-button` class to style the button, this is optional, and these rules are coming from the pyscript.css that we added in the `` section. - -## Creating the Python function - -In this step, we will create the Python function that will be called when the button is clicked. This function will get the current time and update the paragraph with the current time. We will use a `` tag to specify the Python code that will be executed when the page is loaded. - - -```html - - - - - - - Current Time - - - - - - - -

- - - import datetime - - def current_time(): - now = datetime.datetime.now() - - - -``` - -## Writing the time to the page - -If you run the example, you will notice that nothing happened. This is because we still need to update the paragraph with the current time. We can do this by using the [`Element` API](../reference/API/element.md) to get the paragraph element and then update it with the current time with the `write` method. - - -```html - - - - - - - Current Time - - - - - - - -

- - - from pyscript import Element - import datetime - - def current_time(): - now = datetime.datetime.now() - - # Get paragraph element by id - paragraph = Element("current-time") - - # Add current time to the paragraph element - paragraph.write(now.strftime("%Y-%m-%d %H:%M:%S")) - - - -``` - -Now, if you refresh the page and click the button, the paragraph will be updated with the current time. diff --git a/docs/tutorials/py-config-fetch.md b/docs/tutorials/py-config-fetch.md deleted file mode 100644 index 3831d8fa5c1..00000000000 --- a/docs/tutorials/py-config-fetch.md +++ /dev/null @@ -1,188 +0,0 @@ -# Using the fetch from py-config - -This tutorial shows how to use the fetch configuration from `py-config` to fetch two files from a remote server, store them in a local directory, and verify their contents. - -## Development setup - -We will create a todo list application similar to the one in the [examples](https://pyscript.net/examples/todo.html). To do this, we need three things: - - * An `index.html` file containing the HTML for the application. - * A `todo.py` file containing the Python code for the application. - * A `utils.py` file containing some utility functions for the application. - - -We will use the `fetch` configuration from `py-config` to fetch these files from a remote server and store them in a local directory. - -### Creating the html file - -In this first step, we will create the `index.html` file and import both `pyscript.css` and `pyscript.js`. These are needed to run our Python code in the browser and style the application. - -```html - - - - - - - My Todo - - - - - - - - - -``` - -## Fetching the files - -### Using `fetch` to get the python files - -Now we will use the `fetch` configuration from `py-config` to fetch the `todo.py` and `utils.py` files from a remote server and store them in a local directory called `todo`. Here we will fetch files from different URLs, using a `fetch` per item. - -```html - - - - - - - My Todo - - - - - - - - [[fetch]] - from = "https://pyscript.net/examples/" - files = ["utils.py"] - [[fetch]] - from = "https://gist.githubusercontent.com/FabioRosado/faba0b7f6ad4438b07c9ac567c73b864/raw/37603b76dc7ef7997bf36781ea0116150f727f44/" - files = ["todo.py"] - - - -``` - -## Creating a todo application - -### Creating the todo elements - -Now we will create the todo elements in the `body` of the `index.html` file. - -```html - - - - - - - My Todo - - - - - - - - [[fetch]] - from = "https://pyscript.net/examples/" - files = ["utils.py"] - [[fetch]] - from = "https://gist.githubusercontent.com/FabioRosado/faba0b7f6ad4438b07c9ac567c73b864/raw/37603b76dc7ef7997bf36781ea0116150f727f44/" - files = ["todo.py"] - -
-
-

To Do List

-
-
- - -
-
- -
- - -``` - -Our todo application is starting to shape up, although if you try to add any tasks, you will notice that nothing happens. This is because we have not yet imported the `todo.py` file. - -### Importing the needed functions from `todo.py` - -This is where the magic happens. We can import the `todo.py` file by adding it as a source to the `py-script` tag. By specifying the file, pyscript will automatically import the file and run the code in it. - -```html - - - - - - - My Todo - - - - - - - - [[fetch]] - from = "https://pyscript.net/examples/" - files = ["utils.py"] - [[fetch]] - from = "https://gist.githubusercontent.com/FabioRosado/faba0b7f6ad4438b07c9ac567c73b864/raw/37603b76dc7ef7997bf36781ea0116150f727f44/" - files = ["todo.py"] - - - from todo import add_task, add_task_event - -
-
-

To Do List

-
-
- - -
-
- -
- - -``` - -You can now save the file and refresh the page. You should now be able to add tasks to your todo list. - -## That's it! - -You have now created a todo application using pyscript. You can add tasks and mark them as done. Let's take a recap of what we have achieved: - -* We have imported three separate files into our `index.html` file using the `py-config` tag. -* We have created the necessary HTML code to create our todo's -* We have imported functions from the `todo.py` file, using the `py-script` tag. - -For reference, the code from [the gist](https://gist.githubusercontent.com/FabioRosado/faba0b7f6ad4438b07c9ac567c73b864/raw/37603b76dc7ef7997bf36781ea0116150f727f44/todo.py) is the same code that our [todo example](https://pyscript.net/examples/todo.html) uses with a slight change of importing `Element` from `pyscript`. diff --git a/docs/tutorials/py-config-interpreter.md b/docs/tutorials/py-config-interpreter.md deleted file mode 100644 index bfe06de3642..00000000000 --- a/docs/tutorials/py-config-interpreter.md +++ /dev/null @@ -1,88 +0,0 @@ -# Setting a pyodide interpreter - -Pyscript will automatically set the interpreter for you, but you can also set it manually. This is useful if you want to use a different version than the one set by default. - -## Development setup - -To get started, let's create a new `index.html` file and import `pyscript.js`. - -```html - - - - - - - Interpreter - - - - - - - - - -``` - -We are using the pyodide CDN to setup our interpreter, but you can also download the files from [the pyodide GitHub release](https://github.com/pyodide/pyodide/releases/tag/0.22.0a3), unzip them and use the `pyodide.js` file as your interpreter. - -## Setting the interpreter - -To set the interpreter, you can use the `interpreter` configuration in the `py-config` element. In this tutorial, we will use the default `TOML` format, but know that you can also use `json` if you prefer by changing the `type` attribute of the `py-config` element. - -```html - - - - - - - Interpreter - - - - - - - - [[interpreters]] - src = "https://cdn.jsdelivr.net/pyodide/v0.22.0a3/full/pyodide.js" - name = "pyodide-0.22.0a3" - lang = "python" - - - -``` - -## Confirming the interpreter version - -To confirm that the interpreter is set correctly, you can open the DevTools and check the version from the console. But for the sake of this tutorial, let's create a `py-script` tag and print pyodide's version. - -```html - - - - - - - Interpreter - - - - - - - - [[interpreters]] - src = "https://cdn.jsdelivr.net/pyodide/v0.22.0a3/full/pyodide.js" - name = "pyodide-0.22.0a3" - lang = "python" - - - import pyodide - print(pyodide.__version__) - - - -``` diff --git a/docs/tutorials/requests.md b/docs/tutorials/requests.md deleted file mode 100644 index e03faee426b..00000000000 --- a/docs/tutorials/requests.md +++ /dev/null @@ -1,123 +0,0 @@ -# Calling an API using Requests - -This tutorial will show you how to interact with an API using the [Requests](https://requests.readthedocs.io/en/master/) library. Requests is a popular library, but it doesn't work out of the box with Pyscript. We will use the [pyodide-http](https://github.com/koenvo/pyodide-http) library to patch the Requests library, so it works with Pyscript. - - We will use the [JSON Placeholder API](https://jsonplaceholder.typicode.com/), a free fake API that returns fake data. - -## Development Setup - -Let's build the base HTML page to add our `py-config` and `py-script` tags in the next steps. - -```html - - - - - - - Requests Tutorial - - - - - - - -``` - -## Installing the dependencies - -In this step, we will install the dependencies we need to use the Requests library. We will use the `py-config` tag to specify the dependencies we need to install. - -```html - - - - - - - Requests Tutorial - - - - - - - packages = ["requests", "pyodide-http"] - - - -``` - -## Patching the Requests library - -Now that we have installed the dependencies, we need to patch the Requests library to work with Pyscript. We will use the `py-script` tag to specify the code that will be executed when the page is loaded. - -```html - - - - - - - Requests Tutorial - - - - - - - packages = ["requests", "pyodide-http"] - - - - import pyodide_http - pyodide_http.patch_all() - - - - - - - - - Requests Tutorial - - - - - - - packages = ["requests", "pyodide-http"] - - - - import requests - import pyodide_http - - # Patch the Requests library so it works with Pyscript - pyodide_http.patch_all() - - # Make a request to the JSON Placeholder API - response = requests.get("https://jsonplaceholder.typicode.com/todos") - print(response.json()) - - - -``` - -## Conclusion - -In this tutorial, we learned how to use the Requests library to make requests to an API. We also learned how to use the `py-config` and `py-script` tags to install dependencies and execute code when the page is loaded. - -Depending on the API you use, you may need to add additional headers to your request. You can read the [Requests documentation](https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers) to learn more about how to do this. - -You may also be interested in creating your module to make requests. You can read the in-depth guide on [How to make HTTP requests using `PyScript`, in pure Python](../guides/http-requests.md) to learn more about how to do this. diff --git a/docs/tutorials/writing-to-page.md b/docs/tutorials/writing-to-page.md deleted file mode 100644 index d71fa5e8e8f..00000000000 --- a/docs/tutorials/writing-to-page.md +++ /dev/null @@ -1,212 +0,0 @@ -# How to write content to the page - -When creating your PyScript application, you will want to write content to the page. This tutorial will explore the different methods you can use to write content to the page and their differences. - -## Development setup - -To get started, we will create an `index.html` file, import PyScript and start building on top of it. - -```html - - - - - - - Writing to the page - - - - - - - - - -``` - -## Writing content to an element - -Let's first see how we can write content to an element on the page. We will start by creating a `div` element with an `id` of `manual-write`, then create a `py-script` tag that, upon a click of a button, will write 'Hello World' to the `div` element. - -```html - - - - - - - Writing to the page - - - - - - -
- - - - def write_to_page(): - manual_div = Element("manual-write") - manual_div.element.innerText = "Hello World" - - - -``` - -```{note} -When using `py-click` you must supply an `id` to the element you want to use as the trigger. -``` - -We can now open our `index.html` file and click the button. You will see that "Hello World" will appear in the `div` element. You could also write HTML using `manual_div.element.innerHTML` instead of `innerText`. For example: - -```html - - - - - - - Writing to the page - - - - - - -
- - - - def write_to_page(): - manual_div = Element("manual-write") - manual_div.element.innerHTML = "

Hello World

" -
- - -``` - -## Writing content with the `display` API - -The `display` API is a simple way to write content to the page. Not only does it allow you to write content to the page, but it also allows you to display a range of different content types such as images, markdown, svgs, json, etc. - -Using the' display' API, let's reuse our previous example and write "Hello World" to the page. - -```html - - - - - - - Writing to the page - - - - - - -
- -
- - - - def write_to_page(): - manual_div = Element("manual-write") - manual_div.element.innerHTML = "

Hello World

" - - def display_to_div(): - display("I display things!", target="display-write") -
- - -``` - -```{note} -When using the `display` API, you must specify the `target` parameter to tell PyScript where to write the content. If you do not use this parameter, an error will be thrown. -``` - -You may be interested in reading more about the `display` API in the [Display API](../reference/api/display) section of the documentation. - -## Printing to the page - -We couldn't have a tutorial on writing to the page without mentioning the `print` function. The `print` function is a simple way to write content to the page, that any Python developer will be familiar with. When you use the `print` function, the content will be written to the page in a `py-terminal` element. - -```html - - - - - - - Writing to the page - - - - - - -
- -
- - - - - def write_to_page(): - manual_div = Element("manual-write") - manual_div.element.innerHTML = "

Hello World

" - - def display_to_div(): - display("I display things!", target="display-write") - - def print_to_page(): - print("I print things!") -
- - -``` - -You may be surprised to see that when you click the "Print Things!" button, the content is written below the rest of the elements on the page in a black canvas. This is because the `print` function writes content to the page in a `py-terminal` element. You can read more about the `py-terminal` element in the [Terminal Element](../reference/plugins/py-terminal) section of the documentation. - -PyScript comes with the `py-terminal` plugin by default and any `stdout` or `stderr` content will be shown in this element. We can be explicit about where we want the terminal to be shown by adding the `` tag to our HTML. - -```html - - - - - - - Writing to the page - - - - - - -
- -
- -
- -
- - - - def write_to_page(): - manual_div = Element("manual-write") - manual_div.element.innerHTML = "

Hello World

" - - def display_to_div(): - display("I display things!", target="display-write") - - def print_to_page(): - print("I print things!") -
- - -``` diff --git a/examples/altair.html b/examples/altair.html deleted file mode 100644 index 49e724f882d..00000000000 --- a/examples/altair.html +++ /dev/null @@ -1,81 +0,0 @@ - - - Altair - - - - - - - - -
-
- - - packages = [ - "altair", - "pandas", - "vega_datasets" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - 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) - - display(alt.vconcat( - rect + circ, - bar - ).resolve_legend( - color="independent", - size="independent" - ), target="altair") - - -
- - diff --git a/examples/antigravity.html b/examples/antigravity.html deleted file mode 100644 index 307dd9c5223..00000000000 --- a/examples/antigravity.html +++ /dev/null @@ -1,39 +0,0 @@ - - - Antigravity - - - - - - - - - -
- - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - [[fetch]] - files = ["./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 58b0af4354c..00000000000 --- a/examples/antigravity.py +++ /dev/null @@ -1,44 +0,0 @@ -import random - -from js import DOMParser, document, setInterval -from pyodide.ffi 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): - self.target = ( - document.getElementById(target) - if isinstance(target, str) - else document.body - ) - 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/assets/css/examples.css b/examples/assets/css/examples.css deleted file mode 100644 index 8b8bc96e7a5..00000000000 --- a/examples/assets/css/examples.css +++ /dev/null @@ -1,91 +0,0 @@ -body { - margin: 0; -} - -.pyscript { - margin: 0.5rem; -} - -.code { - display: flex; - position: absolute; - right: 0px; - z-index: 9998; - top: 7rem; -} - -@media (max-width: 1300px) { - .code:has(> .code-section-visible) { - width: 90%; - /* Absolute position is messing up the layout on small screens */ - right: 70px; - } -} - -.code-section-hidden { - width: 0px; - display: none; -} - -.code-section-visible { - display: flex; - flex-direction: column; - width: 100%; - background-color: rgb(45 46 53 / 90%); - padding: 1rem; - border-radius: 10px 0px 0px 10px; - color: #c6c6c8; -} -.code-section-visible p { - margin: 0; - font-style: italic; - font-size: small; -} - -.language-html, -.language-python { - float: left; -} - -#view-code-button { - writing-mode: tb-rl; - text-orientation: sideways-right; - background-color: #1d1d22; - color: white; - padding: 0.5rem; - border-radius: 5px; - cursor: pointer; - height: 81px; -} - -nav { - position: sticky; - width: 100%; - top: 0; - left: 0; - z-index: 9999; -} - -.logo { - padding-right: 10px; - font-size: 28px; - height: 30px; - max-width: inherit; -} - -.title { - text-decoration: none; - text-decoration-line: none; - text-decoration-style: initial; - text-decoration-color: initial; - font-weight: 400; - font-size: 1.5em; - line-height: 2em; - white-space: nowrap; -} - -.app-header { - display: flex; - align-items: center; - padding: 0.5rem 1rem; -} diff --git a/examples/assets/css/index.css b/examples/assets/css/index.css deleted file mode 100644 index a14c1078862..00000000000 --- a/examples/assets/css/index.css +++ /dev/null @@ -1,74 +0,0 @@ -.example { - margin-bottom: 5rem; -} - -.example h2 { - /* color: #000000; */ - font-family: "Inconsolata", monospace; - font-size: 2.25rem; - margin-bottom: 1rem; -} - -.card { - height: 15rem; - background-color: var(--color-secondary); - padding: 1rem; - border-radius: 10px; -} - -.card:hover, -.card:hover a, -.card:hover a:visited, -.card:hover h2 { - background-color: var(--color-primary); - color: #1d1d22; -} - -.card a h2 { - color: var(--color-primary); - margin: 0; - font-family: "Inconsolata", monospace; - font-size: 2.25rem; -} - -.card a p { - color: var(--text-color); -} - -a .card { - height: 100%; - display: flex; - flex-direction: column; - justify-content: space-between; -} - -.card-content { - height: 100%; - display: flex; - flex-direction: column; - justify-content: space-between; -} - -.card-content a, -.card-content a:visited { - color: var(--color-primary); -} - -.container-card { - max-width: 1500px; - margin: 0 auto; - display: grid; - gap: 1rem; -} - -@media (min-width: 600px) { - .container-card { - grid-template-columns: repeat(2, 1fr); - } -} - -@media (min-width: 900px) { - .container-card { - grid-template-columns: repeat(4, 1fr); - } -} diff --git a/examples/assets/css/main.css b/examples/assets/css/main.css deleted file mode 100644 index 0a67bb18e69..00000000000 --- a/examples/assets/css/main.css +++ /dev/null @@ -1,25 +0,0 @@ -@import url("https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;700&display=swap"); -@import "./variables.css"; -@import "./reset.css"; - -body { - background: #2d2e35 - url("https://assets.anaconda.com/production/Content/1650828148240.png?w=3240&auto=compress%2Cformat&fit=crop&dm=1650828161&s=c558dc55e0ed1f8419a892e842a5728f") - repeat-x center bottom / 250px; - background-attachment: fixed; - overflow-x: hidden; - color: var(--text-color); -} - -.container { - max-width: 1510px; - margin: auto; - padding: 0 2rem; -} - -.title-main { - font-size: 4.25rem; - font-family: "Inconsolata", monospace; - text-align: center; - margin: 2rem 0; -} diff --git a/examples/assets/css/reset.css b/examples/assets/css/reset.css deleted file mode 100644 index 0620972cb7f..00000000000 --- a/examples/assets/css/reset.css +++ /dev/null @@ -1,22 +0,0 @@ -*, -*:after, -*:before { - margin: 0; - padding: 0; - box-sizing: border-box; - text-decoration: none; -} - -body { - font-size: 100%; - list-style-type: none; -} - -p { - font-family: "Inconsolata", monospace; - font-weight: 400; -} - -a { - text-decoration: none; -} diff --git a/examples/assets/css/variables.css b/examples/assets/css/variables.css deleted file mode 100644 index 88173b4afb0..00000000000 --- a/examples/assets/css/variables.css +++ /dev/null @@ -1,6 +0,0 @@ -:root { - --color-primary: #fda703; - --color-secondary: #1d1d22; - --text-color: white; - --card-shadow: 0px 5px 11px 0px rgb(0 0 0 / 15%); -} diff --git a/examples/assets/prism/prism.min.css b/examples/assets/prism/prism.min.css deleted file mode 100644 index db26413946c..00000000000 --- a/examples/assets/prism/prism.min.css +++ /dev/null @@ -1,3 +0,0 @@ -/* PrismJS 1.29.0 -https://prismjs.com/download.html#themes=prism-okaidia&languages=markup+clike+javascript+python */ -code[class*=language-],pre[class*=language-]{color:#f8f8f2;background:0 0;text-shadow:0 1px rgba(0,0,0,.3);font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto;border-radius:.3em}:not(pre)>code[class*=language-],pre[class*=language-]{background:#272822}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#8292a2}.token.punctuation{color:#f8f8f2}.token.namespace{opacity:.7}.token.constant,.token.deleted,.token.property,.token.symbol,.token.tag{color:#f92672}.token.boolean,.token.number{color:#ae81ff}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#a6e22e}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url,.token.variable{color:#f8f8f2}.token.atrule,.token.attr-value,.token.class-name,.token.function{color:#e6db74}.token.keyword{color:#66d9ef}.token.important,.token.regex{color:#fd971f}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help} diff --git a/examples/assets/prism/prism.min.js b/examples/assets/prism/prism.min.js deleted file mode 100644 index ec4bbe9d8f5..00000000000 --- a/examples/assets/prism/prism.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/* PrismJS 1.29.0 -https://prismjs.com/download.html#themes=prism-okaidia&languages=markup+clike+javascript+python */ -var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(e){var n=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,t=0,r={},a={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(n){return n instanceof i?new i(n.type,e(n.content),n.alias):Array.isArray(n)?n.map(e):n.replace(/&/g,"&").replace(/=g.reach);A+=w.value.length,w=w.next){var E=w.value;if(n.length>e.length)return;if(!(E instanceof i)){var P,L=1;if(y){if(!(P=l(b,A,e,m))||P.index>=e.length)break;var S=P.index,O=P.index+P[0].length,j=A;for(j+=w.value.length;S>=j;)j+=(w=w.next).value.length;if(A=j-=w.value.length,w.value instanceof i)continue;for(var C=w;C!==n.tail&&(jg.reach&&(g.reach=W);var z=w.prev;if(_&&(z=u(n,z,_),A+=_.length),c(n,z,L),w=u(n,z,new i(f,p?a.tokenize(N,p):N,k,N)),M&&u(n,w,M),L>1){var I={cause:f+","+d,reach:W};o(e,n,t,w.prev,A,I),g&&I.reach>g.reach&&(g.reach=I.reach)}}}}}}function s(){var e={value:null,prev:null,next:null},n={value:null,prev:e,next:null};e.next=n,this.head=e,this.tail=n,this.length=0}function u(e,n,t){var r=n.next,a={value:t,prev:n,next:r};return n.next=a,r.prev=a,e.length++,a}function c(e,n,t){for(var r=n.next,a=0;a"+i.content+""},!e.document)return e.addEventListener?(a.disableWorkerMessageHandler||e.addEventListener("message",(function(n){var t=JSON.parse(n.data),r=t.language,i=t.code,l=t.immediateClose;e.postMessage(a.highlight(i,a.languages[r],r)),l&&e.close()}),!1),a):a;var g=a.util.currentScript();function f(){a.manual||a.highlightAll()}if(g&&(a.filename=g.src,g.hasAttribute("data-manual")&&(a.manual=!0)),!a.manual){var h=document.readyState;"loading"===h||"interactive"===h&&g&&g.defer?document.addEventListener("DOMContentLoaded",f):window.requestAnimationFrame?window.requestAnimationFrame(f):window.setTimeout(f,16)}return a}(_self);"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); -Prism.languages.markup={comment:{pattern://,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern://i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity,Prism.languages.markup.doctype.inside["internal-subset"].inside=Prism.languages.markup,Prism.hooks.add("wrap",(function(a){"entity"===a.type&&(a.attributes.title=a.content.replace(/&/,"&"))})),Object.defineProperty(Prism.languages.markup.tag,"addInlined",{value:function(a,e){var s={};s["language-"+e]={pattern:/(^$)/i,lookbehind:!0,inside:Prism.languages[e]},s.cdata=/^$/i;var t={"included-cdata":{pattern://i,inside:s}};t["language-"+e]={pattern:/[\s\S]+/,inside:Prism.languages[e]};var n={};n[a]={pattern:RegExp("(<__[^>]*>)(?:))*\\]\\]>|(?!)".replace(/__/g,(function(){return a})),"i"),lookbehind:!0,greedy:!0,inside:t},Prism.languages.insertBefore("markup","cdata",n)}}),Object.defineProperty(Prism.languages.markup.tag,"addAttribute",{value:function(a,e){Prism.languages.markup.tag.inside["special-attr"].push({pattern:RegExp("(^|[\"'\\s])(?:"+a+")\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s'\">=]+(?=[\\s>]))","i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[e,"language-"+e],inside:Prism.languages[e]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup,Prism.languages.xml=Prism.languages.extend("markup",{}),Prism.languages.ssml=Prism.languages.xml,Prism.languages.atom=Prism.languages.xml,Prism.languages.rss=Prism.languages.xml; -Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/}; -Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp("(^|[^\\w$])(?:NaN|Infinity|0[bB][01]+(?:_[01]+)*n?|0[oO][0-7]+(?:_[0-7]+)*n?|0[xX][\\dA-Fa-f]+(?:_[\\dA-Fa-f]+)*n?|\\d+(?:_\\d+)*n|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:[Ee][+-]?\\d+(?:_\\d+)*)?)(?![\\w$])"),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),Prism.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp("((?:^|[^$\\w\\xA0-\\uFFFF.\"'\\])\\s]|\\b(?:return|yield))\\s*)/(?:(?:\\[(?:[^\\]\\\\\r\n]|\\\\.)*\\]|\\\\.|[^/\\\\\\[\r\n])+/[dgimyus]{0,7}|(?:\\[(?:[^[\\]\\\\\r\n]|\\\\.|\\[(?:[^[\\]\\\\\r\n]|\\\\.|\\[(?:[^[\\]\\\\\r\n]|\\\\.)*\\])*\\])*\\]|\\\\.|[^/\\\\\\[\r\n])+/[dgimyus]{0,7}v[dgimyus]{0,7})(?=(?:\\s|/\\*(?:[^*]|\\*(?!/))*\\*/)*(?:$|[\r\n,.;:})\\]]|//))"),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:Prism.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Prism.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}}),Prism.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}}),Prism.languages.markup&&(Prism.languages.markup.tag.addInlined("script","javascript"),Prism.languages.markup.tag.addAttribute("on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)","javascript")),Prism.languages.js=Prism.languages.javascript; -Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python; diff --git a/examples/await/await0.html b/examples/await/await0.html deleted file mode 100644 index 085aee770ed..00000000000 --- a/examples/await/await0.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - Async Await BLOCKING LOOP Pyscript Twice - - - - - - import js - import asyncio - for i in range(3): - js.console.log('A', i) - await asyncio.sleep(0.1) - - - import js - import asyncio - for i in range(3): - js.console.log('B', i) - await asyncio.sleep(0.1) - - - diff --git a/examples/await/await1.html b/examples/await/await1.html deleted file mode 100644 index 595f3186e9b..00000000000 --- a/examples/await/await1.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - Async Await BLOCKING LOOP Pyscript Twice - - - - -
- Pyscript - FIRST ASYNC WITH INVOKED LOOP BLOCKING AWAIT AT SAME - LEVEL AS LOOP Pyscript writing to console.log: - - import js - import asyncio - - async def asyncCallLoop1(): - for i in range(3): - js.console.log('A', i) - await asyncio.sleep(2) - - asyncCallLoop1() - -
-
- Pyscript - SECOND ASYNC WITH INVOKED LOOP BLOCKING AWAIT AT SAME - LEVEL AS LOOP Pyscript writing to console.log: - - import js - import asyncio - - async def asyncCallLoop2(): - for i in range(3): - js.console.log('B', i) - await asyncio.sleep(2) - - asyncCallLoop2() - -
- - diff --git a/examples/await/await2.html b/examples/await/await2.html deleted file mode 100644 index f1d0f98a9f1..00000000000 --- a/examples/await/await2.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - Async Await BLOCKING LOOP Pyscript Twice - - - - -
- Pyscript - FIRST ASYNC WITH INVOKED LOOP BLOCKING AWAIT AT SAME - LEVEL AS LOOP Pyscript writing to console.log: - - import js - import asyncio - - async def asyncCallLoop1(): - for i in range(3): - js.console.log('A', i) - await asyncio.sleep(2) - - asyncCallLoop1() - -
-
- Pyscript - SECOND ASYNC WITH TOP-LEVEL LOOP BLOCKING AWAIT AT SAME - LEVEL AS LOOP Pyscript writing to console.log: - - import js - import asyncio - - for i in range(3): - js.console.log('B', i) - await asyncio.sleep(2) - -
- - diff --git a/examples/await/await3.html b/examples/await/await3.html deleted file mode 100644 index 82c425ede08..00000000000 --- a/examples/await/await3.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - Async Await NON-BLOCKING Pyscript Twice - - - - -
- Pyscript - FIRST ASYNC WITH NON-BLOCKING AWAIT AT ONE LEVEL LOWER - THAN LOOP Pyscript writing to console.log: - - import js - import asyncio - - async def asyncCall1(): - await asyncio.sleep(2) - - for i in range(3): - js.console.log('A', i) - asyncCall1() - -
-
- Pyscript - SECOND ASYNC WITH NON-BLOCKING AWAIT AT ONE LEVEL LOWER - THAN LOOP Pyscript writing to console.log: - - import js - import asyncio - - async def asyncCall2(): - await asyncio.sleep(2) - - for i in range(3): - js.console.log('B', i) - asyncCall2() - -
- - diff --git a/examples/await/await4.html b/examples/await/await4.html deleted file mode 100644 index c78d7c3897d..00000000000 --- a/examples/await/await4.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - Async Await BLOCKING LOOP Pyscript Twice - - - - -
- Pyscript - FIRST ASYNC WITH TOP-LEVEL LOOP BLOCKING AWAIT AT SAME - LEVEL AS LOOP Pyscript writing to console.log: - - import js - import asyncio - - for i in range(3): - js.console.log('A', i) - await asyncio.sleep(2) - -
-
- Pyscript - SECOND ASYNC WITH TOP-LEVEL LOOP BLOCKING AWAIT AT SAME - LEVEL AS LOOP Pyscript writing to console.log: - - import js - import asyncio - - for i in range(3): - js.console.log('B', i) - await asyncio.sleep(2) - -
- - diff --git a/examples/await/await5.html b/examples/await/await5.html deleted file mode 100644 index 3312c7659d7..00000000000 --- a/examples/await/await5.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - Async Await BLOCKING LOOP Pyscript Twice - - - - - - import asyncio - from itertools import count - for i in count(): - print(f"Count: {i}") - await asyncio.sleep(1) - - - diff --git a/examples/bokeh.html b/examples/bokeh.html deleted file mode 100644 index aa50be8b3c0..00000000000 --- a/examples/bokeh.html +++ /dev/null @@ -1,86 +0,0 @@ - - - Bokeh Example - - - - - - - - - - - - - - - - - -
-
- - - packages = [ - "pandas", - "bokeh", - "xyzservices" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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(width=400, 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 578016337d4..00000000000 --- a/examples/bokeh_interactive.html +++ /dev/null @@ -1,136 +0,0 @@ - - - Bokeh Example - - - - - - - - - - - - - - - - - -
-

Bokeh Example

-
- - - packages = [ - "https://cdn.holoviz.org/panel/0.14.3/dist/wheels/bokeh-2.4.3-py3-none-any.whl", - "numpy", - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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.ffi.to_js(events)) - pydoc.apply_json_patch(json.loads(json_patch)) - - jsdoc.on_change(pyodide.ffi.create_proxy(jssync), pyodide.ffi.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.ffi.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) - - asyncio.ensure_future(show(row, 'myplot')) - -
-
- - diff --git a/examples/d3.html b/examples/d3.html deleted file mode 100644 index ef3e66f50e7..00000000000 --- a/examples/d3.html +++ /dev/null @@ -1,138 +0,0 @@ - - - d3: JavaScript & PyScript visualizations side-by-side - - - - - - - - - - - - -
- - - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - [[fetch]] - files = ["./d3.py"] - - - - Based on - Learn D3: Shapes - tutorial. - -
-
-
JavaScript version
-
-
-
-
-
-
PyScript version
-
-
-
-
-
- -
- - - - diff --git a/examples/d3.py b/examples/d3.py deleted file mode 100644 index 445e96eff67..00000000000 --- a/examples/d3.py +++ /dev/null @@ -1,64 +0,0 @@ -import js -from pyodide.ffi import create_proxy, to_js - -d3 = js.d3 - -fruits = [ - {"name": "🍊", "count": 21}, - {"name": "🍇", "count": 13}, - {"name": "🍏", "count": 8}, - {"name": "🍌", "count": 5}, - {"name": "🍐", "count": 3}, - {"name": "🍋", "count": 2}, - {"name": "🍎", "count": 1}, - {"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 016cc8e9506..00000000000 --- a/examples/folium.html +++ /dev/null @@ -1,72 +0,0 @@ - - - Folium - - - - - - - - -
-
- - - - packages = [ - "folium", - "pandas" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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) - - display(m, target="folium") - - -
- - 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 - - - - - - Say Hello - - - - - - - - - - from js import handTrack, requestAnimationFrame, console - from pyodide import create_once_callable - import asyncio - - update_note = Element("update-note") - canvas = Element("canvas") - video = Element("myvideo") - 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(): - 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 8929ef83c0b..00000000000 --- a/examples/hello_world.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - PyScript Hello World - - - - - - - - -
- - - - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - -
- Hello world!
- This is the current date and time, as computed by Python: - - from datetime import datetime - now = datetime.now() - display(now.strftime("%m/%d/%Y, %H:%M:%S")) - -
-
- - diff --git a/examples/index.html b/examples/index.html deleted file mode 100644 index afb6f974bd3..00000000000 --- a/examples/index.html +++ /dev/null @@ -1,315 +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

-
-

Simple TODO App

-
-
- -
-
- -

PyScript Native TODO App

-
-

- Simple TODO App using <py-list> -

-
-
-
-
- -
-

MIME Rendering

-
-
-
- -

Matplotlib

-
-

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

-
-
- -
-
- -

Altair

-
-

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

-
-
- -
-
- -

Folium

-
-

- Demonstrates rendering a - 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 the - <py-script> 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 :) -

-
-
- -
-
- -

- 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 85a1d1554b6..00000000000 --- a/examples/mario/css/game.css +++ /dev/null @@ -1,35 +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 d74e320a2ac..00000000000 --- a/examples/mario/js/bcoin.js +++ /dev/null @@ -1,43 +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 662c89aabd2..00000000000 --- a/examples/mario/js/block.js +++ /dev/null @@ -1,84 +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 d7521d3145f..00000000000 --- a/examples/mario/js/coin.js +++ /dev/null @@ -1,62 +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 b90ae85173c..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 c80cb88884d..00000000000 --- a/examples/mario/js/fireball.js +++ /dev/null @@ -1,145 +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 7bac50b3abe..00000000000 --- a/examples/mario/js/fireflower.js +++ /dev/null @@ -1,90 +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] = -0.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 146e92a41c6..00000000000 --- a/examples/mario/js/flag.js +++ /dev/null @@ -1,51 +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 ecf5cf0f451..00000000000 --- a/examples/mario/js/floor.js +++ /dev/null @@ -1,83 +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 f65451b1da1..00000000000 --- a/examples/mario/js/game.js +++ /dev/null @@ -1,253 +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 0cfcaffcafa..00000000000 --- a/examples/mario/js/goomba.js +++ /dev/null @@ -1,147 +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 6e2edc97d8f..00000000000 --- a/examples/mario/js/input.js +++ /dev/null @@ -1,61 +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 51d143c1d0e..00000000000 --- a/examples/mario/js/koopa.js +++ /dev/null @@ -1,228 +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 ce2c8b631f0..00000000000 --- a/examples/mario/js/levels/11.js +++ /dev/null @@ -1,341 +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 4cadc28076d..00000000000 --- a/examples/mario/js/levels/11tunnel.js +++ /dev/null @@ -1,138 +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 12c5d1a92a1..00000000000 --- a/examples/mario/js/levels/level.js +++ /dev/null @@ -1,348 +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 9ef200043cc..00000000000 --- a/examples/mario/js/mushroom.js +++ /dev/null @@ -1,132 +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] = -0.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 eedb4aada3d..00000000000 --- a/examples/mario/js/pipe.js +++ /dev/null @@ -1,228 +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 c8f66761d7e..00000000000 --- a/examples/mario/js/player.js +++ /dev/null @@ -1,505 +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 ca3510e250e..00000000000 --- a/examples/mario/js/prop.js +++ /dev/null @@ -1,14 +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 43f76c5280b..00000000000 --- a/examples/mario/js/resources.js +++ /dev/null @@ -1,61 +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 41da9964d5d..00000000000 --- a/examples/mario/js/rubble.js +++ /dev/null @@ -1,64 +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] += 0.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 5d768b95359..00000000000 --- a/examples/mario/js/sprite.js +++ /dev/null @@ -1,63 +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 2a678e8a21b..00000000000 --- a/examples/mario/js/star.js +++ /dev/null @@ -1,130 +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] = -0.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 efcc03f5472..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 c3ea5dab6e6..00000000000 --- a/examples/mario/play_mario.html +++ /dev/null @@ -1,160 +0,0 @@ - - - - - - - Mario - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - from js import handTrack, setTimeout, requestAnimationFrame, player - from pyodide import create_once_callable - import asyncio - - update_note = Element("update-note") - canvas = Element("canvas") - video = Element("myvideo") - 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(): - 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 start 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/markdown-plugin.html b/examples/markdown-plugin.html deleted file mode 100644 index 36383e0be27..00000000000 --- a/examples/markdown-plugin.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - PyMarkdown - - - - - - - - - - - - packages = [ - "markdown" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_markdown.py", - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - #Hello world! - - - diff --git a/examples/matplotlib.html b/examples/matplotlib.html deleted file mode 100644 index 97dac7657db..00000000000 --- a/examples/matplotlib.html +++ /dev/null @@ -1,73 +0,0 @@ - - - Matplotlib - - - - - - - - -
-
- - - - packages = [ - "matplotlib" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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') - - display(fig1, target="mpl") - - -
- - diff --git a/examples/message_passing.html b/examples/message_passing.html deleted file mode 100644 index b03832f535e..00000000000 --- a/examples/message_passing.html +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - - - packages = [ - "numpy", - "networkx", - "matplotlib" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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 8a09170cc79..00000000000 --- a/examples/micrograd_ai.html +++ /dev/null @@ -1,196 +0,0 @@ - - - - - - - micrograd - - - - - - - - -

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

-
- - - packages = [ - "micrograd", - "numpy", - "matplotlib" - ] - - -
-

- 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 8fb0f8e520e..00000000000 --- a/examples/micrograd_ai.py +++ /dev/null @@ -1,161 +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, strict=True) - ] - 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, strict=True) - ] - 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 14068f207ca..00000000000 --- a/examples/numpy_canvas_fractals.html +++ /dev/null @@ -1,411 +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 -
-
-
-
-
- -
-
-
- - - { - "packages": [ - "numpy", - "sympy" - ], - "fetch": [ - { - "files": [ - "./palettes.py", - "./fractals.py" - ] - } - ], - "plugins": [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - } - - - - from pyodide.ffi 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 - - async def main(): - _ = await asyncio.gather( - draw_mandelbrot(), - draw_julia(), - draw_newton(), - ) - - asyncio.ensure_future(main()) - - -
- - 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/pandas.html b/examples/pandas.html deleted file mode 100644 index 778ae7c945e..00000000000 --- a/examples/pandas.html +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - -
-
- -
-

Data Source

- - -
- - - - - - - - - - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - packages = ["pandas"] - - -
- - import pandas as pd - from pyodide.http import open_url - import sys - - title = "Pandas (and basic DOM manipulation)" - page_message = "This example loads a remote CSV file into a Pandas dataframe, displays it and lets you manipulate it through a Python REPL" - - url = "https://raw.githubusercontent.com/datasets/airport-codes/master/data/airport-codes.csv" - - Element("header-title").element.innerText = title - Element("page-title").element.innerText = title - Element("page-message").element.innerText = page_message - - Element("txt-url").element.value = url - - # Depending on the type of DOM element, there are several alternative methods to write to it - # Element("id-of-dom-element").write("example") - # Element("id-of-dom-element").innerText = "example" - # Element("id-of-dom-element").value = "example" - # Element("id-of-dom-element").element.innerText = "example" - # Element("id-of-dom-element").element.value = "example" - # js.document.getElementById("id-of-dom-element").innerText = "example" - # js.document.getElementById("id-of-dom-element").value = "example" - - df = pd.DataFrame() - - - def loadFromURL(*args, **kws): - global df - - # clear dataframe & output - df = pd.DataFrame() - Element("pandas-output-inner").element.innerHTML = "" - - url = Element("txt-url").element.value - log ("Trying to fetch CSV from " + url) - - df = pd.read_csv(open_url(url)) - - Element("pandas-repl").element.style.display = "block" - Element("pandas-output").element.style.display = "block" - Element("pandas-dev-console").element.style.display = "block" - - display (df, target="pandas-output-inner", append="False") - - def log(message): - # log to pyscript dev console - print (message) - - # log to JS console - js.console.log (message) - -
-
- - diff --git a/examples/panel.html b/examples/panel.html deleted file mode 100644 index 8e999a89311..00000000000 --- a/examples/panel.html +++ /dev/null @@ -1,68 +0,0 @@ - - - Panel Example - - - - - - - - - - - - -
-
- - - - packages = [ - "https://cdn.holoviz.org/panel/0.14.3/dist/wheels/bokeh-2.4.3-py3-none-any.whl", - "numpy", - "panel==0.14.1" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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 06e5f71089e..00000000000 --- a/examples/panel_deckgl.html +++ /dev/null @@ -1,284 +0,0 @@ - - - - - - - - - - PyScript/Panel DeckGL Demo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- -
-
-
-
- - - - packages = [ - "https://cdn.holoviz.org/panel/0.14.3/dist/wheels/bokeh-2.4.3-py3-none-any.whl", - "numpy", - "pandas", - "panel==0.13.1" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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 dd5cb8c536d..00000000000 --- a/examples/panel_kmeans.html +++ /dev/null @@ -1,229 +0,0 @@ - - - - - - - - - - Pyscript/Panel KMeans Demo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- -
-
-
-
-
-
- - - packages = [ - "https://cdn.holoviz.org/panel/0.14.3/dist/wheels/bokeh-2.4.3-py3-none-any.whl", - "altair", - "numpy", - "pandas", - "scikit-learn", - "panel==0.13.1" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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 fc678923baf..00000000000 --- a/examples/panel_stream.html +++ /dev/null @@ -1,162 +0,0 @@ - - - - - - - - - - PyScript/Panel Streaming Demo - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
-
-
-
-
-
-
-
- - - - packages = [ - "https://cdn.holoviz.org/panel/0.14.3/dist/wheels/bokeh-2.4.3-py3-none-any.whl", - "numpy", - "pandas", - "panel==0.13.1" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - - - 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 d3cef5e6896..00000000000 --- a/examples/pylist.py +++ /dev/null @@ -1,21 +0,0 @@ -from datetime import datetime as dt - -import pyscript - - -class PyItem(pyscript.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(pyscript.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 18c6c7d3cf3..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 da26ffb836e..00000000000 --- a/examples/repl.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - REPL - - - - - - - - - -
-

PyScript REPL

- Tip: press Shift-ENTER to evaluate a cell -
- - - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - [[fetch]] - files = ["./antigravity.py"] - -
- -
-
-
- - diff --git a/examples/repl2.html b/examples/repl2.html deleted file mode 100644 index a1796a9e13c..00000000000 --- a/examples/repl2.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - Custom REPL Example - - - - - - - - - - -
-

Custom REPL

- - - packages = [ - "bokeh", - "numpy" - ] - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - - [[fetch]] - files = ["./utils.py", "./antigravity.py"] - -
- -
-
-
-
- - diff --git a/examples/simple_bioinformatics_tool.html b/examples/simple_bioinformatics_tool.html deleted file mode 100644 index eb6b5e9c579..00000000000 --- a/examples/simple_bioinformatics_tool.html +++ /dev/null @@ -1,179 +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 d5eb608afeb..00000000000 --- a/examples/simple_clock.html +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - Simple Clock Demo - - - - - - - - - - -
-
- start time: -
-
-
- - - - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - [[fetch]] - files = ["./utils.py"] - - - import utils - display(utils.now()) - - - - from utils import now - import asyncio - - async def foo(): - while True: - await asyncio.sleep(1) - output = now() - Element("outputDiv2").write(output) - - out3 = Element("outputDiv3") - if output[-1] in ["0", "4", "8"]: - out3.write("It's espresso time!") - else: - out3.clear() - - pyscript.run_until_complete(foo()) - - -
- - diff --git a/examples/todo-pylist.html b/examples/todo-pylist.html deleted file mode 100644 index 328b23f84e6..00000000000 --- a/examples/todo-pylist.html +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - Todo App - - - - - - - - - - -
-

To Do List

- - - - - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - [[fetch]] - files = ["./utils.py", "./pylist.py"] - - - - from js import document - from pyodide.ffi.wrappers import add_event_listener - - def add_task(*args, **kws): - # create a new dictionary representing the new task - new_task_content = Element("new-task-content") - 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() - - def on_click(evt): - add_task() - - def handle_keypress(evt): - if evt.key == "Enter": - add_task() - - add_event_listener( - document.getElementById("new-task-content"), - "keypress", - handle_keypress - ) - -
- - -
- - - -
-
- - diff --git a/examples/todo.html b/examples/todo.html deleted file mode 100644 index 12e7bc16ddb..00000000000 --- a/examples/todo.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - Todo App - - - - - - - - - - -
- - - plugins = [ - "https://pyscript.net/latest/plugins/python/py_tutor.py" - ] - [[fetch]] - files = ["./utils.py", "./todo.py"] - - - - -
-
-
-

- To Do List -

-
-
- - -
- - -
- - -
-
-
- - diff --git a/examples/todo.py b/examples/todo.py deleted file mode 100644 index bf77bb63d17..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(*args, **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) - 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 23c1145b1d3..00000000000 --- a/examples/toga/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# Freedom Units! - -This is a demo Toga app implementing a Fahrenheit to Celsius converter. - -It can be served as a Single Page App from a static web server. - -## Initial setup - -1. Create and activate a virtual environment, and move into the `freedom` - project directory: - - $ python -m venv venv - $ . ./venv/bin/activate - $ cd freedom - -2. Install Briefcase: - - $ pip install briefcase - -## 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. To re-build the app and start a -local webserver, run: - - $ briefcase run web - -## Desktop app - -To run this app as a desktop app in development mode: - - $ briefcase dev - -To build and run it as an app bundle: - - $ briefcase run - -## Mobile 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 6d61a1c4e2b..00000000000 --- a/examples/toga/freedom.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - Freedom Units - - - - - - - - - - - -
- - - - - - name = "Freedom Units" - description = "A testing app" - version = "0.0.1" - terminal = false - packages = [ - "./static/wheels/freedom-0.0.1-py3-none-any.whl", - "toga_core==0.3.0", - "toga_web==0.3.0", - "travertino==0.1.3", - ] - - [splashscreen] - autoclose = true - - - import runpy - result = runpy.run_module("freedom", run_name="__main__", alter_sys=True) - - - diff --git a/examples/toga/freedom/pyproject.toml b/examples/toga/freedom/pyproject.toml deleted file mode 100644 index e07dfd62daa..00000000000 --- a/examples/toga/freedom/pyproject.toml +++ /dev/null @@ -1,72 +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 = [ -] - -[tool.briefcase.app.freedom.macOS] -requires = [ - "toga-cocoa~=0.3.0", - "std-nslog>=1.0.0", -] - -[tool.briefcase.app.freedom.linux] -requires = [ - "toga-gtk~=0.3.0", -] - -[tool.briefcase.app.freedom.linux.appimage] -system_requires = [ - "gir1.2-webkit2-4.0", - "libcairo2-dev", - "libgirepository1.0-dev", - "libgtk-3-dev", - "libpango1.0-dev", - "librsvg2-dev", - "libwebkit2gtk-4.0-dev", -] -linuxdeploy_plugins = [ - "DEPLOY_GTK_VERSION=3 gtk", -] - -[tool.briefcase.app.freedom.linux.flatpak] -flatpak_runtime = "org.gnome.Platform" -flatpak_runtime_version = "42" -flatpak_sdk = "org.gnome.Sdk" - -[tool.briefcase.app.freedom.windows] -requires = [ - "toga-winforms~=0.3.0", -] - -# Mobile deployments -[tool.briefcase.app.freedom.iOS] -requires = [ - "toga-iOS~=0.3.0", - "std-nslog>=1.0.0", -] - -[tool.briefcase.app.freedom.android] -requires = [ - "toga-android~=0.3.0", -] - -# Web deployments -[tool.briefcase.app.freedom.web] -requires = [ - "toga-web~=0.3.0", -] -style_framework = "Bootstrap v4.6" diff --git a/examples/toga/freedom/src/freedom/__main__.py b/examples/toga/freedom/src/freedom/__main__.py deleted file mode 100644 index 6bd21e053d3..00000000000 --- a/examples/toga/freedom/src/freedom/__main__.py +++ /dev/null @@ -1,4 +0,0 @@ -from freedom.app import 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/css/briefcase.css b/examples/toga/static/css/briefcase.css deleted file mode 100644 index b6f87c85bfe..00000000000 --- a/examples/toga/static/css/briefcase.css +++ /dev/null @@ -1,35 +0,0 @@ -/* Unset the overly generic pyscript .label style */ -#app-placeholder .label { - margin-top: inherit; - color: inherit; - text-align: inherit; - width: inherit; - display: inherit; - color: inherit; - font-size: inherit; - margin-top: inherit; -} - -/******************************************************************* - * WARNING: Do not remove or modify this comment block, or add any - * content below this block. Briefcase will add content here during - * the build step. - ******************* Wheel contributed styles **********************/ - -/******************************************************* - * toga_web 0.3.0::toga.css - *******************************************************/ - -main.toga.window { - margin-top: 5em; - display: flex; - flex-direction: column; -} - -div.toga.box { - display: flex; -} - -span.toga.label { - white-space: nowrap; -} diff --git a/examples/toga/static/logo-32.png b/examples/toga/static/logo-32.png deleted file mode 100644 index d4ee3c9b6a3..00000000000 Binary files a/examples/toga/static/logo-32.png and /dev/null differ 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 7e7ad9130ff..00000000000 Binary files a/examples/toga/static/wheels/freedom-0.0.1-py3-none-any.whl and /dev/null differ diff --git a/examples/utils.py b/examples/utils.py deleted file mode 100644 index 8abc63e90ca..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 f"{dt_:{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 a98f8a3f1c8..00000000000 --- a/examples/webgl/raycaster/index.html +++ /dev/null @@ -1,195 +0,0 @@ - - - - - Raycaster - - - - - -
-
-
-
-
-
-
-
-
-
-
- - - - - - from pyodide.ffi import create_proxy, to_js - from js import window - from js import Math - from js import THREE - from js import performance - from js import Object - from js import document - import asyncio - - 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.ffi.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); - - sceneGroup = THREE.Object3D.new(); - particularGroup = THREE.Object3D.new(); - - def mathRandom(num = 1): - setNumber = - Math.random() * num + Math.random() * num - return setNumber - - particularGroup = THREE.Object3D.new(); - modularGroup = 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, modularGroup): - 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); - modularGroup.add(cube); - i += 1 - - create_cubes(mathRandom, modularGroup) - - - def generateParticle(mathRandom, particularGroup, 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); - particularGroup.add(particular); - i += 1 - - generateParticle(mathRandom, particularGroup, 200, 2) - - sceneGroup.add(particularGroup); - scene.add(modularGroup); - scene.add(sceneGroup); - - 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(sceneGroup); - scene.add(light); - scene.add(lightBack); - - rectSize = 2 - intensity = 14 - rectLight = THREE.RectAreaLight.new( 0x0FFFFF, intensity, rectSize, rectSize ) - rectLight.position.set( 0, 0, 1 ) - rectLight.lookAt( 0, 0, 0 ) - scene.add( rectLight ) - - raycaster = THREE.Raycaster.new(); - uSpeed = 0.1 - - time = 0.0003; - camera.lookAt(scene.position) - - async def main(): - while True: - time = performance.now() * 0.0003; - i = 0 - while i < particularGroup.children.length: - newObject = particularGroup.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 < modularGroup.children.length: - newCubes = modularGroup.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 - - particularGroup.rotation.y += 0.005; - - modularGroup.rotation.y -= ((mouse.x * 4) + modularGroup.rotation.y) * uSpeed; - modularGroup.rotation.x -= ((-mouse.y * 4) + modularGroup.rotation.x) * uSpeed; - - renderer.render( scene, camera ) - await asyncio.sleep(0.02) - - asyncio.ensure_future(main()) - - - diff --git a/examples/webgl/raycaster/style.css b/examples/webgl/raycaster/style.css deleted file mode 100644 index d70645cffb5..00000000000 --- a/examples/webgl/raycaster/style.css +++ /dev/null @@ -1,55 +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 index 0e73d3812b8..a3a7cbc434d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,40 +1,9 @@ -[build-system] -requires = ["setuptools>=61.2"] -build-backend = "setuptools.build_meta" - -[project] -dynamic = ["version"] - [tool.codespell] ignore-words-list = "afterall" -skip = "pyscriptjs/node_modules/*,*.js,*.json" +skip = "*.js,*.json" [tool.ruff] -builtins = [ - "Element", - "PyItemTemplate", - "PyListTemplate", - "pyscript", -] -ignore = [ - "S101", - "S113", -] -line-length = 100 -select = [ - "B", - "C9", - "E", - "F", - "I", - "S", - "UP", - "W", -] -target-version = "py310" - -[tool.ruff.mccabe] -max-complexity = 10 - -[tool.setuptools] -include-package-data = false +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 0945b1a1555..00000000000 --- a/pyscriptjs/.eslintrc.js +++ /dev/null @@ -1,39 +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'], - }, - env: { - es6: true, - browser: true, - }, - plugins: ['@typescript-eslint'], - ignorePatterns: ['node_modules'], - rules: { - // ts-ignore is already an explicit override, no need to have a second lint - '@typescript-eslint/ban-ts-comment': 'off', - - // any related lints - '@typescript-eslint/no-explicit-any': 'error', - '@typescript-eslint/no-unsafe-assignment': 'error', - '@typescript-eslint/no-unsafe-call': 'error', - '@typescript-eslint/no-unsafe-member-access': 'error', - '@typescript-eslint/no-unsafe-argument': 'error', - '@typescript-eslint/no-unsafe-return': 'error', - - // other rules - 'no-prototype-builtins': 'error', - '@typescript-eslint/no-unused-vars': ['error', { args: 'none' }], - '@typescript-eslint/no-floating-promises': 'error', - '@typescript-eslint/restrict-plus-operands': 'error', - '@typescript-eslint/no-empty-function': 'error', - }, -}; 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 01d6f2dae6e..00000000000 --- a/pyscriptjs/.prettierrc.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports = { - arrowParens: 'avoid', - bracketSameLine: true, - singleQuote: true, - printWidth: 120, - semi: true, - tabWidth: 4, - trailingComma: 'all', -}; diff --git a/pyscriptjs/Makefile b/pyscriptjs/Makefile deleted file mode 100644 index 4e486319e32..00000000000 --- a/pyscriptjs/Makefile +++ /dev/null @@ -1,131 +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)/pyscriptjs/src -examples ?= ../$(base_dir)/examples -app_dir ?= $(shell git rev-parse --show-prefix) - -CONDA_EXE := conda -CONDA_ENV ?= $(base_dir)/pyscriptjs/env -env := $(CONDA_ENV) -conda_run := $(CONDA_EXE) run -p $(env) -PYTEST_EXE := $(CONDA_ENV)/bin/pytest -GOOD_NODE_VER := 14 -GOOD_NPM_VER := 6 -NODE_VER := $(shell node -v | cut -d. -f1 | sed 's/^v\(.*\)/\1/') -NPM_VER := $(shell npm -v | cut -d. -f1) - -ifeq ($(shell uname -s), Darwin) - SED_I_ARG := -i '' -else - SED_I_ARG := -i -endif - -GOOD_NODE := $(shell if [ $(NODE_VER) -ge $(GOOD_NODE_VER) ]; then echo true; else echo false; fi) -GOOD_NPM := $(shell if [ $(NPM_VER) -ge $(GOOD_NPM_VER) ]; then echo true; else echo false; fi) - -.PHONY: check-node -check-node: - @echo Build requires Node $(GOOD_NODE_VER).x or higher: $(NODE_VER) detected && $(GOOD_NODE) - -.PHONY: check-npm -check-npm: - @echo Build requires npm $(GOOD_NPM_VER).x or higher: $(NPM_VER) detected && $(GOOD_NPM) - -setup: - make check-node - make check-npm - 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 -y - -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 - -build-fast: - node esbuild.js - -# use the following rule to do all the checks done by precommit: in -# particular, use this if you want to run eslint. -precommit-check: - pre-commit run --all-files - -examples: - mkdir -p ./examples - cp -r ../examples/* ./examples - chmod -R 755 examples - find ./examples/toga -type f -name '*.html' -exec sed $(SED_I_ARG) s+https://pyscript.net/latest/+../../build/+g {} \; - find ./examples/webgl -type f -name '*.html' -exec sed $(SED_I_ARG) s+https://pyscript.net/latest/+../../../build/+g {} \; - find ./examples -type f -name '*.html' -exec sed $(SED_I_ARG) s+https://pyscript.net/latest/+../build/+g {} \; - npm run build - rm -rf ./examples/build - mkdir -p ./examples/build - cp -R ./build/* ./examples/build - @echo "To serve examples run: $(conda_run) python -m http.server 8080 --directory examples" - -# run prerequisites and serve pyscript examples at http://localhost:8000/examples/ -run-examples: setup build examples - make examples - npm install - make dev - -test: - make examples - make test-ts - make test-py - make test-integration-parallel - -test-integration: - make examples - mkdir -p test_results - $(PYTEST_EXE) -vv $(ARGS) tests/integration/ --log-cli-level=warning --junitxml=test_results/integration.xml - -test-integration-parallel: - make examples - mkdir -p test_results - $(PYTEST_EXE) --numprocesses auto -vv $(ARGS) tests/integration/ --log-cli-level=warning --junitxml=test_results/integration.xml - -test-py: - @echo "Tests from $(src_dir)" - mkdir -p test_results - $(PYTEST_EXE) -vv $(ARGS) tests/py-unit/ --log-cli-level=warning --junitxml=test_results/py-unit.xml - -test-ts: - npm run test - -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 . - -.PHONY: $(MAKECMDGOALS) diff --git a/pyscriptjs/README.md b/pyscriptjs/README.md deleted file mode 100644 index afbcd9e47f1..00000000000 --- a/pyscriptjs/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# PyScript Demonstrator - -[A simple webapp to demonstrate the capabilities of PyScript.](https://github.com/pyscript/pyscript/blob/main/docs/development/setting-up-environment.md#pyscript-demonstrator) diff --git a/pyscriptjs/__mocks__/_pyscript.js b/pyscriptjs/__mocks__/_pyscript.js deleted file mode 100644 index 5ea0010793e..00000000000 --- a/pyscriptjs/__mocks__/_pyscript.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * this file mocks the `src/python/pyscript.py` file - * since importing of `.py` files isn't usually supported - * inside JS/TS files. - * - * It sets the value of whatever is imported from - * `src/python/pyscript.py` the contents of that file - * - * This is needed since the imported object is further - * passed to a function which only accepts a string. - */ - -const fs = require('fs'); -module.exports = fs.readFileSync('./src/python/pyscript.py', 'utf8'); diff --git a/pyscriptjs/__mocks__/cssMock.js b/pyscriptjs/__mocks__/cssMock.js deleted file mode 100644 index 9dc5fc1e4a4..00000000000 --- a/pyscriptjs/__mocks__/cssMock.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = ''; diff --git a/pyscriptjs/__mocks__/fileMock.js b/pyscriptjs/__mocks__/fileMock.js deleted file mode 100644 index 1fce9017442..00000000000 --- a/pyscriptjs/__mocks__/fileMock.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * this file mocks python files that are not explicitly - * matched by a regex in jest.config.js, since importing of - * `.py` files isn't usually supported inside JS/TS files. - * - * This is needed since the imported object is further - * passed to a function which only accepts a string. - * - * The mocked contents of the `.py` file will be "", e.g. - * nothing. - */ - -console.warn(`.py files that are not explicitly mocked in \ - jest.config.js and /__mocks__/ are mocked as empty strings`); - -module.exports = ''; diff --git a/pyscriptjs/directoryManifest.mjs b/pyscriptjs/directoryManifest.mjs deleted file mode 100644 index 4fb5756c3ca..00000000000 --- a/pyscriptjs/directoryManifest.mjs +++ /dev/null @@ -1,44 +0,0 @@ -// This logic split out because it is shared by: -// 1. esbuild.mjs -// 2. Jest setup.ts - -import { join } from 'path'; -import { opendir, readFile } from 'fs/promises'; - -/** - * List out everything in a directory, but skip __pycache__ directory. Used to - * list out the directory paths and the [file path, file contents] pairs in the - * Python package. All paths are relative to the directory we are listing. The - * directories are sorted topologically so that a parent directory always - * appears before its children. - * - * This is consumed in main.ts which calls mkdir for each directory and then - * writeFile to create each file. - * - * @param {string} dir The path to the directory we want to list out - * @returns {dirs: string[], files: [string, string][]} - */ -export async function directoryManifest(dir) { - const result = { dirs: [], files: [] }; - await _directoryManifestHelper(dir, '.', result); - return result; -} - -/** - * Recursive helper function for directoryManifest - */ -async function _directoryManifestHelper(root, dir, result) { - const dirObj = await opendir(join(root, dir)); - for await (const d of dirObj) { - const entry = join(dir, d.name); - if (d.isDirectory()) { - if (d.name === '__pycache__') { - continue; - } - result.dirs.push(entry); - await _directoryManifestHelper(root, entry, result); - } else if (d.isFile()) { - result.files.push([entry, await readFile(join(root, entry), { encoding: 'utf-8' })]); - } - } -} diff --git a/pyscriptjs/environment.yml b/pyscriptjs/environment.yml deleted file mode 100644 index bc4d2568a8d..00000000000 --- a/pyscriptjs/environment.yml +++ /dev/null @@ -1,24 +0,0 @@ -channels: - - defaults - - conda-forge - - microsoft -dependencies: - - python=3.11 - - pip - - pytest=7 - - nodejs=16 - - black - - isort - - codespell - - pre-commit - - pillow - - numpy - - markdown - - pip: - - playwright - - pytest-playwright - - pytest-xdist - # We need Pyodide and micropip so we can import them in our Python - # unit tests - - pyodide_py==0.22 - - micropip==0.2.2 diff --git a/pyscriptjs/esbuild.mjs b/pyscriptjs/esbuild.mjs deleted file mode 100644 index 5a0d4ca7fd9..00000000000 --- a/pyscriptjs/esbuild.mjs +++ /dev/null @@ -1,121 +0,0 @@ -import { build } from 'esbuild'; -import { spawn } from 'child_process'; -import { dirname, join } from 'path'; -import { watchFile } from 'fs'; -import { cp, lstat, readdir } from 'fs/promises'; -import { directoryManifest } from './directoryManifest.mjs'; - -const __dirname = dirname(new URL(import.meta.url).pathname); - -const production = !process.env.NODE_WATCH || process.env.NODE_ENV === 'production'; - -const copy_targets = [ - { src: 'public/index.html', dest: 'build' }, - { src: 'src/plugins/python/*', dest: 'build/plugins/python' }, -]; - -if (!production) { - copy_targets.push({ src: 'build/*', dest: 'examples/build' }); -} - -/** - * An esbuild plugin that injects the Pyscript Python package. - * - * It uses onResolve to attach our custom namespace to the import and then uses - * onLoad to inject the file contents. - */ -function bundlePyscriptPythonPlugin() { - const namespace = 'bundlePyscriptPythonPlugin'; - return { - name: namespace, - setup(build) { - // Resolve the pyscript_package to our custom namespace - // The path doesn't really matter, but we need a separate namespace - // or else the file system resolver will raise an error. - build.onResolve({ filter: /^pyscript_python_package.esbuild_injected.json$/ }, args => { - return { path: 'dummy', namespace }; - }); - // Inject our manifest as JSON contents, and use the JSON loader. - // Also tell esbuild to watch the files & directories we've listed - // for updates. - build.onLoad({ filter: /^dummy$/, namespace }, async args => { - const manifest = await directoryManifest('./src/python'); - return { - contents: JSON.stringify(manifest), - loader: 'json', - watchFiles: manifest.files.map(([k, v]) => k), - watchDirs: manifest.dirs, - }; - }); - }, - }; -} - -const pyScriptConfig = { - entryPoints: ['src/main.ts'], - loader: { '.py': 'text' }, - bundle: true, - format: 'iife', - globalName: 'pyscript', - plugins: [bundlePyscriptPythonPlugin()], -}; - -const copyPath = (source, dest, ...rest) => cp(join(__dirname, source), join(__dirname, dest), ...rest); - -const esbuild = async () => { - const timer = `\x1b[1mpyscript\x1b[0m \x1b[2m(${production ? 'prod' : 'dev'})\x1b[0m built in`; - console.time(timer); - - await Promise.all([ - build({ - ...pyScriptConfig, - sourcemap: false, - minify: false, - outfile: 'build/pyscript.js', - }), - build({ - ...pyScriptConfig, - sourcemap: true, - minify: true, - outfile: 'build/pyscript.min.js', - }), - ]); - - const copy = []; - for (const { src, dest } of copy_targets) { - if (src.endsWith('/*')) { - copy.push(copyPath(src.slice(0, -2), dest, { recursive: true })); - } else { - copy.push(copyPath(src, dest + src.slice(src.lastIndexOf('/')))); - } - } - await Promise.all(copy); - - console.timeEnd(timer); -}; - -esbuild().then(() => { - if (!production) { - (async function watchPath(path) { - for (const file of await readdir(path)) { - const whole = join(path, file); - if (/\.(js|ts|css|py)$/.test(file)) { - watchFile(whole, async () => { - await esbuild(); - }); - } else if ((await lstat(whole)).isDirectory()) { - watchPath(whole); - } - } - })('src'); - - const server = spawn('python', ['-m', 'http.server', '--directory', './examples', '8080'], { - stdio: 'inherit', - detached: false, - }); - - process.on('exit', () => { - server.kill(); - }); - } -}); diff --git a/pyscriptjs/jest-environment-jsdom.js b/pyscriptjs/jest-environment-jsdom.js deleted file mode 100644 index 4ff695fc589..00000000000 --- a/pyscriptjs/jest-environment-jsdom.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const { TextEncoder, TextDecoder } = require('util'); -const { MessageChannel } = require('node:worker_threads'); - -const { default: $JSDOMEnvironment, TestEnvironment } = require('jest-environment-jsdom'); - -Object.defineProperty(exports, '__esModule', { - value: true, -}); - -class JSDOMEnvironment extends $JSDOMEnvironment { - constructor(...args) { - const { global } = super(...args); - if (!global.TextEncoder) { - global.TextEncoder = TextEncoder; - } - if (!global.TextDecoder) { - global.TextDecoder = TextDecoder; - } - if (!global.MessageChannel) { - global.MessageChannel = MessageChannel; - } - } -} - -exports.default = JSDOMEnvironment; -exports.TestEnvironment = TestEnvironment === $JSDOMEnvironment ? JSDOMEnvironment : TestEnvironment; diff --git a/pyscriptjs/jest.config.js b/pyscriptjs/jest.config.js deleted file mode 100644 index 788ff3b1615..00000000000 --- a/pyscriptjs/jest.config.js +++ /dev/null @@ -1,25 +0,0 @@ -//jest.config.js -module.exports = { - preset: 'ts-jest', - setupFilesAfterEnv: ['./tests/unit/setup.ts'], - testEnvironment: './jest-environment-jsdom.js', - extensionsToTreatAsEsm: ['.ts'], - transform: { - '^.+\\.tsx?$': [ - 'ts-jest', - { - tsconfig: 'tsconfig.json', - useESM: true, - }, - ], - }, - verbose: true, - testEnvironmentOptions: { - url: 'http://localhost', - }, - moduleNameMapper: { - '^.*?pyscript.py$': '/__mocks__/_pyscript.js', - '^[./a-zA-Z0-9$_-]+\\.py$': '/__mocks__/fileMock.js', - '\\.(css)$': '/__mocks__/cssMock.js', - }, -}; diff --git a/pyscriptjs/package-lock.json b/pyscriptjs/package-lock.json deleted file mode 100644 index 5d85e19ec80..00000000000 --- a/pyscriptjs/package-lock.json +++ /dev/null @@ -1,10394 +0,0 @@ -{ - "name": "pyscript", - "version": "0.0.1", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "pyscript", - "version": "0.0.1", - "dependencies": { - "@codemirror/commands": "^6.2.2", - "@codemirror/lang-python": "^6.1.2", - "@codemirror/language": "^6.6.0", - "@codemirror/state": "^6.2.0", - "@codemirror/theme-one-dark": "^6.1.1", - "@codemirror/view": "^6.9.3", - "@hoodmane/toml-j0.4": "^1.1.2", - "codemirror": "6.0.1", - "synclink": "^0.1.1" - }, - "devDependencies": { - "@jest/globals": "29.1.2", - "@types/codemirror": "^5.60.5", - "@types/jest": "29.1.2", - "@types/node": "18.8.3", - "@typescript-eslint/eslint-plugin": "5.39.0", - "@typescript-eslint/parser": "5.39.0", - "cross-env": "7.0.3", - "esbuild": "0.17.12", - "eslint": "8.25.0", - "jest": "29.1.2", - "jest-environment-jsdom": "29.1.2", - "prettier": "2.7.1", - "pyodide": "0.22.1", - "ts-jest": "29.0.3", - "tslib": "2.4.0", - "typescript": "4.8.4" - } - }, - "node_modules/@ampproject/remapping": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz", - "integrity": "sha512-qRmjj8nj9qmLTQXXmaR1cck3UXSRMPrbsLJAasZpF+t3riI71BXed5ebIOYwQntykeZuhjsdweEc9BxH5Jc26w==", - "dev": true, - "dependencies": { - "@jridgewell/gen-mapping": "^0.1.0", - "@jridgewell/trace-mapping": "^0.3.9" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/code-frame": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", - "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", - "dev": true, - "dependencies": { - "@babel/highlight": "^7.18.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.21.0.tgz", - "integrity": "sha512-gMuZsmsgxk/ENC3O/fRw5QY8A9/uxQbbCEypnLIiYYc/qVJtEV7ouxC3EllIIwNzMqAQee5tanFabWsUOutS7g==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.21.3.tgz", - "integrity": "sha512-qIJONzoa/qiHghnm0l1n4i/6IIziDpzqc36FBs4pzMhDUraHqponwJLiAKm1hGLP3OSB/TVNz6rMwVGpwxxySw==", - "dev": true, - "dependencies": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.18.6", - "@babel/generator": "^7.21.3", - "@babel/helper-compilation-targets": "^7.20.7", - "@babel/helper-module-transforms": "^7.21.2", - "@babel/helpers": "^7.21.0", - "@babel/parser": "^7.21.3", - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.3", - "@babel/types": "^7.21.3", - "convert-source-map": "^1.7.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.2", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/core/node_modules/convert-source-map": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", - "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", - "dev": true - }, - "node_modules/@babel/core/node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/generator": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.21.3.tgz", - "integrity": "sha512-QS3iR1GYC/YGUnW7IdggFeN5c1poPUurnGttOV/bZgPGV+izC/D8HnD6DLwod0fsatNyVn1G3EVWMYIF0nHbeA==", - "dev": true, - "dependencies": { - "@babel/types": "^7.21.3", - "@jridgewell/gen-mapping": "^0.3.2", - "@jridgewell/trace-mapping": "^0.3.17", - "jsesc": "^2.5.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz", - "integrity": "sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==", - "dev": true, - "dependencies": { - "@jridgewell/set-array": "^1.0.1", - "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.9" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.20.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.20.7.tgz", - "integrity": "sha512-4tGORmfQcrc+bvrjb5y3dG9Mx1IOZjsHqQVUz7XCNHO+iTmqxWnVg3KRygjGmpRLJGdQSKuvFinbIb0CnZwHAQ==", - "dev": true, - "dependencies": { - "@babel/compat-data": "^7.20.5", - "@babel/helper-validator-option": "^7.18.6", - "browserslist": "^4.21.3", - "lru-cache": "^5.1.1", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-compilation-targets/node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/helper-environment-visitor": { - "version": "7.18.9", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", - "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-function-name": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.21.0.tgz", - "integrity": "sha512-HfK1aMRanKHpxemaY2gqBmL04iAPOPRj7DxtNbiDOrJK+gdwkiNRVpCpUJYbUT+aZyemKN8brqTOxzCaG6ExRg==", - "dev": true, - "dependencies": { - "@babel/template": "^7.20.7", - "@babel/types": "^7.21.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", - "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", - "dev": true, - "dependencies": { - "@babel/types": "^7.18.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", - "integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", - "dev": true, - "dependencies": { - "@babel/types": "^7.18.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.21.2", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.21.2.tgz", - "integrity": "sha512-79yj2AR4U/Oqq/WOV7Lx6hUjau1Zfo4cI+JLAVYeMV5XIlbOhmjEk5ulbTc9fMpmlojzZHkUUxAiK+UKn+hNQQ==", - "dev": true, - "dependencies": { - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-module-imports": "^7.18.6", - "@babel/helper-simple-access": "^7.20.2", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/helper-validator-identifier": "^7.19.1", - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.2", - "@babel/types": "^7.21.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.20.2.tgz", - "integrity": "sha512-8RvlJG2mj4huQ4pZ+rU9lqKi9ZKiRmuvGuM2HlWmkmgOhbs6zEAw6IEiJ5cQqGbDzGZOhwuOQNtZMi/ENLjZoQ==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-simple-access": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.20.2.tgz", - "integrity": "sha512-+0woI/WPq59IrqDYbVGfshjT5Dmk/nnbdpcF8SnMhhXObpTq2KNBdLFRFrkVdbDOyUmHBCxzm5FHV1rACIkIbA==", - "dev": true, - "dependencies": { - "@babel/types": "^7.20.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-split-export-declaration": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", - "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", - "dev": true, - "dependencies": { - "@babel/types": "^7.18.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.19.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", - "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.19.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", - "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.21.0.tgz", - "integrity": "sha512-rmL/B8/f0mKS2baE9ZpyTcTavvEuWhTTW8amjzXNvYG4AwBsqTLikfXsEofsJEfKHf+HQVQbFOHy6o+4cnC/fQ==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.21.0.tgz", - "integrity": "sha512-XXve0CBtOW0pd7MRzzmoyuSj0e3SEzj8pgyFxnTT1NJZL38BD1MK7yYrm8yefRPIDvNNe14xR4FdbHwpInD4rA==", - "dev": true, - "dependencies": { - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.0", - "@babel/types": "^7.21.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/highlight": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", - "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", - "dev": true, - "dependencies": { - "@babel/helper-validator-identifier": "^7.18.6", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/highlight/node_modules/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, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/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, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/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, - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/@babel/highlight/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "node_modules/@babel/highlight/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@babel/highlight/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/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, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/parser": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.21.3.tgz", - "integrity": "sha512-lobG0d7aOfQRXh8AyklEAgZGvA4FShxo6xQbUrrT/cNBPUdIDojlokwJsQyCC/eKia7ifqM0yP+2DRZ4WKw2RQ==", - "dev": true, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.12.13" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.18.6.tgz", - "integrity": "sha512-6mmljtAedFGTWu2p/8WIORGwy+61PLgOMPOdazc7YoJ9ZCWUyFy3A6CpPkRKLKD1ToAesxX8KGEViAiLo9N+7Q==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.18.6" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-top-level-await": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", - "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.20.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.20.0.tgz", - "integrity": "sha512-rd9TkG+u1CExzS4SM1BlMEhMXwFLKVjOAFFCDx9PbX5ycJWDoWMcwdJH9RhkPu1dOgn5TrxLot/Gx6lWFuAUNQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.19.0" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/template": { - "version": "7.20.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz", - "integrity": "sha512-8SegXApWe6VoNw0r9JHpSteLKTpTiLZ4rMlGIm9JQ18KiCtyQiAMEazujAHrUS5flrcqYZa75ukev3P6QmUwUw==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.18.6", - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.21.3.tgz", - "integrity": "sha512-XLyopNeaTancVitYZe2MlUEvgKb6YVVPXzofHgqHijCImG33b/uTurMS488ht/Hbsb2XK3U2BnSTxKVNGV3nGQ==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.18.6", - "@babel/generator": "^7.21.3", - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-function-name": "^7.21.0", - "@babel/helper-hoist-variables": "^7.18.6", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/parser": "^7.21.3", - "@babel/types": "^7.21.3", - "debug": "^4.1.0", - "globals": "^11.1.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse/node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/types": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.21.3.tgz", - "integrity": "sha512-sBGdETxC+/M4o/zKC0sl6sjWv62WFR/uzxrJ6uYyMLZOUlPnwzw0tKgVHOXxaAd5l2g8pEDM5RZ495GPQI77kg==", - "dev": true, - "dependencies": { - "@babel/helper-string-parser": "^7.19.4", - "@babel/helper-validator-identifier": "^7.19.1", - "to-fast-properties": "^2.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", - "dev": true - }, - "node_modules/@codemirror/autocomplete": { - "version": "6.4.2", - "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.4.2.tgz", - "integrity": "sha512-8WE2xp+D0MpWEv5lZ6zPW1/tf4AGb358T5GWYiKEuCP8MvFfT3tH2mIF9Y2yr2e3KbHuSvsVhosiEyqCpiJhZQ==", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.6.0", - "@lezer/common": "^1.0.0" - }, - "peerDependencies": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.0.0" - } - }, - "node_modules/@codemirror/commands": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.2.2.tgz", - "integrity": "sha512-s9lPVW7TxXrI/7voZ+HmD/yiAlwAYn9PH5SUVSUhsxXHhv4yl5eZ3KLntSoTynfdgVYM0oIpccQEWRBQgmNZyw==", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.2.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.0.0" - } - }, - "node_modules/@codemirror/lang-python": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.1.2.tgz", - "integrity": "sha512-nbQfifLBZstpt6Oo4XxA2LOzlSp4b/7Bc5cmodG1R+Cs5PLLCTUvsMNWDnziiCfTOG/SW1rVzXq/GbIr6WXlcw==", - "dependencies": { - "@codemirror/autocomplete": "^6.3.2", - "@codemirror/language": "^6.0.0", - "@lezer/python": "^1.0.0" - } - }, - "node_modules/@codemirror/language": { - "version": "6.6.0", - "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.6.0.tgz", - "integrity": "sha512-cwUd6lzt3MfNYOobdjf14ZkLbJcnv4WtndYaoBkbor/vF+rCNguMPK0IRtvZJG4dsWiaWPcK8x1VijhvSxnstg==", - "dependencies": { - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.0.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0", - "style-mod": "^4.0.0" - } - }, - "node_modules/@codemirror/lint": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.2.0.tgz", - "integrity": "sha512-KVCECmR2fFeYBr1ZXDVue7x3q5PMI0PzcIbA+zKufnkniMBo1325t0h1jM85AKp8l3tj67LRxVpZfgDxEXlQkg==", - "dependencies": { - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "crelt": "^1.0.5" - } - }, - "node_modules/@codemirror/search": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.3.0.tgz", - "integrity": "sha512-rBhZxzT34CarfhgCZGhaLBScABDN3iqJxixzNuINp9lrb3lzm0nTpR77G1VrxGO3HOGK7j62jcJftQM7eCOIuw==", - "dependencies": { - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "crelt": "^1.0.5" - } - }, - "node_modules/@codemirror/state": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.2.0.tgz", - "integrity": "sha512-69QXtcrsc3RYtOtd+GsvczJ319udtBf1PTrr2KbLWM/e2CXUPnh0Nz9AUo8WfhSQ7GeL8dPVNUmhQVgpmuaNGA==" - }, - "node_modules/@codemirror/theme-one-dark": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.1.tgz", - "integrity": "sha512-+CfzmScfJuD6uDF5bHJkAjWTQ2QAAHxODCPxUEgcImDYcJLT+4l5vLnBHmDVv46kCC5uUJGMrBJct2Z6JbvqyQ==", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/highlight": "^1.0.0" - } - }, - "node_modules/@codemirror/view": { - "version": "6.9.3", - "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.9.3.tgz", - "integrity": "sha512-BJ5mvEIhFM+SrNwc5X8pLIvMM9ffjkviVbxpg84Xk2OE8ZyKaEbId8kX+nAYEEso7+qnbwsXe1bkAHsasebMow==", - "dependencies": { - "@codemirror/state": "^6.1.4", - "style-mod": "^4.0.0", - "w3c-keyname": "^2.2.4" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.12.tgz", - "integrity": "sha512-E/sgkvwoIfj4aMAPL2e35VnUJspzVYl7+M1B2cqeubdBhADV4uPon0KCc8p2G+LqSJ6i8ocYPCqY3A4GGq0zkQ==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.12.tgz", - "integrity": "sha512-WQ9p5oiXXYJ33F2EkE3r0FRDFVpEdcDiwNX3u7Xaibxfx6vQE0Sb8ytrfQsA5WO6kDn6mDfKLh6KrPBjvkk7xA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.12.tgz", - "integrity": "sha512-m4OsaCr5gT+se25rFPHKQXARMyAehHTQAz4XX1Vk3d27VtqiX0ALMBPoXZsGaB6JYryCLfgGwUslMqTfqeLU0w==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.12.tgz", - "integrity": "sha512-O3GCZghRIx+RAN0NDPhyyhRgwa19MoKlzGonIb5hgTj78krqp9XZbYCvFr9N1eUxg0ZQEpiiZ4QvsOQwBpP+lg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.12.tgz", - "integrity": "sha512-5D48jM3tW27h1qjaD9UNRuN+4v0zvksqZSPZqeSWggfMlsVdAhH3pwSfQIFJwcs9QJ9BRibPS4ViZgs3d2wsCA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.12.tgz", - "integrity": "sha512-OWvHzmLNTdF1erSvrfoEBGlN94IE6vCEaGEkEH29uo/VoONqPnoDFfShi41Ew+yKimx4vrmmAJEGNoyyP+OgOQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.12.tgz", - "integrity": "sha512-A0Xg5CZv8MU9xh4a+7NUpi5VHBKh1RaGJKqjxe4KG87X+mTjDE6ZvlJqpWoeJxgfXHT7IMP9tDFu7IZ03OtJAw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.12.tgz", - "integrity": "sha512-WsHyJ7b7vzHdJ1fv67Yf++2dz3D726oO3QCu8iNYik4fb5YuuReOI9OtA+n7Mk0xyQivNTPbl181s+5oZ38gyA==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.12.tgz", - "integrity": "sha512-cK3AjkEc+8v8YG02hYLQIQlOznW+v9N+OI9BAFuyqkfQFR+DnDLhEM5N8QRxAUz99cJTo1rLNXqRrvY15gbQUg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.12.tgz", - "integrity": "sha512-jdOBXJqcgHlah/nYHnj3Hrnl9l63RjtQ4vn9+bohjQPI2QafASB5MtHAoEv0JQHVb/xYQTFOeuHnNYE1zF7tYw==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.12.tgz", - "integrity": "sha512-GTOEtj8h9qPKXCyiBBnHconSCV9LwFyx/gv3Phw0pa25qPYjVuuGZ4Dk14bGCfGX3qKF0+ceeQvwmtI+aYBbVA==", - "cpu": [ - "loong64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.12.tgz", - "integrity": "sha512-o8CIhfBwKcxmEENOH9RwmUejs5jFiNoDw7YgS0EJTF6kgPgcqLFjgoc5kDey5cMHRVCIWc6kK2ShUePOcc7RbA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.12.tgz", - "integrity": "sha512-biMLH6NR/GR4z+ap0oJYb877LdBpGac8KfZoEnDiBKd7MD/xt8eaw1SFfYRUeMVx519kVkAOL2GExdFmYnZx3A==", - "cpu": [ - "ppc64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.12.tgz", - "integrity": "sha512-jkphYUiO38wZGeWlfIBMB72auOllNA2sLfiZPGDtOBb1ELN8lmqBrlMiucgL8awBw1zBXN69PmZM6g4yTX84TA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.12.tgz", - "integrity": "sha512-j3ucLdeY9HBcvODhCY4b+Ds3hWGO8t+SAidtmWu/ukfLLG/oYDMaA+dnugTVAg5fnUOGNbIYL9TOjhWgQB8W5g==", - "cpu": [ - "s390x" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.12.tgz", - "integrity": "sha512-uo5JL3cgaEGotaqSaJdRfFNSCUJOIliKLnDGWaVCgIKkHxwhYMm95pfMbWZ9l7GeW9kDg0tSxcy9NYdEtjwwmA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.12.tgz", - "integrity": "sha512-DNdoRg8JX+gGsbqt2gPgkgb00mqOgOO27KnrWZtdABl6yWTST30aibGJ6geBq3WM2TIeW6COs5AScnC7GwtGPg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.12.tgz", - "integrity": "sha512-aVsENlr7B64w8I1lhHShND5o8cW6sB9n9MUtLumFlPhG3elhNWtE7M1TFpj3m7lT3sKQUMkGFjTQBrvDDO1YWA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.12.tgz", - "integrity": "sha512-qbHGVQdKSwi0JQJuZznS4SyY27tYXYF0mrgthbxXrZI3AHKuRvU+Eqbg/F0rmLDpW/jkIZBlCO1XfHUBMNJ1pg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.12.tgz", - "integrity": "sha512-zsCp8Ql+96xXTVTmm6ffvoTSZSV2B/LzzkUXAY33F/76EajNw1m+jZ9zPfNJlJ3Rh4EzOszNDHsmG/fZOhtqDg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.12.tgz", - "integrity": "sha512-FfrFjR4id7wcFYOdqbDfDET3tjxCozUgbqdkOABsSFzoZGFC92UK7mg4JKRc/B3NNEf1s2WHxJ7VfTdVDPN3ng==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.12.tgz", - "integrity": "sha512-JOOxw49BVZx2/5tW3FqkdjSD/5gXYeVGPDcB0lvap0gLQshkh1Nyel1QazC+wNxus3xPlsYAgqU1BUmrmCvWtw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@eslint/eslintrc": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.1.tgz", - "integrity": "sha512-XXrH9Uarn0stsyldqDYq8r++mROmWRI1xKMXa640Bb//SY1+ECYX6VzT6Lcx5frD0V30XieqJ0oX9I2Xj5aoMA==", - "dev": true, - "dependencies": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.4.0", - "globals": "^13.19.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": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@hoodmane/toml-j0.4": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@hoodmane/toml-j0.4/-/toml-j0.4-1.1.2.tgz", - "integrity": "sha512-vQvFpjssFt39GcYwsFLDts6eReKSWeDwFt3AufXnM62ACIG2MgvOVomNRo4kQUYV0G3+zpu4LezUWw5JCFgF0Q==" - }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.10.7", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.10.7.tgz", - "integrity": "sha512-MDl6D6sBsaV452/QSdX+4CXIjZhIcI0PELsxUjk4U828yd58vk3bTIvk/6w5FY+4hIy9sLW0sfrV7K7Kc++j/w==", - "dev": true, - "dependencies": { - "@humanwhocodes/object-schema": "^1.2.1", - "debug": "^4.1.1", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=10.10.0" - } - }, - "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, - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@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 - }, - "node_modules/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, - "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "dependencies": { - "sprintf-js": "~1.0.2" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/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, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/@jest/console": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.5.0.tgz", - "integrity": "sha512-NEpkObxPwyw/XxZVLPmAGKE89IQRp4puc6IQRPru6JKd1M3fW9v1xM1AnzIJE65hbCkzQAdnL8P47e9hzhiYLQ==", - "dev": true, - "dependencies": { - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^29.5.0", - "jest-util": "^29.5.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/core": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.5.0.tgz", - "integrity": "sha512-28UzQc7ulUrOQw1IsN/kv1QES3q2kkbl/wGslyhAclqZ/8cMdB5M68BffkIdSJgKBUt50d3hbwJ92XESlE7LiQ==", - "dev": true, - "dependencies": { - "@jest/console": "^29.5.0", - "@jest/reporters": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^29.5.0", - "jest-config": "^29.5.0", - "jest-haste-map": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-regex-util": "^29.4.3", - "jest-resolve": "^29.5.0", - "jest-resolve-dependencies": "^29.5.0", - "jest-runner": "^29.5.0", - "jest-runtime": "^29.5.0", - "jest-snapshot": "^29.5.0", - "jest-util": "^29.5.0", - "jest-validate": "^29.5.0", - "jest-watcher": "^29.5.0", - "micromatch": "^4.0.4", - "pretty-format": "^29.5.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/environment": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.5.0.tgz", - "integrity": "sha512-5FXw2+wD29YU1d4I2htpRX7jYnAyTRjP2CsXQdo9SAM8g3ifxWPSV0HnClSn71xwctr0U3oZIIH+dtbfmnbXVQ==", - "dev": true, - "dependencies": { - "@jest/fake-timers": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "jest-mock": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.5.0.tgz", - "integrity": "sha512-PueDR2HGihN3ciUNGr4uelropW7rqUfTiOn+8u0leg/42UhblPxHkfoh0Ruu3I9Y1962P3u2DY4+h7GVTSVU6g==", - "dev": true, - "dependencies": { - "expect": "^29.5.0", - "jest-snapshot": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect-utils": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.5.0.tgz", - "integrity": "sha512-fmKzsidoXQT2KwnrwE0SQq3uj8Z763vzR8LnLBwC2qYWEFpjX8daRsk6rHUM1QvNlEW/UJXNXm59ztmJJWs2Mg==", - "dev": true, - "dependencies": { - "jest-get-type": "^29.4.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/fake-timers": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.5.0.tgz", - "integrity": "sha512-9ARvuAAQcBwDAqOnglWq2zwNIRUDtk/SCkp/ToGEhFv5r86K21l+VEs0qNTaXtyiY0lEePl3kylijSYJQqdbDg==", - "dev": true, - "dependencies": { - "@jest/types": "^29.5.0", - "@sinonjs/fake-timers": "^10.0.2", - "@types/node": "*", - "jest-message-util": "^29.5.0", - "jest-mock": "^29.5.0", - "jest-util": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/globals": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.1.2.tgz", - "integrity": "sha512-uMgfERpJYoQmykAd0ffyMq8wignN4SvLUG6orJQRe9WAlTRc9cdpCaE/29qurXixYJVZWUqIBXhSk8v5xN1V9g==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.1.2", - "@jest/expect": "^29.1.2", - "@jest/types": "^29.1.2", - "jest-mock": "^29.1.2" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/reporters": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.5.0.tgz", - "integrity": "sha512-D05STXqj/M8bP9hQNSICtPqz97u7ffGzZu+9XLucXhkOFBqKcXe04JLZOgIekOxdb73MAoBUFnqvf7MCpKk5OA==", - "dev": true, - "dependencies": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@jridgewell/trace-mapping": "^0.3.15", - "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^5.1.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "^29.5.0", - "jest-util": "^29.5.0", - "jest-worker": "^29.5.0", - "slash": "^3.0.0", - "string-length": "^4.0.1", - "strip-ansi": "^6.0.0", - "v8-to-istanbul": "^9.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/schemas": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.4.3.tgz", - "integrity": "sha512-VLYKXQmtmuEz6IxJsrZwzG9NvtkQsWNnWMsKxqWNu3+CnfzJQhp0WDDKWLVV9hLKr0l3SLLFRqcYHjhtyuDVxg==", - "dev": true, - "dependencies": { - "@sinclair/typebox": "^0.25.16" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/source-map": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.4.3.tgz", - "integrity": "sha512-qyt/mb6rLyd9j1jUts4EQncvS6Yy3PM9HghnNv86QBlV+zdL2inCdK1tuVlL+J+lpiw2BI67qXOrX3UurBqQ1w==", - "dev": true, - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.15", - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-result": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.5.0.tgz", - "integrity": "sha512-fGl4rfitnbfLsrfx1uUpDEESS7zM8JdgZgOCQuxQvL1Sn/I6ijeAVQWGfXI9zb1i9Mzo495cIpVZhA0yr60PkQ==", - "dev": true, - "dependencies": { - "@jest/console": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-sequencer": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.5.0.tgz", - "integrity": "sha512-yPafQEcKjkSfDXyvtgiV4pevSeyuA6MQr6ZIdVkWJly9vkqjnFfcfhRQqpD5whjoU8EORki752xQmjaqoFjzMQ==", - "dev": true, - "dependencies": { - "@jest/test-result": "^29.5.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.5.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/transform": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.5.0.tgz", - "integrity": "sha512-8vbeZWqLJOvHaDfeMuoHITGKSz5qWc9u04lnWrQE3VyuSw604PzQM824ZeX9XSjUCeDiE3GuxZe5UKa8J61NQw==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/types": "^29.5.0", - "@jridgewell/trace-mapping": "^0.3.15", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.5.0", - "jest-regex-util": "^29.4.3", - "jest-util": "^29.5.0", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", - "slash": "^3.0.0", - "write-file-atomic": "^4.0.2" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/types": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.5.0.tgz", - "integrity": "sha512-qbu7kN6czmVRc3xWFQcAN03RAUamgppVUdXrvl1Wr3jlNF93o9mJbGcDWrwGB6ht44u7efB1qCFgVQmca24Uog==", - "dev": true, - "dependencies": { - "@jest/schemas": "^29.4.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz", - "integrity": "sha512-sQXCasFk+U8lWYEe66WxRDOE9PjVz4vSM51fTu3Hw+ClTpUSQb718772vH3pyS5pShp6lvQM7SxgIDXXXmOX7w==", - "dev": true, - "dependencies": { - "@jridgewell/set-array": "^1.0.0", - "@jridgewell/sourcemap-codec": "^1.4.10" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", - "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/set-array": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", - "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.14", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", - "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", - "dev": true - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.17", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.17.tgz", - "integrity": "sha512-MCNzAp77qzKca9+W/+I0+sEpaUnZoeasnghNeVc41VZCEKaCH73Vq3BZZ/SzWIgrqE4H4ceI+p+b6C0mHf9T4g==", - "dev": true, - "dependencies": { - "@jridgewell/resolve-uri": "3.1.0", - "@jridgewell/sourcemap-codec": "1.4.14" - } - }, - "node_modules/@lezer/common": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.0.2.tgz", - "integrity": "sha512-SVgiGtMnMnW3ActR8SXgsDhw7a0w0ChHSYAyAUxxrOiJ1OqYWEKk/xJd84tTSPo1mo6DXLObAJALNnd0Hrv7Ng==" - }, - "node_modules/@lezer/highlight": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.1.3.tgz", - "integrity": "sha512-3vLKLPThO4td43lYRBygmMY18JN3CPh9w+XS2j8WC30vR4yZeFG4z1iFe4jXE43NtGqe//zHW5q8ENLlHvz9gw==", - "dependencies": { - "@lezer/common": "^1.0.0" - } - }, - "node_modules/@lezer/lr": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.3.3.tgz", - "integrity": "sha512-JPQe3mwJlzEVqy67iQiiGozhcngbO8QBgpqZM6oL1Wj/dXckrEexpBLeFkq0edtW5IqnPRFxA24BHJni8Js69w==", - "dependencies": { - "@lezer/common": "^1.0.0" - } - }, - "node_modules/@lezer/python": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.3.tgz", - "integrity": "sha512-rUdt5/H8JjVY3YIROZF2ZNUMx7eYB7h0cmC8c4TfkgJt4xcn6vLpjCOCk1usP4vV3YfMC+VDB786dKjJ6tL5Hw==", - "dependencies": { - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" - } - }, - "node_modules/@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, - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@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, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@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, - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@sinclair/typebox": { - "version": "0.25.24", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.25.24.tgz", - "integrity": "sha512-XJfwUVUKDHF5ugKwIcxEgc9k8b7HbznCp6eUfWgu710hMPNIO4aw4/zB5RogDQz8nd6gyCDpU9O/m6qYEWY6yQ==", - "dev": true - }, - "node_modules/@sinonjs/commons": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-2.0.0.tgz", - "integrity": "sha512-uLa0j859mMrg2slwQYdO/AkrOfmH+X6LTVmNTS9CqexuE2IvVORIkSpJLqePAbEnKJ77aMmCwr1NUZ57120Xcg==", - "dev": true, - "dependencies": { - "type-detect": "4.0.8" - } - }, - "node_modules/@sinonjs/fake-timers": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.0.2.tgz", - "integrity": "sha512-SwUDyjWnah1AaNl7kxsa7cfLhlTYoiyhDAIgyh+El30YvXs/o7OLXpYH88Zdhyx9JExKrmHDJ+10bwIcY80Jmw==", - "dev": true, - "dependencies": { - "@sinonjs/commons": "^2.0.0" - } - }, - "node_modules/@tootallnate/once": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", - "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", - "dev": true, - "engines": { - "node": ">= 10" - } - }, - "node_modules/@types/babel__core": { - "version": "7.20.0", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.0.tgz", - "integrity": "sha512-+n8dL/9GWblDO0iU6eZAwEIJVr5DWigtle+Q6HLOrh/pdbXOhOtqzq8VPPE2zvNJzSKY4vH/z3iT3tn0A3ypiQ==", - "dev": true, - "dependencies": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "node_modules/@types/babel__generator": { - "version": "7.6.4", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", - "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", - "dev": true, - "dependencies": { - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__template": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", - "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", - "dev": true, - "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__traverse": { - "version": "7.18.3", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.18.3.tgz", - "integrity": "sha512-1kbcJ40lLB7MHsj39U4Sh1uTd2E7rLEa79kmDpI6cy+XiXsteB3POdQomoq4FxszMrO3ZYchkhYJw7A2862b3w==", - "dev": true, - "dependencies": { - "@babel/types": "^7.3.0" - } - }, - "node_modules/@types/codemirror": { - "version": "5.60.7", - "resolved": "https://registry.npmjs.org/@types/codemirror/-/codemirror-5.60.7.tgz", - "integrity": "sha512-QXIC+RPzt/1BGSuD6iFn6UMC9TDp+9hkOANYNPVsjjrDdzKphfRkwQDKGp2YaC54Yhz0g6P5uYTCCibZZEiMAA==", - "dev": true, - "dependencies": { - "@types/tern": "*" - } - }, - "node_modules/@types/estree": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.0.tgz", - "integrity": "sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ==", - "dev": true - }, - "node_modules/@types/graceful-fs": { - "version": "4.1.6", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.6.tgz", - "integrity": "sha512-Sig0SNORX9fdW+bQuTEovKj3uHcUL6LQKbCrrqb1X7J6/ReAbhCXRAhc+SMejhLELFj2QcyuxmUooZ4bt5ReSw==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/istanbul-lib-coverage": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", - "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", - "dev": true - }, - "node_modules/@types/istanbul-lib-report": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", - "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", - "dev": true, - "dependencies": { - "@types/istanbul-lib-coverage": "*" - } - }, - "node_modules/@types/istanbul-reports": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", - "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", - "dev": true, - "dependencies": { - "@types/istanbul-lib-report": "*" - } - }, - "node_modules/@types/jest": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.1.2.tgz", - "integrity": "sha512-y+nlX0h87U0R+wsGn6EBuoRWYyv3KFtwRNP3QWp9+k2tJ2/bqcGS3UxD7jgT+tiwJWWq3UsyV4Y+T6rsMT4XMg==", - "dev": true, - "dependencies": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" - } - }, - "node_modules/@types/jsdom": { - "version": "20.0.1", - "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-20.0.1.tgz", - "integrity": "sha512-d0r18sZPmMQr1eG35u12FZfhIXNrnsPU/g5wvRKCUf/tOGilKKwYMYGqh33BNR6ba+2gkHw1EUiHoN3mn7E5IQ==", - "dev": true, - "dependencies": { - "@types/node": "*", - "@types/tough-cookie": "*", - "parse5": "^7.0.0" - } - }, - "node_modules/@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 - }, - "node_modules/@types/node": { - "version": "18.8.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.8.3.tgz", - "integrity": "sha512-0os9vz6BpGwxGe9LOhgP/ncvYN5Tx1fNcd2TM3rD/aCGBkysb+ZWpXEocG24h6ZzOi13+VB8HndAQFezsSOw1w==", - "dev": true - }, - "node_modules/@types/prettier": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", - "integrity": "sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==", - "dev": true - }, - "node_modules/@types/stack-utils": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", - "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", - "dev": true - }, - "node_modules/@types/tern": { - "version": "0.23.4", - "resolved": "https://registry.npmjs.org/@types/tern/-/tern-0.23.4.tgz", - "integrity": "sha512-JAUw1iXGO1qaWwEOzxTKJZ/5JxVeON9kvGZ/osgZaJImBnyjyn0cjovPsf6FNLmyGY8Vw9DoXZCMlfMkMwHRWg==", - "dev": true, - "dependencies": { - "@types/estree": "*" - } - }, - "node_modules/@types/tough-cookie": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.2.tgz", - "integrity": "sha512-Q5vtl1W5ue16D+nIaW8JWebSSraJVlK+EthKn7e7UcD4KWsaSJ8BqGPXNaPghgtcn/fhvrN17Tv8ksUsQpiplw==", - "dev": true - }, - "node_modules/@types/yargs": { - "version": "17.0.23", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.23.tgz", - "integrity": "sha512-yuogunc04OnzGQCrfHx+Kk883Q4X0aSwmYZhKjI21m+SVYzjIbrWl8dOOwSv5hf2Um2pdCOXWo9isteZTNXUZQ==", - "dev": true, - "dependencies": { - "@types/yargs-parser": "*" - } - }, - "node_modules/@types/yargs-parser": { - "version": "21.0.0", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", - "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", - "dev": true - }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.39.0.tgz", - "integrity": "sha512-xVfKOkBm5iWMNGKQ2fwX5GVgBuHmZBO1tCRwXmY5oAIsPscfwm2UADDuNB8ZVYCtpQvJK4xpjrK7jEhcJ0zY9A==", - "dev": true, - "dependencies": { - "@typescript-eslint/scope-manager": "5.39.0", - "@typescript-eslint/type-utils": "5.39.0", - "@typescript-eslint/utils": "5.39.0", - "debug": "^4.3.4", - "ignore": "^5.2.0", - "regexpp": "^3.2.0", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^5.0.0", - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.39.0.tgz", - "integrity": "sha512-PhxLjrZnHShe431sBAGHaNe6BDdxAASDySgsBCGxcBecVCi8NQWxQZMcizNA4g0pN51bBAn/FUfkWG3SDVcGlA==", - "dev": true, - "dependencies": { - "@typescript-eslint/scope-manager": "5.39.0", - "@typescript-eslint/types": "5.39.0", - "@typescript-eslint/typescript-estree": "5.39.0", - "debug": "^4.3.4" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.39.0.tgz", - "integrity": "sha512-/I13vAqmG3dyqMVSZPjsbuNQlYS082Y7OMkwhCfLXYsmlI0ca4nkL7wJ/4gjX70LD4P8Hnw1JywUVVAwepURBw==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "5.39.0", - "@typescript-eslint/visitor-keys": "5.39.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.39.0.tgz", - "integrity": "sha512-KJHJkOothljQWzR3t/GunL0TPKY+fGJtnpl+pX+sJ0YiKTz3q2Zr87SGTmFqsCMFrLt5E0+o+S6eQY0FAXj9uA==", - "dev": true, - "dependencies": { - "@typescript-eslint/typescript-estree": "5.39.0", - "@typescript-eslint/utils": "5.39.0", - "debug": "^4.3.4", - "tsutils": "^3.21.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "*" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/types": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.39.0.tgz", - "integrity": "sha512-gQMZrnfEBFXK38hYqt8Lkwt8f4U6yq+2H5VDSgP/qiTzC8Nw8JO3OuSUOQ2qW37S/dlwdkHDntkZM6SQhKyPhw==", - "dev": true, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.39.0.tgz", - "integrity": "sha512-qLFQP0f398sdnogJoLtd43pUgB18Q50QSA+BTE5h3sUxySzbWDpTSdgt4UyxNSozY/oDK2ta6HVAzvGgq8JYnA==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "5.39.0", - "@typescript-eslint/visitor-keys": "5.39.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/utils": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.39.0.tgz", - "integrity": "sha512-+DnY5jkpOpgj+EBtYPyHRjXampJfC0yUZZzfzLuUWVZvCuKqSdJVC8UhdWipIw7VKNTfwfAPiOWzYkAwuIhiAg==", - "dev": true, - "dependencies": { - "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.39.0", - "@typescript-eslint/types": "5.39.0", - "@typescript-eslint/typescript-estree": "5.39.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.39.0.tgz", - "integrity": "sha512-yyE3RPwOG+XJBLrhvsxAidUgybJVQ/hG8BhiJo0k8JSAYfk/CshVcxf0HwP4Jt7WZZ6vLmxdo1p6EyN3tzFTkg==", - "dev": true, - "dependencies": { - "@typescript-eslint/types": "5.39.0", - "eslint-visitor-keys": "^3.3.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/abab": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", - "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", - "dev": true - }, - "node_modules/acorn": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", - "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", - "dev": true, - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-globals": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-7.0.1.tgz", - "integrity": "sha512-umOSDSDrfHbTNPuNpC2NSnnA3LUrqpevPb4T9jRx4MagXNS0rs+gwiTcAvqCRmsD6utzsrzNt+ebm00SNWiC3Q==", - "dev": true, - "dependencies": { - "acorn": "^8.1.0", - "acorn-walk": "^8.0.2" - } - }, - "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, - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "dev": true, - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "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, - "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-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "dev": true, - "dependencies": { - "type-fest": "^0.21.3" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ansi-escapes/node_modules/type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "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, - "engines": { - "node": ">=8" - } - }, - "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, - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "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 - }, - "node_modules/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, - "engines": { - "node": ">=8" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true - }, - "node_modules/babel-jest": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.5.0.tgz", - "integrity": "sha512-mA4eCDh5mSo2EcA9xQjVTpmbbNk32Zb3Q3QFQsNhaK56Q+yoXowzFodLux30HRgyOho5rsQ6B0P9QpMkvvnJ0Q==", - "dev": true, - "dependencies": { - "@jest/transform": "^29.5.0", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^29.5.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.8.0" - } - }, - "node_modules/babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-jest-hoist": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.5.0.tgz", - "integrity": "sha512-zSuuuAlTMT4mzLj2nPnUm6fsE6270vdOfnpbJ+RmruU75UhLFvL0N2NgI7xpeS7NaB6hGqmd5pVpGTDYvi4Q3w==", - "dev": true, - "dependencies": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.1.14", - "@types/babel__traverse": "^7.0.6" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/babel-preset-current-node-syntax": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", - "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", - "dev": true, - "dependencies": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.8.3", - "@babel/plugin-syntax-import-meta": "^7.8.3", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.8.3", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-top-level-await": "^7.8.3" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/babel-preset-jest": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.5.0.tgz", - "integrity": "sha512-JOMloxOqdiBSxMAzjRaH023/vvcaSaec49zvg+2LmNsktC7ei39LTJGw02J+9uUtTZUq6xbLyJ4dxe9sSmIuAg==", - "dev": true, - "dependencies": { - "babel-plugin-jest-hoist": "^29.5.0", - "babel-preset-current-node-syntax": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.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 - }, - "node_modules/base-64": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", - "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==", - "dev": true - }, - "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, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "dev": true, - "dependencies": { - "fill-range": "^7.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/browserslist": { - "version": "4.21.5", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.5.tgz", - "integrity": "sha512-tUkiguQGW7S3IhB7N+c2MV/HZPSCPAAiYBZXLsBhFB/PCy6ZKKsZrmBayHV9fdGV/ARIfJ14NkxKzRDjvp7L6w==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - } - ], - "dependencies": { - "caniuse-lite": "^1.0.30001449", - "electron-to-chromium": "^1.4.284", - "node-releases": "^2.0.8", - "update-browserslist-db": "^1.0.10" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/bs-logger": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", - "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", - "dev": true, - "dependencies": { - "fast-json-stable-stringify": "2.x" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", - "dev": true, - "dependencies": { - "node-int64": "^0.4.0" - } - }, - "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 - }, - "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, - "engines": { - "node": ">=6" - } - }, - "node_modules/camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001469", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001469.tgz", - "integrity": "sha512-Rcp7221ScNqQPP3W+lVOYDyjdR6dC+neEQCttoNr5bAyz54AboB4iwpnWgyi8P4YUsPybVzT4LgWiBbI3drL4g==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - } - ] - }, - "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, - "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/char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/ci-info": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.8.0.tgz", - "integrity": "sha512-eXTggHWSooYhq49F2opQhuHWgzucfF2YgODK4e1566GQs5BIfP30B0oenwBJHfWxAs2fyPB1s7Mg949zLf61Yw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "engines": { - "node": ">=8" - } - }, - "node_modules/cjs-module-lexer": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz", - "integrity": "sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==", - "dev": true - }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "dev": true, - "engines": { - "iojs": ">= 1.0.0", - "node": ">= 0.12.0" - } - }, - "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==", - "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/collect-v8-coverage": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", - "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==", - "dev": true - }, - "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, - "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 - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "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 - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true - }, - "node_modules/crelt": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.5.tgz", - "integrity": "sha512-+BO9wPPi+DWTDcNYhr/W90myha8ptzftZT+LwcmUbbok0rcP/fequmFYCw8NMoH7pkAZQzU78b3kYrlua5a9eA==" - }, - "node_modules/cross-env": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", - "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", - "dev": true, - "dependencies": { - "cross-spawn": "^7.0.1" - }, - "bin": { - "cross-env": "src/bin/cross-env.js", - "cross-env-shell": "src/bin/cross-env-shell.js" - }, - "engines": { - "node": ">=10.14", - "npm": ">=6", - "yarn": ">=1" - } - }, - "node_modules/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, - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/cssom": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", - "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", - "dev": true - }, - "node_modules/cssstyle": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", - "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", - "dev": true, - "dependencies": { - "cssom": "~0.3.6" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cssstyle/node_modules/cssom": { - "version": "0.3.8", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", - "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", - "dev": true - }, - "node_modules/data-urls": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-3.0.2.tgz", - "integrity": "sha512-Jy/tj3ldjZJo63sVAvg6LHt2mHvl4V6AgRAmNDtLdm7faqtsx+aJG42rsyCo9JCoRVKwPFzKlIPx3DIibwSIaQ==", - "dev": true, - "dependencies": { - "abab": "^2.0.6", - "whatwg-mimetype": "^3.0.0", - "whatwg-url": "^11.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dev": true, - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/decimal.js": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz", - "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==", - "dev": true - }, - "node_modules/dedent": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", - "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==", - "dev": 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 - }, - "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, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/diff-sequences": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.4.3.tgz", - "integrity": "sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/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, - "dependencies": { - "path-type": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/domexception": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz", - "integrity": "sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==", - "dev": true, - "dependencies": { - "webidl-conversions": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/electron-to-chromium": { - "version": "1.4.334", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.334.tgz", - "integrity": "sha512-laZ1odk+TRen6q0GeyQx/JEkpD3iSZT7ewopCpKqg9bTjP1l8XRfU3Bg20CFjNPZkp5+NDBl3iqd4o/kPO+Vew==", - "dev": true - }, - "node_modules/emittery": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", - "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sindresorhus/emittery?sponsor=1" - } - }, - "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 - }, - "node_modules/entities": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.4.0.tgz", - "integrity": "sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==", - "dev": true, - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/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, - "dependencies": { - "is-arrayish": "^0.2.1" - } - }, - "node_modules/esbuild": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.12.tgz", - "integrity": "sha512-bX/zHl7Gn2CpQwcMtRogTTBf9l1nl+H6R8nUbjk+RuKqAE3+8FDulLA+pHvX7aA7Xe07Iwa+CWvy9I8Y2qqPKQ==", - "dev": true, - "hasInstallScript": true, - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=12" - }, - "optionalDependencies": { - "@esbuild/android-arm": "0.17.12", - "@esbuild/android-arm64": "0.17.12", - "@esbuild/android-x64": "0.17.12", - "@esbuild/darwin-arm64": "0.17.12", - "@esbuild/darwin-x64": "0.17.12", - "@esbuild/freebsd-arm64": "0.17.12", - "@esbuild/freebsd-x64": "0.17.12", - "@esbuild/linux-arm": "0.17.12", - "@esbuild/linux-arm64": "0.17.12", - "@esbuild/linux-ia32": "0.17.12", - "@esbuild/linux-loong64": "0.17.12", - "@esbuild/linux-mips64el": "0.17.12", - "@esbuild/linux-ppc64": "0.17.12", - "@esbuild/linux-riscv64": "0.17.12", - "@esbuild/linux-s390x": "0.17.12", - "@esbuild/linux-x64": "0.17.12", - "@esbuild/netbsd-x64": "0.17.12", - "@esbuild/openbsd-x64": "0.17.12", - "@esbuild/sunos-x64": "0.17.12", - "@esbuild/win32-arm64": "0.17.12", - "@esbuild/win32-ia32": "0.17.12", - "@esbuild/win32-x64": "0.17.12" - } - }, - "node_modules/escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "dev": true, - "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, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/escodegen": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.0.0.tgz", - "integrity": "sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw==", - "dev": true, - "dependencies": { - "esprima": "^4.0.1", - "estraverse": "^5.2.0", - "esutils": "^2.0.2", - "optionator": "^0.8.1" - }, - "bin": { - "escodegen": "bin/escodegen.js", - "esgenerate": "bin/esgenerate.js" - }, - "engines": { - "node": ">=6.0" - }, - "optionalDependencies": { - "source-map": "~0.6.1" - } - }, - "node_modules/escodegen/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, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/escodegen/node_modules/levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", - "dev": true, - "dependencies": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/escodegen/node_modules/optionator": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", - "dev": true, - "dependencies": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.6", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "word-wrap": "~1.2.3" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/escodegen/node_modules/prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/escodegen/node_modules/type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg==", - "dev": true, - "dependencies": { - "prelude-ls": "~1.1.2" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/eslint": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.25.0.tgz", - "integrity": "sha512-DVlJOZ4Pn50zcKW5bYH7GQK/9MsoQG2d5eDH0ebEkE8PbgzTTmtt/VTH9GGJ4BfeZCpBLqFfvsjX35UacUL83A==", - "dev": true, - "dependencies": { - "@eslint/eslintrc": "^1.3.3", - "@humanwhocodes/config-array": "^0.10.5", - "@humanwhocodes/module-importer": "^1.0.1", - "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.4.0", - "esquery": "^1.4.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "find-up": "^5.0.0", - "glob-parent": "^6.0.1", - "globals": "^13.15.0", - "globby": "^11.1.0", - "grapheme-splitter": "^1.0.4", - "ignore": "^5.2.0", - "import-fresh": "^3.0.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "js-sdsl": "^4.1.4", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "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" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/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, - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/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, - "dependencies": { - "eslint-visitor-keys": "^2.0.0" - }, - "engines": { - "node": "^10.0.0 || ^12.0.0 || >= 14.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - }, - "peerDependencies": { - "eslint": ">=5" - } - }, - "node_modules/eslint-utils/node_modules/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, - "engines": { - "node": ">=10" - } - }, - "node_modules/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, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, - "node_modules/eslint/node_modules/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, - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, - "node_modules/eslint/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, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/espree": { - "version": "9.5.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.5.0.tgz", - "integrity": "sha512-JPbJGhKc47++oo4JkEoTe2wjy4fmMwvFpgJT9cQzmfXKp22Dr6Hf1tdCteLz1h0P3t+mGvWZ+4Uankvh8+c6zw==", - "dev": true, - "dependencies": { - "acorn": "^8.8.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.3.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/esquery": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", - "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", - "dev": true, - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esquery/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, - "engines": { - "node": ">=4.0" - } - }, - "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, - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esrecurse/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, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true, - "engines": { - "node": ">=4.0" - } - }, - "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, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/expect": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.5.0.tgz", - "integrity": "sha512-yM7xqUrCO2JdpFo4XpM82t+PJBFybdqoQuJLDGeDX2ij8NZzqRHyu3Hp188/JX7SWqud+7t4MUdvcgGBICMHZg==", - "dev": true, - "dependencies": { - "@jest/expect-utils": "^29.5.0", - "jest-get-type": "^29.4.3", - "jest-matcher-utils": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-util": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "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 - }, - "node_modules/fast-glob": { - "version": "3.2.12", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.12.tgz", - "integrity": "sha512-DVj4CQIYYow0BlaelwK1pHl5n5cRSJfM60UA0zK891sVInoPri2Ekj7+e1CT3/3qxXenpI+nBBmQAcJPJgaj4w==", - "dev": true, - "dependencies": { - "@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" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-glob/node_modules/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, - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "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 - }, - "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 - }, - "node_modules/fastq": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", - "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", - "dev": true, - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fb-watchman": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", - "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", - "dev": true, - "dependencies": { - "bser": "2.1.1" - } - }, - "node_modules/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, - "dependencies": { - "flat-cache": "^3.0.4" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/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, - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "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, - "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": "3.0.4", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz", - "integrity": "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==", - "dev": true, - "dependencies": { - "flatted": "^3.1.0", - "rimraf": "^3.0.2" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/flatted": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.7.tgz", - "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", - "dev": true - }, - "node_modules/form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true - }, - "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, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "dev": true - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "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, - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/globals": { - "version": "13.20.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.20.0.tgz", - "integrity": "sha512-Qg5QtVkCy/kv3FUSlu4ukeZDVf9ee0iXLAUYX13gbR17bnejFTzr4iS9bY7kwCf1NztRNm1t91fjOiyx4CSwPQ==", - "dev": true, - "dependencies": { - "type-fest": "^0.20.2" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/globby": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", - "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", - "dev": true, - "dependencies": { - "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" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true - }, - "node_modules/grapheme-splitter": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz", - "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", - "dev": true - }, - "node_modules/has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "dev": true, - "dependencies": { - "function-bind": "^1.1.1" - }, - "engines": { - "node": ">= 0.4.0" - } - }, - "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, - "engines": { - "node": ">=8" - } - }, - "node_modules/html-encoding-sniffer": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", - "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==", - "dev": true, - "dependencies": { - "whatwg-encoding": "^2.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true - }, - "node_modules/http-proxy-agent": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", - "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", - "dev": true, - "dependencies": { - "@tootallnate/once": "2", - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "dev": true, - "dependencies": { - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true, - "engines": { - "node": ">=10.17.0" - } - }, - "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "dev": true, - "engines": { - "node": ">= 4" - } - }, - "node_modules/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, - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/import-local": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", - "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", - "dev": true, - "dependencies": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - }, - "bin": { - "import-local-fixture": "fixtures/cli.js" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "dev": true, - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true - }, - "node_modules/is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true - }, - "node_modules/is-core-module": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", - "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", - "dev": true, - "dependencies": { - "has": "^1.0.3" - }, - "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, - "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, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "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, - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/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, - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-potential-custom-element-name": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", - "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true - }, - "node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true - }, - "node_modules/istanbul-lib-coverage": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", - "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/istanbul-lib-report": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", - "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", - "dev": true, - "dependencies": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^3.0.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "dev": true, - "dependencies": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-reports": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.5.tgz", - "integrity": "sha512-nUsEMa9pBt/NOHqbcbeJEgqIlY/K7rVWUX6Lql2orY5e9roQOthbR3vtY4zzf2orPELg80fnxxk9zUyPlgwD1w==", - "dev": true, - "dependencies": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/jest": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/jest/-/jest-29.1.2.tgz", - "integrity": "sha512-5wEIPpCezgORnqf+rCaYD1SK+mNN7NsstWzIsuvsnrhR/hSxXWd82oI7DkrbJ+XTD28/eG8SmxdGvukrGGK6Tw==", - "dev": true, - "dependencies": { - "@jest/core": "^29.1.2", - "@jest/types": "^29.1.2", - "import-local": "^3.0.2", - "jest-cli": "^29.1.2" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-changed-files": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.5.0.tgz", - "integrity": "sha512-IFG34IUMUaNBIxjQXF/iu7g6EcdMrGRRxaUSw92I/2g2YC6vCdTltl4nHvt7Ci5nSJwXIkCu8Ka1DKF+X7Z1Ag==", - "dev": true, - "dependencies": { - "execa": "^5.0.0", - "p-limit": "^3.1.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-circus": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.5.0.tgz", - "integrity": "sha512-gq/ongqeQKAplVxqJmbeUOJJKkW3dDNPY8PjhJ5G0lBRvu0e3EWGxGy5cI4LAGA7gV2UHCtWBI4EMXK8c9nQKA==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.5.0", - "@jest/expect": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "dedent": "^0.7.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^29.5.0", - "jest-matcher-utils": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-runtime": "^29.5.0", - "jest-snapshot": "^29.5.0", - "jest-util": "^29.5.0", - "p-limit": "^3.1.0", - "pretty-format": "^29.5.0", - "pure-rand": "^6.0.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-cli": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.5.0.tgz", - "integrity": "sha512-L1KcP1l4HtfwdxXNFCL5bmUbLQiKrakMUriBEcc1Vfz6gx31ORKdreuWvmQVBit+1ss9NNR3yxjwfwzZNdQXJw==", - "dev": true, - "dependencies": { - "@jest/core": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/types": "^29.5.0", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "import-local": "^3.0.2", - "jest-config": "^29.5.0", - "jest-util": "^29.5.0", - "jest-validate": "^29.5.0", - "prompts": "^2.0.1", - "yargs": "^17.3.1" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-config": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.5.0.tgz", - "integrity": "sha512-kvDUKBnNJPNBmFFOhDbm59iu1Fii1Q6SxyhXfvylq3UTHbg6o7j/g8k2dZyXWLvfdKB1vAPxNZnMgtKJcmu3kA==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/test-sequencer": "^29.5.0", - "@jest/types": "^29.5.0", - "babel-jest": "^29.5.0", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-circus": "^29.5.0", - "jest-environment-node": "^29.5.0", - "jest-get-type": "^29.4.3", - "jest-regex-util": "^29.4.3", - "jest-resolve": "^29.5.0", - "jest-runner": "^29.5.0", - "jest-util": "^29.5.0", - "jest-validate": "^29.5.0", - "micromatch": "^4.0.4", - "parse-json": "^5.2.0", - "pretty-format": "^29.5.0", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@types/node": "*", - "ts-node": ">=9.0.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "ts-node": { - "optional": true - } - } - }, - "node_modules/jest-diff": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.5.0.tgz", - "integrity": "sha512-LtxijLLZBduXnHSniy0WMdaHjmQnt3g5sa16W4p0HqukYTTsyTW3GD1q41TyGl5YFXj/5B2U6dlh5FM1LIMgxw==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "diff-sequences": "^29.4.3", - "jest-get-type": "^29.4.3", - "pretty-format": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-docblock": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.4.3.tgz", - "integrity": "sha512-fzdTftThczeSD9nZ3fzA/4KkHtnmllawWrXO69vtI+L9WjEIuXWs4AmyME7lN5hU7dB0sHhuPfcKofRsUb/2Fg==", - "dev": true, - "dependencies": { - "detect-newline": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-each": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.5.0.tgz", - "integrity": "sha512-HM5kIJ1BTnVt+DQZ2ALp3rzXEl+g726csObrW/jpEGl+CDSSQpOJJX2KE/vEg8cxcMXdyEPu6U4QX5eruQv5hA==", - "dev": true, - "dependencies": { - "@jest/types": "^29.5.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.4.3", - "jest-util": "^29.5.0", - "pretty-format": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-environment-jsdom": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.1.2.tgz", - "integrity": "sha512-D+XNIKia5+uDjSMwL/G1l6N9MCb7LymKI8FpcLo7kkISjc/Sa9w+dXXEa7u1Wijo3f8sVLqfxdGqYtRhmca+Xw==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.1.2", - "@jest/fake-timers": "^29.1.2", - "@jest/types": "^29.1.2", - "@types/jsdom": "^20.0.0", - "@types/node": "*", - "jest-mock": "^29.1.2", - "jest-util": "^29.1.2", - "jsdom": "^20.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-environment-node": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.5.0.tgz", - "integrity": "sha512-ExxuIK/+yQ+6PRGaHkKewYtg6hto2uGCgvKdb2nfJfKXgZ17DfXjvbZ+jA1Qt9A8EQSfPnt5FKIfnOO3u1h9qw==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.5.0", - "@jest/fake-timers": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "jest-mock": "^29.5.0", - "jest-util": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-get-type": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.4.3.tgz", - "integrity": "sha512-J5Xez4nRRMjk8emnTpWrlkyb9pfRQQanDrvWHhsR1+VUfbwxi30eVcZFlcdGInRibU4G5LwHXpI7IRHU0CY+gg==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-haste-map": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.5.0.tgz", - "integrity": "sha512-IspOPnnBro8YfVYSw6yDRKh/TiCdRngjxeacCps1cQ9cgVN6+10JUcuJ1EabrgYLOATsIAigxA0rLR9x/YlrSA==", - "dev": true, - "dependencies": { - "@jest/types": "^29.5.0", - "@types/graceful-fs": "^4.1.3", - "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^29.4.3", - "jest-util": "^29.5.0", - "jest-worker": "^29.5.0", - "micromatch": "^4.0.4", - "walker": "^1.0.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "optionalDependencies": { - "fsevents": "^2.3.2" - } - }, - "node_modules/jest-leak-detector": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.5.0.tgz", - "integrity": "sha512-u9YdeeVnghBUtpN5mVxjID7KbkKE1QU4f6uUwuxiY0vYRi9BUCLKlPEZfDGR67ofdFmDz9oPAy2G92Ujrntmow==", - "dev": true, - "dependencies": { - "jest-get-type": "^29.4.3", - "pretty-format": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-matcher-utils": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.5.0.tgz", - "integrity": "sha512-lecRtgm/rjIK0CQ7LPQwzCs2VwW6WAahA55YBuI+xqmhm7LAaxokSB8C97yJeYyT+HvQkH741StzpU41wohhWw==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "jest-diff": "^29.5.0", - "jest-get-type": "^29.4.3", - "pretty-format": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-message-util": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.5.0.tgz", - "integrity": "sha512-Kijeg9Dag6CKtIDA7O21zNTACqD5MD/8HfIV8pdD94vFyFuer52SigdC3IQMhab3vACxXMiFk+yMHNdbqtyTGA==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.5.0", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.5.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-mock": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.5.0.tgz", - "integrity": "sha512-GqOzvdWDE4fAV2bWQLQCkujxYWL7RxjCnj71b5VhDAGOevB3qj3Ovg26A5NI84ZpODxyzaozXLOh2NCgkbvyaw==", - "dev": true, - "dependencies": { - "@jest/types": "^29.5.0", - "@types/node": "*", - "jest-util": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "dev": true, - "engines": { - "node": ">=6" - }, - "peerDependencies": { - "jest-resolve": "*" - }, - "peerDependenciesMeta": { - "jest-resolve": { - "optional": true - } - } - }, - "node_modules/jest-regex-util": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.4.3.tgz", - "integrity": "sha512-O4FglZaMmWXbGHSQInfXewIsd1LMn9p3ZXB/6r4FOkyhX2/iP/soMG98jGvk/A3HAN78+5VWcBGO0BJAPRh4kg==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.5.0.tgz", - "integrity": "sha512-1TzxJ37FQq7J10jPtQjcc+MkCkE3GBpBecsSUWJ0qZNJpmg6m0D9/7II03yJulm3H/fvVjgqLh/k2eYg+ui52w==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.5.0", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^29.5.0", - "jest-validate": "^29.5.0", - "resolve": "^1.20.0", - "resolve.exports": "^2.0.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve-dependencies": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.5.0.tgz", - "integrity": "sha512-sjV3GFr0hDJMBpYeUuGduP+YeCRbd7S/ck6IvL3kQ9cpySYKqcqhdLLC2rFwrcL7tz5vYibomBrsFYWkIGGjOg==", - "dev": true, - "dependencies": { - "jest-regex-util": "^29.4.3", - "jest-snapshot": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runner": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.5.0.tgz", - "integrity": "sha512-m7b6ypERhFghJsslMLhydaXBiLf7+jXy8FwGRHO3BGV1mcQpPbwiqiKUR2zU2NJuNeMenJmlFZCsIqzJCTeGLQ==", - "dev": true, - "dependencies": { - "@jest/console": "^29.5.0", - "@jest/environment": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^29.4.3", - "jest-environment-node": "^29.5.0", - "jest-haste-map": "^29.5.0", - "jest-leak-detector": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-resolve": "^29.5.0", - "jest-runtime": "^29.5.0", - "jest-util": "^29.5.0", - "jest-watcher": "^29.5.0", - "jest-worker": "^29.5.0", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runtime": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.5.0.tgz", - "integrity": "sha512-1Hr6Hh7bAgXQP+pln3homOiEZtCDZFqwmle7Ew2j8OlbkIu6uE3Y/etJQG8MLQs3Zy90xrp2C0BRrtPHG4zryw==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.5.0", - "@jest/fake-timers": "^29.5.0", - "@jest/globals": "^29.5.0", - "@jest/source-map": "^29.4.3", - "@jest/test-result": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-mock": "^29.5.0", - "jest-regex-util": "^29.4.3", - "jest-resolve": "^29.5.0", - "jest-snapshot": "^29.5.0", - "jest-util": "^29.5.0", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runtime/node_modules/@jest/globals": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.5.0.tgz", - "integrity": "sha512-S02y0qMWGihdzNbUiqSAiKSpSozSuHX5UYc7QbnHP+D9Lyw8DgGGCinrN9uSuHPeKgSSzvPom2q1nAtBvUsvPQ==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.5.0", - "@jest/expect": "^29.5.0", - "@jest/types": "^29.5.0", - "jest-mock": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-snapshot": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.5.0.tgz", - "integrity": "sha512-x7Wolra5V0tt3wRs3/ts3S6ciSQVypgGQlJpz2rsdQYoUKxMxPNaoHMGJN6qAuPJqS+2iQ1ZUn5kl7HCyls84g==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-jsx": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/traverse": "^7.7.2", - "@babel/types": "^7.3.3", - "@jest/expect-utils": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/babel__traverse": "^7.0.6", - "@types/prettier": "^2.1.5", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^29.5.0", - "graceful-fs": "^4.2.9", - "jest-diff": "^29.5.0", - "jest-get-type": "^29.4.3", - "jest-matcher-utils": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-util": "^29.5.0", - "natural-compare": "^1.4.0", - "pretty-format": "^29.5.0", - "semver": "^7.3.5" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-util": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.5.0.tgz", - "integrity": "sha512-RYMgG/MTadOr5t8KdhejfvUU82MxsCu5MF6KuDUHl+NuwzUt+Sm6jJWxTJVrDR1j5M/gJVCPKQEpWXY+yIQ6lQ==", - "dev": true, - "dependencies": { - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.5.0.tgz", - "integrity": "sha512-pC26etNIi+y3HV8A+tUGr/lph9B18GnzSRAkPaaZJIE1eFdiYm6/CewuiJQ8/RlfHd1u/8Ioi8/sJ+CmbA+zAQ==", - "dev": true, - "dependencies": { - "@jest/types": "^29.5.0", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.4.3", - "leven": "^3.1.0", - "pretty-format": "^29.5.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate/node_modules/camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/jest-watcher": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.5.0.tgz", - "integrity": "sha512-KmTojKcapuqYrKDpRwfqcQ3zjMlwu27SYext9pt4GlF5FUgB+7XE1mcCnSm6a4uUpFyQIkb6ZhzZvHl+jiBCiA==", - "dev": true, - "dependencies": { - "@jest/test-result": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "jest-util": "^29.5.0", - "string-length": "^4.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.5.0.tgz", - "integrity": "sha512-NcrQnevGoSp4b5kg+akIpthoAFHxPBcb5P6mYPY0fUNT+sSvmtu6jlkEle3anczUKIKEbMxFimk9oTP/tpIPgA==", - "dev": true, - "dependencies": { - "@types/node": "*", - "jest-util": "^29.5.0", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, - "node_modules/js-sdsl": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.3.0.tgz", - "integrity": "sha512-mifzlm2+5nZ+lEcLJMoBK0/IH/bDg8XnJfd/Wq6IP+xoCjLZsTOnV2QpxlVbX9bMnkl5PdEjNtBJ9Cj1NjifhQ==", - "dev": true, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/js-sdsl" - } - }, - "node_modules/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 - }, - "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, - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/jsdom": { - "version": "20.0.3", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.3.tgz", - "integrity": "sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==", - "dev": true, - "dependencies": { - "abab": "^2.0.6", - "acorn": "^8.8.1", - "acorn-globals": "^7.0.0", - "cssom": "^0.5.0", - "cssstyle": "^2.3.0", - "data-urls": "^3.0.2", - "decimal.js": "^10.4.2", - "domexception": "^4.0.0", - "escodegen": "^2.0.0", - "form-data": "^4.0.0", - "html-encoding-sniffer": "^3.0.0", - "http-proxy-agent": "^5.0.0", - "https-proxy-agent": "^5.0.1", - "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.2", - "parse5": "^7.1.1", - "saxes": "^6.0.0", - "symbol-tree": "^3.2.4", - "tough-cookie": "^4.1.2", - "w3c-xmlserializer": "^4.0.0", - "webidl-conversions": "^7.0.0", - "whatwg-encoding": "^2.0.0", - "whatwg-mimetype": "^3.0.0", - "whatwg-url": "^11.0.0", - "ws": "^8.11.0", - "xml-name-validator": "^4.0.0" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "canvas": "^2.5.0" - }, - "peerDependenciesMeta": { - "canvas": { - "optional": true - } - } - }, - "node_modules/jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true, - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/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 - }, - "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 - }, - "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 - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "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, - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/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 - }, - "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, - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "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 - }, - "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 - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/make-dir": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", - "dev": true, - "dependencies": { - "semver": "^6.0.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/make-dir/node_modules/semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true - }, - "node_modules/makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "dev": true, - "dependencies": { - "tmpl": "1.0.5" - } - }, - "node_modules/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 - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", - "dev": true, - "dependencies": { - "braces": "^3.0.2", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "dev": true, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "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, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/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 - }, - "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 - }, - "node_modules/node-fetch": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", - "integrity": "sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg==", - "dev": true, - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/node-fetch/node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true - }, - "node_modules/node-fetch/node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true - }, - "node_modules/node-fetch/node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "dev": true, - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "node_modules/node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", - "dev": true - }, - "node_modules/node-releases": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.10.tgz", - "integrity": "sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w==", - "dev": true - }, - "node_modules/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, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/nwsapi": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.2.tgz", - "integrity": "sha512-90yv+6538zuvUMnN+zCr8LuV6bPFdq50304114vJYJ8RDyK8D5O9Phpbd6SZWgI7PwzmmfN1upeOJlvybDSgCw==", - "dev": true - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, - "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/optionator": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", - "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", - "dev": true, - "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.3" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "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, - "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, - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "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, - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/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, - "dependencies": { - "@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" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/parse5": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", - "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", - "dev": true, - "dependencies": { - "entities": "^4.4.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, - "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, - "engines": { - "node": ">=8" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "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, - "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 - }, - "node_modules/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, - "engines": { - "node": ">=8" - } - }, - "node_modules/picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", - "dev": true - }, - "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pirates": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", - "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==", - "dev": true, - "engines": { - "node": ">= 6" - } - }, - "node_modules/pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "dependencies": { - "find-up": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/pkg-dir/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "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, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/prettier": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", - "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==", - "dev": true, - "bin": { - "prettier": "bin-prettier.js" - }, - "engines": { - "node": ">=10.13.0" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/pretty-format": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.5.0.tgz", - "integrity": "sha512-V2mGkI31qdttvTFX7Mt4efOqHXqJWMu4/r66Xh3Z3BwZaPfPJgp6/gbwoujRpPUtfEF6AUUWx3Jim3GCw5g/Qw==", - "dev": true, - "dependencies": { - "@jest/schemas": "^29.4.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "dev": true, - "dependencies": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/psl": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", - "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", - "dev": true - }, - "node_modules/punycode": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", - "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/pure-rand": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.1.tgz", - "integrity": "sha512-t+x1zEHDjBwkDGY5v5ApnZ/utcd4XYDiJsaQQoptTXgUXX95sDg1elCdJghzicm7n2mbCBJ3uYWr6M22SO19rg==", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/dubzzz" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fast-check" - } - ] - }, - "node_modules/pyodide": { - "version": "0.22.1", - "resolved": "https://registry.npmjs.org/pyodide/-/pyodide-0.22.1.tgz", - "integrity": "sha512-6+PkFLTC+kcBKtFQxYBxR44J5IBxLm8UGkobLgZv1SxzV9qOU2rb0YYf0qDtlnfDiN/IQd2uckf+D8Zwe88Mqg==", - "dev": true, - "dependencies": { - "base-64": "^1.0.0", - "node-fetch": "^2.6.1", - "ws": "^8.5.0" - } - }, - "node_modules/querystringify": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", - "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", - "dev": true - }, - "node_modules/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, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", - "dev": true - }, - "node_modules/regexpp": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", - "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", - "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true - }, - "node_modules/resolve": { - "version": "1.22.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", - "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", - "dev": true, - "dependencies": { - "is-core-module": "^2.9.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", - "dev": true, - "dependencies": { - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve-cwd/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, - "engines": { - "node": ">=8" - } - }, - "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, - "engines": { - "node": ">=4" - } - }, - "node_modules/resolve.exports": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.1.tgz", - "integrity": "sha512-OEJWVeimw8mgQuj3HfkNl4KqRevH7lzeQNaWRPfx0PPse7Jk6ozcsG4FKVgtzDsC1KUF+YlTHh17NcgHOPykLw==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", - "dev": true, - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "dev": true, - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/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, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true - }, - "node_modules/saxes": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", - "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", - "dev": true, - "dependencies": { - "xmlchars": "^2.2.0" - }, - "engines": { - "node": ">=v12.22.7" - } - }, - "node_modules/semver": { - "version": "7.3.8", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", - "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/semver/node_modules/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, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/semver/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, - "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, - "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, - "engines": { - "node": ">=8" - } - }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true - }, - "node_modules/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true - }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "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, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "dev": true, - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true - }, - "node_modules/stack-utils": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, - "dependencies": { - "escape-string-regexp": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/stack-utils/node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, - "dependencies": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "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, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "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, - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "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, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/style-mod": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.0.2.tgz", - "integrity": "sha512-C4myMmRTO8iaC5Gg+N1ftK2WT4eXUTMAa+HEFPPrfVeO/NtqLTtAmV1HbqnuGtLwCek44Ra76fdGUkSqjiMPcQ==" - }, - "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, - "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, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/symbol-tree": { - "version": "3.2.4", - "dev": true, - "license": "MIT" - }, - "node_modules/synclink": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/synclink/-/synclink-0.1.1.tgz", - "integrity": "sha512-34eBqFHZn3f2PX/tz/z0E+817Um6ESFNsBkMoGqoGgBX0qlLNlRXFoHSNIUSjTK8l5Qs4gL99Xwrz0vNAUrPEw==" - }, - "node_modules/test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, - "dependencies": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true - }, - "node_modules/tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", - "dev": true - }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/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, - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/tough-cookie": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.2.tgz", - "integrity": "sha512-G9fqXWoYFZgTc2z8Q5zaHy/vJMjm+WV0AkAeHxVCQiEB1b+dGvWzFW6QV07cY5jQ5gRkeid2qIkzkxUnmoQZUQ==", - "dev": true, - "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/tr46": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", - "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", - "dev": true, - "dependencies": { - "punycode": "^2.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/ts-jest": { - "version": "29.0.3", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.0.3.tgz", - "integrity": "sha512-Ibygvmuyq1qp/z3yTh9QTwVVAbFdDy/+4BtIQR2sp6baF2SJU/8CKK/hhnGIDY2L90Az2jIqTwZPnN2p+BweiQ==", - "dev": true, - "dependencies": { - "bs-logger": "0.x", - "fast-json-stable-stringify": "2.x", - "jest-util": "^29.0.0", - "json5": "^2.2.1", - "lodash.memoize": "4.x", - "make-error": "1.x", - "semver": "7.x", - "yargs-parser": "^21.0.1" - }, - "bin": { - "ts-jest": "cli.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": ">=7.0.0-beta.0 <8", - "@jest/types": "^29.0.0", - "babel-jest": "^29.0.0", - "jest": "^29.0.0", - "typescript": ">=4.3" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "@jest/types": { - "optional": true - }, - "babel-jest": { - "optional": true - }, - "esbuild": { - "optional": true - } - } - }, - "node_modules/tslib": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==", - "dev": true - }, - "node_modules/tsutils": { - "version": "3.21.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", - "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", - "dev": true, - "dependencies": { - "tslib": "^1.8.1" - }, - "engines": { - "node": ">= 6" - }, - "peerDependencies": { - "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" - } - }, - "node_modules/tsutils/node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "dev": true - }, - "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, - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/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, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/typescript": { - "version": "4.8.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.4.tgz", - "integrity": "sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=4.2.0" - } - }, - "node_modules/universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", - "dev": true, - "engines": { - "node": ">= 4.0.0" - } - }, - "node_modules/update-browserslist-db": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", - "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - } - ], - "dependencies": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" - }, - "bin": { - "browserslist-lint": "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, - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/url-parse": { - "version": "1.5.10", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", - "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "dev": true, - "dependencies": { - "querystringify": "^2.1.1", - "requires-port": "^1.0.0" - } - }, - "node_modules/v8-to-istanbul": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.0.tgz", - "integrity": "sha512-6z3GW9x8G1gd+JIIgQQQxXuiJtCXeAjp6RaPEPLv62mH3iPHPxV6W3robxtCzNErRo6ZwTmzWhsbNvjyEBKzKA==", - "dev": true, - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.12", - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^1.6.0" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/v8-to-istanbul/node_modules/convert-source-map": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", - "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", - "dev": true - }, - "node_modules/w3c-keyname": { - "version": "2.2.6", - "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.6.tgz", - "integrity": "sha512-f+fciywl1SJEniZHD6H+kUO8gOnwIr7f4ijKA6+ZvJFjeGi1r4PDLl53Ayud9O/rk64RqgoQine0feoeOU0kXg==" - }, - "node_modules/w3c-xmlserializer": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz", - "integrity": "sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==", - "dev": true, - "dependencies": { - "xml-name-validator": "^4.0.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "dev": true, - "dependencies": { - "makeerror": "1.0.12" - } - }, - "node_modules/webidl-conversions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", - "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "node_modules/whatwg-encoding": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", - "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", - "dev": true, - "dependencies": { - "iconv-lite": "0.6.3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/whatwg-mimetype": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", - "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "node_modules/whatwg-url": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", - "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", - "dev": true, - "dependencies": { - "tr46": "^3.0.0", - "webidl-conversions": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "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, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/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, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true - }, - "node_modules/write-file-atomic": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", - "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "dev": true, - "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/ws": { - "version": "8.13.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", - "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", - "dev": true, - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/xml-name-validator": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-4.0.0.tgz", - "integrity": "sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "node_modules/xmlchars": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", - "dev": true - }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true - }, - "node_modules/yargs": { - "version": "17.7.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.1.tgz", - "integrity": "sha512-cwiTb08Xuv5fqF4AovYacTFNxk62th7LKJ6BL9IGUpTJrWoU7/7WdQGTP2SjKf1dUNBGzDd28p/Yfs/GI6JrLw==", - "dev": true, - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "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, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - } - }, - "dependencies": { - "@ampproject/remapping": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz", - "integrity": "sha512-qRmjj8nj9qmLTQXXmaR1cck3UXSRMPrbsLJAasZpF+t3riI71BXed5ebIOYwQntykeZuhjsdweEc9BxH5Jc26w==", - "dev": true, - "requires": { - "@jridgewell/gen-mapping": "^0.1.0", - "@jridgewell/trace-mapping": "^0.3.9" - } - }, - "@babel/code-frame": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", - "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", - "dev": true, - "requires": { - "@babel/highlight": "^7.18.6" - } - }, - "@babel/compat-data": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.21.0.tgz", - "integrity": "sha512-gMuZsmsgxk/ENC3O/fRw5QY8A9/uxQbbCEypnLIiYYc/qVJtEV7ouxC3EllIIwNzMqAQee5tanFabWsUOutS7g==", - "dev": true - }, - "@babel/core": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.21.3.tgz", - "integrity": "sha512-qIJONzoa/qiHghnm0l1n4i/6IIziDpzqc36FBs4pzMhDUraHqponwJLiAKm1hGLP3OSB/TVNz6rMwVGpwxxySw==", - "dev": true, - "requires": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.18.6", - "@babel/generator": "^7.21.3", - "@babel/helper-compilation-targets": "^7.20.7", - "@babel/helper-module-transforms": "^7.21.2", - "@babel/helpers": "^7.21.0", - "@babel/parser": "^7.21.3", - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.3", - "@babel/types": "^7.21.3", - "convert-source-map": "^1.7.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.2", - "semver": "^6.3.0" - }, - "dependencies": { - "convert-source-map": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", - "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", - "dev": true - }, - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, - "@babel/generator": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.21.3.tgz", - "integrity": "sha512-QS3iR1GYC/YGUnW7IdggFeN5c1poPUurnGttOV/bZgPGV+izC/D8HnD6DLwod0fsatNyVn1G3EVWMYIF0nHbeA==", - "dev": true, - "requires": { - "@babel/types": "^7.21.3", - "@jridgewell/gen-mapping": "^0.3.2", - "@jridgewell/trace-mapping": "^0.3.17", - "jsesc": "^2.5.1" - }, - "dependencies": { - "@jridgewell/gen-mapping": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz", - "integrity": "sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==", - "dev": true, - "requires": { - "@jridgewell/set-array": "^1.0.1", - "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.9" - } - } - } - }, - "@babel/helper-compilation-targets": { - "version": "7.20.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.20.7.tgz", - "integrity": "sha512-4tGORmfQcrc+bvrjb5y3dG9Mx1IOZjsHqQVUz7XCNHO+iTmqxWnVg3KRygjGmpRLJGdQSKuvFinbIb0CnZwHAQ==", - "dev": true, - "requires": { - "@babel/compat-data": "^7.20.5", - "@babel/helper-validator-option": "^7.18.6", - "browserslist": "^4.21.3", - "lru-cache": "^5.1.1", - "semver": "^6.3.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, - "@babel/helper-environment-visitor": { - "version": "7.18.9", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", - "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", - "dev": true - }, - "@babel/helper-function-name": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.21.0.tgz", - "integrity": "sha512-HfK1aMRanKHpxemaY2gqBmL04iAPOPRj7DxtNbiDOrJK+gdwkiNRVpCpUJYbUT+aZyemKN8brqTOxzCaG6ExRg==", - "dev": true, - "requires": { - "@babel/template": "^7.20.7", - "@babel/types": "^7.21.0" - } - }, - "@babel/helper-hoist-variables": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", - "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", - "dev": true, - "requires": { - "@babel/types": "^7.18.6" - } - }, - "@babel/helper-module-imports": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", - "integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", - "dev": true, - "requires": { - "@babel/types": "^7.18.6" - } - }, - "@babel/helper-module-transforms": { - "version": "7.21.2", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.21.2.tgz", - "integrity": "sha512-79yj2AR4U/Oqq/WOV7Lx6hUjau1Zfo4cI+JLAVYeMV5XIlbOhmjEk5ulbTc9fMpmlojzZHkUUxAiK+UKn+hNQQ==", - "dev": true, - "requires": { - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-module-imports": "^7.18.6", - "@babel/helper-simple-access": "^7.20.2", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/helper-validator-identifier": "^7.19.1", - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.2", - "@babel/types": "^7.21.2" - } - }, - "@babel/helper-plugin-utils": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.20.2.tgz", - "integrity": "sha512-8RvlJG2mj4huQ4pZ+rU9lqKi9ZKiRmuvGuM2HlWmkmgOhbs6zEAw6IEiJ5cQqGbDzGZOhwuOQNtZMi/ENLjZoQ==", - "dev": true - }, - "@babel/helper-simple-access": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.20.2.tgz", - "integrity": "sha512-+0woI/WPq59IrqDYbVGfshjT5Dmk/nnbdpcF8SnMhhXObpTq2KNBdLFRFrkVdbDOyUmHBCxzm5FHV1rACIkIbA==", - "dev": true, - "requires": { - "@babel/types": "^7.20.2" - } - }, - "@babel/helper-split-export-declaration": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", - "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", - "dev": true, - "requires": { - "@babel/types": "^7.18.6" - } - }, - "@babel/helper-string-parser": { - "version": "7.19.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", - "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", - "dev": true - }, - "@babel/helper-validator-identifier": { - "version": "7.19.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", - "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", - "dev": true - }, - "@babel/helper-validator-option": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.21.0.tgz", - "integrity": "sha512-rmL/B8/f0mKS2baE9ZpyTcTavvEuWhTTW8amjzXNvYG4AwBsqTLikfXsEofsJEfKHf+HQVQbFOHy6o+4cnC/fQ==", - "dev": true - }, - "@babel/helpers": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.21.0.tgz", - "integrity": "sha512-XXve0CBtOW0pd7MRzzmoyuSj0e3SEzj8pgyFxnTT1NJZL38BD1MK7yYrm8yefRPIDvNNe14xR4FdbHwpInD4rA==", - "dev": true, - "requires": { - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.0", - "@babel/types": "^7.21.0" - } - }, - "@babel/highlight": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", - "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", - "dev": true, - "requires": { - "@babel/helper-validator-identifier": "^7.18.6", - "chalk": "^2.0.0", - "js-tokens": "^4.0.0" - }, - "dependencies": { - "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" - } - }, - "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" - } - }, - "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": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "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": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true - }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true - }, - "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" - } - } - } - }, - "@babel/parser": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.21.3.tgz", - "integrity": "sha512-lobG0d7aOfQRXh8AyklEAgZGvA4FShxo6xQbUrrT/cNBPUdIDojlokwJsQyCC/eKia7ifqM0yP+2DRZ4WKw2RQ==", - "dev": true - }, - "@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.12.13" - } - }, - "@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.10.4" - } - }, - "@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-jsx": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.18.6.tgz", - "integrity": "sha512-6mmljtAedFGTWu2p/8WIORGwy+61PLgOMPOdazc7YoJ9ZCWUyFy3A6CpPkRKLKD1ToAesxX8KGEViAiLo9N+7Q==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.18.6" - } - }, - "@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.10.4" - } - }, - "@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.10.4" - } - }, - "@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.8.0" - } - }, - "@babel/plugin-syntax-top-level-await": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", - "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.14.5" - } - }, - "@babel/plugin-syntax-typescript": { - "version": "7.20.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.20.0.tgz", - "integrity": "sha512-rd9TkG+u1CExzS4SM1BlMEhMXwFLKVjOAFFCDx9PbX5ycJWDoWMcwdJH9RhkPu1dOgn5TrxLot/Gx6lWFuAUNQ==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.19.0" - } - }, - "@babel/template": { - "version": "7.20.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz", - "integrity": "sha512-8SegXApWe6VoNw0r9JHpSteLKTpTiLZ4rMlGIm9JQ18KiCtyQiAMEazujAHrUS5flrcqYZa75ukev3P6QmUwUw==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.18.6", - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7" - } - }, - "@babel/traverse": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.21.3.tgz", - "integrity": "sha512-XLyopNeaTancVitYZe2MlUEvgKb6YVVPXzofHgqHijCImG33b/uTurMS488ht/Hbsb2XK3U2BnSTxKVNGV3nGQ==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.18.6", - "@babel/generator": "^7.21.3", - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-function-name": "^7.21.0", - "@babel/helper-hoist-variables": "^7.18.6", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/parser": "^7.21.3", - "@babel/types": "^7.21.3", - "debug": "^4.1.0", - "globals": "^11.1.0" - }, - "dependencies": { - "globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true - } - } - }, - "@babel/types": { - "version": "7.21.3", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.21.3.tgz", - "integrity": "sha512-sBGdETxC+/M4o/zKC0sl6sjWv62WFR/uzxrJ6uYyMLZOUlPnwzw0tKgVHOXxaAd5l2g8pEDM5RZ495GPQI77kg==", - "dev": true, - "requires": { - "@babel/helper-string-parser": "^7.19.4", - "@babel/helper-validator-identifier": "^7.19.1", - "to-fast-properties": "^2.0.0" - } - }, - "@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", - "dev": true - }, - "@codemirror/autocomplete": { - "version": "6.4.2", - "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.4.2.tgz", - "integrity": "sha512-8WE2xp+D0MpWEv5lZ6zPW1/tf4AGb358T5GWYiKEuCP8MvFfT3tH2mIF9Y2yr2e3KbHuSvsVhosiEyqCpiJhZQ==", - "requires": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.6.0", - "@lezer/common": "^1.0.0" - } - }, - "@codemirror/commands": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.2.2.tgz", - "integrity": "sha512-s9lPVW7TxXrI/7voZ+HmD/yiAlwAYn9PH5SUVSUhsxXHhv4yl5eZ3KLntSoTynfdgVYM0oIpccQEWRBQgmNZyw==", - "requires": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.2.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.0.0" - } - }, - "@codemirror/lang-python": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.1.2.tgz", - "integrity": "sha512-nbQfifLBZstpt6Oo4XxA2LOzlSp4b/7Bc5cmodG1R+Cs5PLLCTUvsMNWDnziiCfTOG/SW1rVzXq/GbIr6WXlcw==", - "requires": { - "@codemirror/autocomplete": "^6.3.2", - "@codemirror/language": "^6.0.0", - "@lezer/python": "^1.0.0" - } - }, - "@codemirror/language": { - "version": "6.6.0", - "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.6.0.tgz", - "integrity": "sha512-cwUd6lzt3MfNYOobdjf14ZkLbJcnv4WtndYaoBkbor/vF+rCNguMPK0IRtvZJG4dsWiaWPcK8x1VijhvSxnstg==", - "requires": { - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/common": "^1.0.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0", - "style-mod": "^4.0.0" - } - }, - "@codemirror/lint": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.2.0.tgz", - "integrity": "sha512-KVCECmR2fFeYBr1ZXDVue7x3q5PMI0PzcIbA+zKufnkniMBo1325t0h1jM85AKp8l3tj67LRxVpZfgDxEXlQkg==", - "requires": { - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "crelt": "^1.0.5" - } - }, - "@codemirror/search": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.3.0.tgz", - "integrity": "sha512-rBhZxzT34CarfhgCZGhaLBScABDN3iqJxixzNuINp9lrb3lzm0nTpR77G1VrxGO3HOGK7j62jcJftQM7eCOIuw==", - "requires": { - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "crelt": "^1.0.5" - } - }, - "@codemirror/state": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.2.0.tgz", - "integrity": "sha512-69QXtcrsc3RYtOtd+GsvczJ319udtBf1PTrr2KbLWM/e2CXUPnh0Nz9AUo8WfhSQ7GeL8dPVNUmhQVgpmuaNGA==" - }, - "@codemirror/theme-one-dark": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.1.tgz", - "integrity": "sha512-+CfzmScfJuD6uDF5bHJkAjWTQ2QAAHxODCPxUEgcImDYcJLT+4l5vLnBHmDVv46kCC5uUJGMrBJct2Z6JbvqyQ==", - "requires": { - "@codemirror/language": "^6.0.0", - "@codemirror/state": "^6.0.0", - "@codemirror/view": "^6.0.0", - "@lezer/highlight": "^1.0.0" - } - }, - "@codemirror/view": { - "version": "6.9.3", - "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.9.3.tgz", - "integrity": "sha512-BJ5mvEIhFM+SrNwc5X8pLIvMM9ffjkviVbxpg84Xk2OE8ZyKaEbId8kX+nAYEEso7+qnbwsXe1bkAHsasebMow==", - "requires": { - "@codemirror/state": "^6.1.4", - "style-mod": "^4.0.0", - "w3c-keyname": "^2.2.4" - } - }, - "@esbuild/android-arm": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.12.tgz", - "integrity": "sha512-E/sgkvwoIfj4aMAPL2e35VnUJspzVYl7+M1B2cqeubdBhADV4uPon0KCc8p2G+LqSJ6i8ocYPCqY3A4GGq0zkQ==", - "dev": true, - "optional": true - }, - "@esbuild/android-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.12.tgz", - "integrity": "sha512-WQ9p5oiXXYJ33F2EkE3r0FRDFVpEdcDiwNX3u7Xaibxfx6vQE0Sb8ytrfQsA5WO6kDn6mDfKLh6KrPBjvkk7xA==", - "dev": true, - "optional": true - }, - "@esbuild/android-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.12.tgz", - "integrity": "sha512-m4OsaCr5gT+se25rFPHKQXARMyAehHTQAz4XX1Vk3d27VtqiX0ALMBPoXZsGaB6JYryCLfgGwUslMqTfqeLU0w==", - "dev": true, - "optional": true - }, - "@esbuild/darwin-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.12.tgz", - "integrity": "sha512-O3GCZghRIx+RAN0NDPhyyhRgwa19MoKlzGonIb5hgTj78krqp9XZbYCvFr9N1eUxg0ZQEpiiZ4QvsOQwBpP+lg==", - "dev": true, - "optional": true - }, - "@esbuild/darwin-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.12.tgz", - "integrity": "sha512-5D48jM3tW27h1qjaD9UNRuN+4v0zvksqZSPZqeSWggfMlsVdAhH3pwSfQIFJwcs9QJ9BRibPS4ViZgs3d2wsCA==", - "dev": true, - "optional": true - }, - "@esbuild/freebsd-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.12.tgz", - "integrity": "sha512-OWvHzmLNTdF1erSvrfoEBGlN94IE6vCEaGEkEH29uo/VoONqPnoDFfShi41Ew+yKimx4vrmmAJEGNoyyP+OgOQ==", - "dev": true, - "optional": true - }, - "@esbuild/freebsd-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.12.tgz", - "integrity": "sha512-A0Xg5CZv8MU9xh4a+7NUpi5VHBKh1RaGJKqjxe4KG87X+mTjDE6ZvlJqpWoeJxgfXHT7IMP9tDFu7IZ03OtJAw==", - "dev": true, - "optional": true - }, - "@esbuild/linux-arm": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.12.tgz", - "integrity": "sha512-WsHyJ7b7vzHdJ1fv67Yf++2dz3D726oO3QCu8iNYik4fb5YuuReOI9OtA+n7Mk0xyQivNTPbl181s+5oZ38gyA==", - "dev": true, - "optional": true - }, - "@esbuild/linux-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.12.tgz", - "integrity": "sha512-cK3AjkEc+8v8YG02hYLQIQlOznW+v9N+OI9BAFuyqkfQFR+DnDLhEM5N8QRxAUz99cJTo1rLNXqRrvY15gbQUg==", - "dev": true, - "optional": true - }, - "@esbuild/linux-ia32": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.12.tgz", - "integrity": "sha512-jdOBXJqcgHlah/nYHnj3Hrnl9l63RjtQ4vn9+bohjQPI2QafASB5MtHAoEv0JQHVb/xYQTFOeuHnNYE1zF7tYw==", - "dev": true, - "optional": true - }, - "@esbuild/linux-loong64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.12.tgz", - "integrity": "sha512-GTOEtj8h9qPKXCyiBBnHconSCV9LwFyx/gv3Phw0pa25qPYjVuuGZ4Dk14bGCfGX3qKF0+ceeQvwmtI+aYBbVA==", - "dev": true, - "optional": true - }, - "@esbuild/linux-mips64el": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.12.tgz", - "integrity": "sha512-o8CIhfBwKcxmEENOH9RwmUejs5jFiNoDw7YgS0EJTF6kgPgcqLFjgoc5kDey5cMHRVCIWc6kK2ShUePOcc7RbA==", - "dev": true, - "optional": true - }, - "@esbuild/linux-ppc64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.12.tgz", - "integrity": "sha512-biMLH6NR/GR4z+ap0oJYb877LdBpGac8KfZoEnDiBKd7MD/xt8eaw1SFfYRUeMVx519kVkAOL2GExdFmYnZx3A==", - "dev": true, - "optional": true - }, - "@esbuild/linux-riscv64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.12.tgz", - "integrity": "sha512-jkphYUiO38wZGeWlfIBMB72auOllNA2sLfiZPGDtOBb1ELN8lmqBrlMiucgL8awBw1zBXN69PmZM6g4yTX84TA==", - "dev": true, - "optional": true - }, - "@esbuild/linux-s390x": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.12.tgz", - "integrity": "sha512-j3ucLdeY9HBcvODhCY4b+Ds3hWGO8t+SAidtmWu/ukfLLG/oYDMaA+dnugTVAg5fnUOGNbIYL9TOjhWgQB8W5g==", - "dev": true, - "optional": true - }, - "@esbuild/linux-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.12.tgz", - "integrity": "sha512-uo5JL3cgaEGotaqSaJdRfFNSCUJOIliKLnDGWaVCgIKkHxwhYMm95pfMbWZ9l7GeW9kDg0tSxcy9NYdEtjwwmA==", - "dev": true, - "optional": true - }, - "@esbuild/netbsd-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.12.tgz", - "integrity": "sha512-DNdoRg8JX+gGsbqt2gPgkgb00mqOgOO27KnrWZtdABl6yWTST30aibGJ6geBq3WM2TIeW6COs5AScnC7GwtGPg==", - "dev": true, - "optional": true - }, - "@esbuild/openbsd-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.12.tgz", - "integrity": "sha512-aVsENlr7B64w8I1lhHShND5o8cW6sB9n9MUtLumFlPhG3elhNWtE7M1TFpj3m7lT3sKQUMkGFjTQBrvDDO1YWA==", - "dev": true, - "optional": true - }, - "@esbuild/sunos-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.12.tgz", - "integrity": "sha512-qbHGVQdKSwi0JQJuZznS4SyY27tYXYF0mrgthbxXrZI3AHKuRvU+Eqbg/F0rmLDpW/jkIZBlCO1XfHUBMNJ1pg==", - "dev": true, - "optional": true - }, - "@esbuild/win32-arm64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.12.tgz", - "integrity": "sha512-zsCp8Ql+96xXTVTmm6ffvoTSZSV2B/LzzkUXAY33F/76EajNw1m+jZ9zPfNJlJ3Rh4EzOszNDHsmG/fZOhtqDg==", - "dev": true, - "optional": true - }, - "@esbuild/win32-ia32": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.12.tgz", - "integrity": "sha512-FfrFjR4id7wcFYOdqbDfDET3tjxCozUgbqdkOABsSFzoZGFC92UK7mg4JKRc/B3NNEf1s2WHxJ7VfTdVDPN3ng==", - "dev": true, - "optional": true - }, - "@esbuild/win32-x64": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.12.tgz", - "integrity": "sha512-JOOxw49BVZx2/5tW3FqkdjSD/5gXYeVGPDcB0lvap0gLQshkh1Nyel1QazC+wNxus3xPlsYAgqU1BUmrmCvWtw==", - "dev": true, - "optional": true - }, - "@eslint/eslintrc": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.4.1.tgz", - "integrity": "sha512-XXrH9Uarn0stsyldqDYq8r++mROmWRI1xKMXa640Bb//SY1+ECYX6VzT6Lcx5frD0V30XieqJ0oX9I2Xj5aoMA==", - "dev": true, - "requires": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.4.0", - "globals": "^13.19.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" - } - }, - "@hoodmane/toml-j0.4": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@hoodmane/toml-j0.4/-/toml-j0.4-1.1.2.tgz", - "integrity": "sha512-vQvFpjssFt39GcYwsFLDts6eReKSWeDwFt3AufXnM62ACIG2MgvOVomNRo4kQUYV0G3+zpu4LezUWw5JCFgF0Q==" - }, - "@humanwhocodes/config-array": { - "version": "0.10.7", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.10.7.tgz", - "integrity": "sha512-MDl6D6sBsaV452/QSdX+4CXIjZhIcI0PELsxUjk4U828yd58vk3bTIvk/6w5FY+4hIy9sLW0sfrV7K7Kc++j/w==", - "dev": true, - "requires": { - "@humanwhocodes/object-schema": "^1.2.1", - "debug": "^4.1.1", - "minimatch": "^3.0.4" - } - }, - "@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 - }, - "@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 - }, - "@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, - "requires": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "dependencies": { - "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "requires": { - "sprintf-js": "~1.0.2" - } - }, - "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "requires": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - } - }, - "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, - "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - } - }, - "locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "requires": { - "p-locate": "^4.1.0" - } - }, - "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "requires": { - "p-limit": "^2.2.0" - } - }, - "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 - } - } - }, - "@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", - "dev": true - }, - "@jest/console": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.5.0.tgz", - "integrity": "sha512-NEpkObxPwyw/XxZVLPmAGKE89IQRp4puc6IQRPru6JKd1M3fW9v1xM1AnzIJE65hbCkzQAdnL8P47e9hzhiYLQ==", - "dev": true, - "requires": { - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^29.5.0", - "jest-util": "^29.5.0", - "slash": "^3.0.0" - } - }, - "@jest/core": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.5.0.tgz", - "integrity": "sha512-28UzQc7ulUrOQw1IsN/kv1QES3q2kkbl/wGslyhAclqZ/8cMdB5M68BffkIdSJgKBUt50d3hbwJ92XESlE7LiQ==", - "dev": true, - "requires": { - "@jest/console": "^29.5.0", - "@jest/reporters": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^29.5.0", - "jest-config": "^29.5.0", - "jest-haste-map": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-regex-util": "^29.4.3", - "jest-resolve": "^29.5.0", - "jest-resolve-dependencies": "^29.5.0", - "jest-runner": "^29.5.0", - "jest-runtime": "^29.5.0", - "jest-snapshot": "^29.5.0", - "jest-util": "^29.5.0", - "jest-validate": "^29.5.0", - "jest-watcher": "^29.5.0", - "micromatch": "^4.0.4", - "pretty-format": "^29.5.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" - } - }, - "@jest/environment": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.5.0.tgz", - "integrity": "sha512-5FXw2+wD29YU1d4I2htpRX7jYnAyTRjP2CsXQdo9SAM8g3ifxWPSV0HnClSn71xwctr0U3oZIIH+dtbfmnbXVQ==", - "dev": true, - "requires": { - "@jest/fake-timers": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "jest-mock": "^29.5.0" - } - }, - "@jest/expect": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.5.0.tgz", - "integrity": "sha512-PueDR2HGihN3ciUNGr4uelropW7rqUfTiOn+8u0leg/42UhblPxHkfoh0Ruu3I9Y1962P3u2DY4+h7GVTSVU6g==", - "dev": true, - "requires": { - "expect": "^29.5.0", - "jest-snapshot": "^29.5.0" - } - }, - "@jest/expect-utils": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.5.0.tgz", - "integrity": "sha512-fmKzsidoXQT2KwnrwE0SQq3uj8Z763vzR8LnLBwC2qYWEFpjX8daRsk6rHUM1QvNlEW/UJXNXm59ztmJJWs2Mg==", - "dev": true, - "requires": { - "jest-get-type": "^29.4.3" - } - }, - "@jest/fake-timers": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.5.0.tgz", - "integrity": "sha512-9ARvuAAQcBwDAqOnglWq2zwNIRUDtk/SCkp/ToGEhFv5r86K21l+VEs0qNTaXtyiY0lEePl3kylijSYJQqdbDg==", - "dev": true, - "requires": { - "@jest/types": "^29.5.0", - "@sinonjs/fake-timers": "^10.0.2", - "@types/node": "*", - "jest-message-util": "^29.5.0", - "jest-mock": "^29.5.0", - "jest-util": "^29.5.0" - } - }, - "@jest/globals": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.1.2.tgz", - "integrity": "sha512-uMgfERpJYoQmykAd0ffyMq8wignN4SvLUG6orJQRe9WAlTRc9cdpCaE/29qurXixYJVZWUqIBXhSk8v5xN1V9g==", - "dev": true, - "requires": { - "@jest/environment": "^29.1.2", - "@jest/expect": "^29.1.2", - "@jest/types": "^29.1.2", - "jest-mock": "^29.1.2" - } - }, - "@jest/reporters": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.5.0.tgz", - "integrity": "sha512-D05STXqj/M8bP9hQNSICtPqz97u7ffGzZu+9XLucXhkOFBqKcXe04JLZOgIekOxdb73MAoBUFnqvf7MCpKk5OA==", - "dev": true, - "requires": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@jridgewell/trace-mapping": "^0.3.15", - "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^5.1.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "^29.5.0", - "jest-util": "^29.5.0", - "jest-worker": "^29.5.0", - "slash": "^3.0.0", - "string-length": "^4.0.1", - "strip-ansi": "^6.0.0", - "v8-to-istanbul": "^9.0.1" - } - }, - "@jest/schemas": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.4.3.tgz", - "integrity": "sha512-VLYKXQmtmuEz6IxJsrZwzG9NvtkQsWNnWMsKxqWNu3+CnfzJQhp0WDDKWLVV9hLKr0l3SLLFRqcYHjhtyuDVxg==", - "dev": true, - "requires": { - "@sinclair/typebox": "^0.25.16" - } - }, - "@jest/source-map": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.4.3.tgz", - "integrity": "sha512-qyt/mb6rLyd9j1jUts4EQncvS6Yy3PM9HghnNv86QBlV+zdL2inCdK1tuVlL+J+lpiw2BI67qXOrX3UurBqQ1w==", - "dev": true, - "requires": { - "@jridgewell/trace-mapping": "^0.3.15", - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9" - } - }, - "@jest/test-result": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.5.0.tgz", - "integrity": "sha512-fGl4rfitnbfLsrfx1uUpDEESS7zM8JdgZgOCQuxQvL1Sn/I6ijeAVQWGfXI9zb1i9Mzo495cIpVZhA0yr60PkQ==", - "dev": true, - "requires": { - "@jest/console": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" - } - }, - "@jest/test-sequencer": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.5.0.tgz", - "integrity": "sha512-yPafQEcKjkSfDXyvtgiV4pevSeyuA6MQr6ZIdVkWJly9vkqjnFfcfhRQqpD5whjoU8EORki752xQmjaqoFjzMQ==", - "dev": true, - "requires": { - "@jest/test-result": "^29.5.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.5.0", - "slash": "^3.0.0" - } - }, - "@jest/transform": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.5.0.tgz", - "integrity": "sha512-8vbeZWqLJOvHaDfeMuoHITGKSz5qWc9u04lnWrQE3VyuSw604PzQM824ZeX9XSjUCeDiE3GuxZe5UKa8J61NQw==", - "dev": true, - "requires": { - "@babel/core": "^7.11.6", - "@jest/types": "^29.5.0", - "@jridgewell/trace-mapping": "^0.3.15", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.5.0", - "jest-regex-util": "^29.4.3", - "jest-util": "^29.5.0", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", - "slash": "^3.0.0", - "write-file-atomic": "^4.0.2" - } - }, - "@jest/types": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.5.0.tgz", - "integrity": "sha512-qbu7kN6czmVRc3xWFQcAN03RAUamgppVUdXrvl1Wr3jlNF93o9mJbGcDWrwGB6ht44u7efB1qCFgVQmca24Uog==", - "dev": true, - "requires": { - "@jest/schemas": "^29.4.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" - } - }, - "@jridgewell/gen-mapping": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz", - "integrity": "sha512-sQXCasFk+U8lWYEe66WxRDOE9PjVz4vSM51fTu3Hw+ClTpUSQb718772vH3pyS5pShp6lvQM7SxgIDXXXmOX7w==", - "dev": true, - "requires": { - "@jridgewell/set-array": "^1.0.0", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, - "@jridgewell/resolve-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", - "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", - "dev": true - }, - "@jridgewell/set-array": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", - "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", - "dev": true - }, - "@jridgewell/sourcemap-codec": { - "version": "1.4.14", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", - "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", - "dev": true - }, - "@jridgewell/trace-mapping": { - "version": "0.3.17", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.17.tgz", - "integrity": "sha512-MCNzAp77qzKca9+W/+I0+sEpaUnZoeasnghNeVc41VZCEKaCH73Vq3BZZ/SzWIgrqE4H4ceI+p+b6C0mHf9T4g==", - "dev": true, - "requires": { - "@jridgewell/resolve-uri": "3.1.0", - "@jridgewell/sourcemap-codec": "1.4.14" - } - }, - "@lezer/common": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.0.2.tgz", - "integrity": "sha512-SVgiGtMnMnW3ActR8SXgsDhw7a0w0ChHSYAyAUxxrOiJ1OqYWEKk/xJd84tTSPo1mo6DXLObAJALNnd0Hrv7Ng==" - }, - "@lezer/highlight": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.1.3.tgz", - "integrity": "sha512-3vLKLPThO4td43lYRBygmMY18JN3CPh9w+XS2j8WC30vR4yZeFG4z1iFe4jXE43NtGqe//zHW5q8ENLlHvz9gw==", - "requires": { - "@lezer/common": "^1.0.0" - } - }, - "@lezer/lr": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.3.3.tgz", - "integrity": "sha512-JPQe3mwJlzEVqy67iQiiGozhcngbO8QBgpqZM6oL1Wj/dXckrEexpBLeFkq0edtW5IqnPRFxA24BHJni8Js69w==", - "requires": { - "@lezer/common": "^1.0.0" - } - }, - "@lezer/python": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.3.tgz", - "integrity": "sha512-rUdt5/H8JjVY3YIROZF2ZNUMx7eYB7h0cmC8c4TfkgJt4xcn6vLpjCOCk1usP4vV3YfMC+VDB786dKjJ6tL5Hw==", - "requires": { - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.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" - } - }, - "@sinclair/typebox": { - "version": "0.25.24", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.25.24.tgz", - "integrity": "sha512-XJfwUVUKDHF5ugKwIcxEgc9k8b7HbznCp6eUfWgu710hMPNIO4aw4/zB5RogDQz8nd6gyCDpU9O/m6qYEWY6yQ==", - "dev": true - }, - "@sinonjs/commons": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-2.0.0.tgz", - "integrity": "sha512-uLa0j859mMrg2slwQYdO/AkrOfmH+X6LTVmNTS9CqexuE2IvVORIkSpJLqePAbEnKJ77aMmCwr1NUZ57120Xcg==", - "dev": true, - "requires": { - "type-detect": "4.0.8" - } - }, - "@sinonjs/fake-timers": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.0.2.tgz", - "integrity": "sha512-SwUDyjWnah1AaNl7kxsa7cfLhlTYoiyhDAIgyh+El30YvXs/o7OLXpYH88Zdhyx9JExKrmHDJ+10bwIcY80Jmw==", - "dev": true, - "requires": { - "@sinonjs/commons": "^2.0.0" - } - }, - "@tootallnate/once": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", - "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", - "dev": true - }, - "@types/babel__core": { - "version": "7.20.0", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.0.tgz", - "integrity": "sha512-+n8dL/9GWblDO0iU6eZAwEIJVr5DWigtle+Q6HLOrh/pdbXOhOtqzq8VPPE2zvNJzSKY4vH/z3iT3tn0A3ypiQ==", - "dev": true, - "requires": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "@types/babel__generator": { - "version": "7.6.4", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", - "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", - "dev": true, - "requires": { - "@babel/types": "^7.0.0" - } - }, - "@types/babel__template": { - "version": "7.4.1", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", - "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", - "dev": true, - "requires": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "@types/babel__traverse": { - "version": "7.18.3", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.18.3.tgz", - "integrity": "sha512-1kbcJ40lLB7MHsj39U4Sh1uTd2E7rLEa79kmDpI6cy+XiXsteB3POdQomoq4FxszMrO3ZYchkhYJw7A2862b3w==", - "dev": true, - "requires": { - "@babel/types": "^7.3.0" - } - }, - "@types/codemirror": { - "version": "5.60.7", - "resolved": "https://registry.npmjs.org/@types/codemirror/-/codemirror-5.60.7.tgz", - "integrity": "sha512-QXIC+RPzt/1BGSuD6iFn6UMC9TDp+9hkOANYNPVsjjrDdzKphfRkwQDKGp2YaC54Yhz0g6P5uYTCCibZZEiMAA==", - "dev": true, - "requires": { - "@types/tern": "*" - } - }, - "@types/estree": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.0.tgz", - "integrity": "sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ==", - "dev": true - }, - "@types/graceful-fs": { - "version": "4.1.6", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.6.tgz", - "integrity": "sha512-Sig0SNORX9fdW+bQuTEovKj3uHcUL6LQKbCrrqb1X7J6/ReAbhCXRAhc+SMejhLELFj2QcyuxmUooZ4bt5ReSw==", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "@types/istanbul-lib-coverage": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", - "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", - "dev": true - }, - "@types/istanbul-lib-report": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", - "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", - "dev": true, - "requires": { - "@types/istanbul-lib-coverage": "*" - } - }, - "@types/istanbul-reports": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", - "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", - "dev": true, - "requires": { - "@types/istanbul-lib-report": "*" - } - }, - "@types/jest": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.1.2.tgz", - "integrity": "sha512-y+nlX0h87U0R+wsGn6EBuoRWYyv3KFtwRNP3QWp9+k2tJ2/bqcGS3UxD7jgT+tiwJWWq3UsyV4Y+T6rsMT4XMg==", - "dev": true, - "requires": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" - } - }, - "@types/jsdom": { - "version": "20.0.1", - "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-20.0.1.tgz", - "integrity": "sha512-d0r18sZPmMQr1eG35u12FZfhIXNrnsPU/g5wvRKCUf/tOGilKKwYMYGqh33BNR6ba+2gkHw1EUiHoN3mn7E5IQ==", - "dev": true, - "requires": { - "@types/node": "*", - "@types/tough-cookie": "*", - "parse5": "^7.0.0" - } - }, - "@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": "18.8.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.8.3.tgz", - "integrity": "sha512-0os9vz6BpGwxGe9LOhgP/ncvYN5Tx1fNcd2TM3rD/aCGBkysb+ZWpXEocG24h6ZzOi13+VB8HndAQFezsSOw1w==", - "dev": true - }, - "@types/prettier": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.2.tgz", - "integrity": "sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg==", - "dev": true - }, - "@types/stack-utils": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", - "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", - "dev": true - }, - "@types/tern": { - "version": "0.23.4", - "resolved": "https://registry.npmjs.org/@types/tern/-/tern-0.23.4.tgz", - "integrity": "sha512-JAUw1iXGO1qaWwEOzxTKJZ/5JxVeON9kvGZ/osgZaJImBnyjyn0cjovPsf6FNLmyGY8Vw9DoXZCMlfMkMwHRWg==", - "dev": true, - "requires": { - "@types/estree": "*" - } - }, - "@types/tough-cookie": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.2.tgz", - "integrity": "sha512-Q5vtl1W5ue16D+nIaW8JWebSSraJVlK+EthKn7e7UcD4KWsaSJ8BqGPXNaPghgtcn/fhvrN17Tv8ksUsQpiplw==", - "dev": true - }, - "@types/yargs": { - "version": "17.0.23", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.23.tgz", - "integrity": "sha512-yuogunc04OnzGQCrfHx+Kk883Q4X0aSwmYZhKjI21m+SVYzjIbrWl8dOOwSv5hf2Um2pdCOXWo9isteZTNXUZQ==", - "dev": true, - "requires": { - "@types/yargs-parser": "*" - } - }, - "@types/yargs-parser": { - "version": "21.0.0", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", - "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==", - "dev": true - }, - "@typescript-eslint/eslint-plugin": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.39.0.tgz", - "integrity": "sha512-xVfKOkBm5iWMNGKQ2fwX5GVgBuHmZBO1tCRwXmY5oAIsPscfwm2UADDuNB8ZVYCtpQvJK4xpjrK7jEhcJ0zY9A==", - "dev": true, - "requires": { - "@typescript-eslint/scope-manager": "5.39.0", - "@typescript-eslint/type-utils": "5.39.0", - "@typescript-eslint/utils": "5.39.0", - "debug": "^4.3.4", - "ignore": "^5.2.0", - "regexpp": "^3.2.0", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/parser": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.39.0.tgz", - "integrity": "sha512-PhxLjrZnHShe431sBAGHaNe6BDdxAASDySgsBCGxcBecVCi8NQWxQZMcizNA4g0pN51bBAn/FUfkWG3SDVcGlA==", - "dev": true, - "requires": { - "@typescript-eslint/scope-manager": "5.39.0", - "@typescript-eslint/types": "5.39.0", - "@typescript-eslint/typescript-estree": "5.39.0", - "debug": "^4.3.4" - } - }, - "@typescript-eslint/scope-manager": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.39.0.tgz", - "integrity": "sha512-/I13vAqmG3dyqMVSZPjsbuNQlYS082Y7OMkwhCfLXYsmlI0ca4nkL7wJ/4gjX70LD4P8Hnw1JywUVVAwepURBw==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.39.0", - "@typescript-eslint/visitor-keys": "5.39.0" - } - }, - "@typescript-eslint/type-utils": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.39.0.tgz", - "integrity": "sha512-KJHJkOothljQWzR3t/GunL0TPKY+fGJtnpl+pX+sJ0YiKTz3q2Zr87SGTmFqsCMFrLt5E0+o+S6eQY0FAXj9uA==", - "dev": true, - "requires": { - "@typescript-eslint/typescript-estree": "5.39.0", - "@typescript-eslint/utils": "5.39.0", - "debug": "^4.3.4", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/types": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.39.0.tgz", - "integrity": "sha512-gQMZrnfEBFXK38hYqt8Lkwt8f4U6yq+2H5VDSgP/qiTzC8Nw8JO3OuSUOQ2qW37S/dlwdkHDntkZM6SQhKyPhw==", - "dev": true - }, - "@typescript-eslint/typescript-estree": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.39.0.tgz", - "integrity": "sha512-qLFQP0f398sdnogJoLtd43pUgB18Q50QSA+BTE5h3sUxySzbWDpTSdgt4UyxNSozY/oDK2ta6HVAzvGgq8JYnA==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.39.0", - "@typescript-eslint/visitor-keys": "5.39.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - } - }, - "@typescript-eslint/utils": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.39.0.tgz", - "integrity": "sha512-+DnY5jkpOpgj+EBtYPyHRjXampJfC0yUZZzfzLuUWVZvCuKqSdJVC8UhdWipIw7VKNTfwfAPiOWzYkAwuIhiAg==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.9", - "@typescript-eslint/scope-manager": "5.39.0", - "@typescript-eslint/types": "5.39.0", - "@typescript-eslint/typescript-estree": "5.39.0", - "eslint-scope": "^5.1.1", - "eslint-utils": "^3.0.0" - } - }, - "@typescript-eslint/visitor-keys": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.39.0.tgz", - "integrity": "sha512-yyE3RPwOG+XJBLrhvsxAidUgybJVQ/hG8BhiJo0k8JSAYfk/CshVcxf0HwP4Jt7WZZ6vLmxdo1p6EyN3tzFTkg==", - "dev": true, - "requires": { - "@typescript-eslint/types": "5.39.0", - "eslint-visitor-keys": "^3.3.0" - } - }, - "abab": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", - "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", - "dev": true - }, - "acorn": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", - "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", - "dev": true - }, - "acorn-globals": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-7.0.1.tgz", - "integrity": "sha512-umOSDSDrfHbTNPuNpC2NSnnA3LUrqpevPb4T9jRx4MagXNS0rs+gwiTcAvqCRmsD6utzsrzNt+ebm00SNWiC3Q==", - "dev": true, - "requires": { - "acorn": "^8.1.0", - "acorn-walk": "^8.0.2" - } - }, - "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, - "requires": {} - }, - "acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", - "dev": true - }, - "agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "dev": true, - "requires": { - "debug": "4" - } - }, - "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-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "dev": true, - "requires": { - "type-fest": "^0.21.3" - }, - "dependencies": { - "type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true - } - } - }, - "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": "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" - } - }, - "anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "requires": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - } - }, - "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 - }, - "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 - }, - "asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true - }, - "babel-jest": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.5.0.tgz", - "integrity": "sha512-mA4eCDh5mSo2EcA9xQjVTpmbbNk32Zb3Q3QFQsNhaK56Q+yoXowzFodLux30HRgyOho5rsQ6B0P9QpMkvvnJ0Q==", - "dev": true, - "requires": { - "@jest/transform": "^29.5.0", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^29.5.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "slash": "^3.0.0" - } - }, - "babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "dev": true, - "requires": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" - } - }, - "babel-plugin-jest-hoist": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.5.0.tgz", - "integrity": "sha512-zSuuuAlTMT4mzLj2nPnUm6fsE6270vdOfnpbJ+RmruU75UhLFvL0N2NgI7xpeS7NaB6hGqmd5pVpGTDYvi4Q3w==", - "dev": true, - "requires": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.1.14", - "@types/babel__traverse": "^7.0.6" - } - }, - "babel-preset-current-node-syntax": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", - "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", - "dev": true, - "requires": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.8.3", - "@babel/plugin-syntax-import-meta": "^7.8.3", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.8.3", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-top-level-await": "^7.8.3" - } - }, - "babel-preset-jest": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.5.0.tgz", - "integrity": "sha512-JOMloxOqdiBSxMAzjRaH023/vvcaSaec49zvg+2LmNsktC7ei39LTJGw02J+9uUtTZUq6xbLyJ4dxe9sSmIuAg==", - "dev": true, - "requires": { - "babel-plugin-jest-hoist": "^29.5.0", - "babel-preset-current-node-syntax": "^1.0.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 - }, - "base-64": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/base-64/-/base-64-1.0.0.tgz", - "integrity": "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==", - "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.21.5", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.5.tgz", - "integrity": "sha512-tUkiguQGW7S3IhB7N+c2MV/HZPSCPAAiYBZXLsBhFB/PCy6ZKKsZrmBayHV9fdGV/ARIfJ14NkxKzRDjvp7L6w==", - "dev": true, - "requires": { - "caniuse-lite": "^1.0.30001449", - "electron-to-chromium": "^1.4.284", - "node-releases": "^2.0.8", - "update-browserslist-db": "^1.0.10" - } - }, - "bs-logger": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", - "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", - "dev": true, - "requires": { - "fast-json-stable-stringify": "2.x" - } - }, - "bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", - "dev": true, - "requires": { - "node-int64": "^0.4.0" - } - }, - "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 - }, - "callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true - }, - "camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true - }, - "caniuse-lite": { - "version": "1.0.30001469", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001469.tgz", - "integrity": "sha512-Rcp7221ScNqQPP3W+lVOYDyjdR6dC+neEQCttoNr5bAyz54AboB4iwpnWgyi8P4YUsPybVzT4LgWiBbI3drL4g==", - "dev": true - }, - "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" - } - }, - "char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true - }, - "ci-info": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.8.0.tgz", - "integrity": "sha512-eXTggHWSooYhq49F2opQhuHWgzucfF2YgODK4e1566GQs5BIfP30B0oenwBJHfWxAs2fyPB1s7Mg949zLf61Yw==", - "dev": true - }, - "cjs-module-lexer": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz", - "integrity": "sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==", - "dev": true - }, - "cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, - "requires": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - } - }, - "co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "dev": true - }, - "codemirror": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.1.tgz", - "integrity": "sha512-J8j+nZ+CdWmIeFIGXEFbFPtpiYacFMDR8GlHK3IyHQJMCaVRfGx9NT+Hxivv1ckLWPvNdZqndbr/7lVhrf/Svg==", - "requires": { - "@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" - } - }, - "collect-v8-coverage": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", - "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==", - "dev": true - }, - "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 - }, - "combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "requires": { - "delayed-stream": "~1.0.0" - } - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true - }, - "convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "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-env": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", - "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", - "dev": true, - "requires": { - "cross-spawn": "^7.0.1" - } - }, - "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" - } - }, - "cssom": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", - "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", - "dev": true - }, - "cssstyle": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", - "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", - "dev": true, - "requires": { - "cssom": "~0.3.6" - }, - "dependencies": { - "cssom": { - "version": "0.3.8", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", - "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", - "dev": true - } - } - }, - "data-urls": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-3.0.2.tgz", - "integrity": "sha512-Jy/tj3ldjZJo63sVAvg6LHt2mHvl4V6AgRAmNDtLdm7faqtsx+aJG42rsyCo9JCoRVKwPFzKlIPx3DIibwSIaQ==", - "dev": true, - "requires": { - "abab": "^2.0.6", - "whatwg-mimetype": "^3.0.0", - "whatwg-url": "^11.0.0" - } - }, - "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" - } - }, - "decimal.js": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz", - "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==", - "dev": true - }, - "dedent": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", - "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==", - "dev": true - }, - "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.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 - }, - "delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true - }, - "detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "dev": true - }, - "diff-sequences": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.4.3.tgz", - "integrity": "sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==", - "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" - } - }, - "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" - } - }, - "domexception": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz", - "integrity": "sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==", - "dev": true, - "requires": { - "webidl-conversions": "^7.0.0" - } - }, - "electron-to-chromium": { - "version": "1.4.334", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.334.tgz", - "integrity": "sha512-laZ1odk+TRen6q0GeyQx/JEkpD3iSZT7ewopCpKqg9bTjP1l8XRfU3Bg20CFjNPZkp5+NDBl3iqd4o/kPO+Vew==", - "dev": true - }, - "emittery": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", - "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true - }, - "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 - }, - "entities": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.4.0.tgz", - "integrity": "sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==", - "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" - } - }, - "esbuild": { - "version": "0.17.12", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.12.tgz", - "integrity": "sha512-bX/zHl7Gn2CpQwcMtRogTTBf9l1nl+H6R8nUbjk+RuKqAE3+8FDulLA+pHvX7aA7Xe07Iwa+CWvy9I8Y2qqPKQ==", - "dev": true, - "requires": { - "@esbuild/android-arm": "0.17.12", - "@esbuild/android-arm64": "0.17.12", - "@esbuild/android-x64": "0.17.12", - "@esbuild/darwin-arm64": "0.17.12", - "@esbuild/darwin-x64": "0.17.12", - "@esbuild/freebsd-arm64": "0.17.12", - "@esbuild/freebsd-x64": "0.17.12", - "@esbuild/linux-arm": "0.17.12", - "@esbuild/linux-arm64": "0.17.12", - "@esbuild/linux-ia32": "0.17.12", - "@esbuild/linux-loong64": "0.17.12", - "@esbuild/linux-mips64el": "0.17.12", - "@esbuild/linux-ppc64": "0.17.12", - "@esbuild/linux-riscv64": "0.17.12", - "@esbuild/linux-s390x": "0.17.12", - "@esbuild/linux-x64": "0.17.12", - "@esbuild/netbsd-x64": "0.17.12", - "@esbuild/openbsd-x64": "0.17.12", - "@esbuild/sunos-x64": "0.17.12", - "@esbuild/win32-arm64": "0.17.12", - "@esbuild/win32-ia32": "0.17.12", - "@esbuild/win32-x64": "0.17.12" - } - }, - "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": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true - }, - "escodegen": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.0.0.tgz", - "integrity": "sha512-mmHKys/C8BFUGI+MAWNcSYoORYLMdPzjrknd2Vc+bUsjN5bXcr8EhrNB+UTqfL1y3I9c4fw2ihgtMPQLBRiQxw==", - "dev": true, - "requires": { - "esprima": "^4.0.1", - "estraverse": "^5.2.0", - "esutils": "^2.0.2", - "optionator": "^0.8.1", - "source-map": "~0.6.1" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - }, - "levn": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", - "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", - "dev": true, - "requires": { - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2" - } - }, - "optionator": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", - "dev": true, - "requires": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.6", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "word-wrap": "~1.2.3" - } - }, - "prelude-ls": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", - "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", - "dev": true - }, - "type-check": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", - "integrity": "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg==", - "dev": true, - "requires": { - "prelude-ls": "~1.1.2" - } - } - } - }, - "eslint": { - "version": "8.25.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.25.0.tgz", - "integrity": "sha512-DVlJOZ4Pn50zcKW5bYH7GQK/9MsoQG2d5eDH0ebEkE8PbgzTTmtt/VTH9GGJ4BfeZCpBLqFfvsjX35UacUL83A==", - "dev": true, - "requires": { - "@eslint/eslintrc": "^1.3.3", - "@humanwhocodes/config-array": "^0.10.5", - "@humanwhocodes/module-importer": "^1.0.1", - "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.4.0", - "esquery": "^1.4.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "find-up": "^5.0.0", - "glob-parent": "^6.0.1", - "globals": "^13.15.0", - "globby": "^11.1.0", - "grapheme-splitter": "^1.0.4", - "ignore": "^5.2.0", - "import-fresh": "^3.0.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "js-sdsl": "^4.1.4", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "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" - }, - "dependencies": { - "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" - } - }, - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - } - } - }, - "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" - } - }, - "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.5.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.5.0.tgz", - "integrity": "sha512-JPbJGhKc47++oo4JkEoTe2wjy4fmMwvFpgJT9cQzmfXKp22Dr6Hf1tdCteLz1h0P3t+mGvWZ+4Uankvh8+c6zw==", - "dev": true, - "requires": { - "acorn": "^8.8.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.3.0" - } - }, - "esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true - }, - "esquery": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", - "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", - "dev": true, - "requires": { - "estraverse": "^5.1.0" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - } - } - }, - "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" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true - } - } - }, - "estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "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 - }, - "execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "requires": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - } - }, - "exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", - "dev": true - }, - "expect": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.5.0.tgz", - "integrity": "sha512-yM7xqUrCO2JdpFo4XpM82t+PJBFybdqoQuJLDGeDX2ij8NZzqRHyu3Hp188/JX7SWqud+7t4MUdvcgGBICMHZg==", - "dev": true, - "requires": { - "@jest/expect-utils": "^29.5.0", - "jest-get-type": "^29.4.3", - "jest-matcher-utils": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-util": "^29.5.0" - } - }, - "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.12", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.12.tgz", - "integrity": "sha512-DVj4CQIYYow0BlaelwK1pHl5n5cRSJfM60UA0zK891sVInoPri2Ekj7+e1CT3/3qxXenpI+nBBmQAcJPJgaj4w==", - "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" - }, - "dependencies": { - "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" - } - } - } - }, - "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": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true - }, - "fastq": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", - "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", - "dev": true, - "requires": { - "reusify": "^1.0.4" - } - }, - "fb-watchman": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", - "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", - "dev": true, - "requires": { - "bser": "2.1.1" - } - }, - "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" - } - }, - "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, - "requires": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - } - }, - "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" - } - }, - "flatted": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.7.tgz", - "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", - "dev": true - }, - "form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "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 - }, - "gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true - }, - "get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true - }, - "get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true - }, - "get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true - }, - "glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "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" - } - }, - "globals": { - "version": "13.20.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.20.0.tgz", - "integrity": "sha512-Qg5QtVkCy/kv3FUSlu4ukeZDVf9ee0iXLAUYX13gbR17bnejFTzr4iS9bY7kwCf1NztRNm1t91fjOiyx4CSwPQ==", - "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.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true - }, - "grapheme-splitter": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz", - "integrity": "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==", - "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": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true - }, - "html-encoding-sniffer": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", - "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==", - "dev": true, - "requires": { - "whatwg-encoding": "^2.0.0" - } - }, - "html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true - }, - "http-proxy-agent": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", - "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", - "dev": true, - "requires": { - "@tootallnate/once": "2", - "agent-base": "6", - "debug": "4" - } - }, - "https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "dev": true, - "requires": { - "agent-base": "6", - "debug": "4" - } - }, - "human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true - }, - "iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "requires": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - } - }, - "ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", - "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" - } - }, - "import-local": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", - "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", - "dev": true, - "requires": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - } - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "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": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true - }, - "is-core-module": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", - "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", - "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": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true - }, - "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 - }, - "is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", - "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-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-potential-custom-element-name": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", - "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true - }, - "is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true - }, - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true - }, - "istanbul-lib-coverage": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", - "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", - "dev": true - }, - "istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "requires": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, - "istanbul-lib-report": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", - "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", - "dev": true, - "requires": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^3.0.0", - "supports-color": "^7.1.0" - } - }, - "istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "dev": true, - "requires": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - } - }, - "istanbul-reports": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.5.tgz", - "integrity": "sha512-nUsEMa9pBt/NOHqbcbeJEgqIlY/K7rVWUX6Lql2orY5e9roQOthbR3vtY4zzf2orPELg80fnxxk9zUyPlgwD1w==", - "dev": true, - "requires": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - } - }, - "jest": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/jest/-/jest-29.1.2.tgz", - "integrity": "sha512-5wEIPpCezgORnqf+rCaYD1SK+mNN7NsstWzIsuvsnrhR/hSxXWd82oI7DkrbJ+XTD28/eG8SmxdGvukrGGK6Tw==", - "dev": true, - "requires": { - "@jest/core": "^29.1.2", - "@jest/types": "^29.1.2", - "import-local": "^3.0.2", - "jest-cli": "^29.1.2" - } - }, - "jest-changed-files": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.5.0.tgz", - "integrity": "sha512-IFG34IUMUaNBIxjQXF/iu7g6EcdMrGRRxaUSw92I/2g2YC6vCdTltl4nHvt7Ci5nSJwXIkCu8Ka1DKF+X7Z1Ag==", - "dev": true, - "requires": { - "execa": "^5.0.0", - "p-limit": "^3.1.0" - } - }, - "jest-circus": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.5.0.tgz", - "integrity": "sha512-gq/ongqeQKAplVxqJmbeUOJJKkW3dDNPY8PjhJ5G0lBRvu0e3EWGxGy5cI4LAGA7gV2UHCtWBI4EMXK8c9nQKA==", - "dev": true, - "requires": { - "@jest/environment": "^29.5.0", - "@jest/expect": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "dedent": "^0.7.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^29.5.0", - "jest-matcher-utils": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-runtime": "^29.5.0", - "jest-snapshot": "^29.5.0", - "jest-util": "^29.5.0", - "p-limit": "^3.1.0", - "pretty-format": "^29.5.0", - "pure-rand": "^6.0.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - } - }, - "jest-cli": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.5.0.tgz", - "integrity": "sha512-L1KcP1l4HtfwdxXNFCL5bmUbLQiKrakMUriBEcc1Vfz6gx31ORKdreuWvmQVBit+1ss9NNR3yxjwfwzZNdQXJw==", - "dev": true, - "requires": { - "@jest/core": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/types": "^29.5.0", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "import-local": "^3.0.2", - "jest-config": "^29.5.0", - "jest-util": "^29.5.0", - "jest-validate": "^29.5.0", - "prompts": "^2.0.1", - "yargs": "^17.3.1" - } - }, - "jest-config": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.5.0.tgz", - "integrity": "sha512-kvDUKBnNJPNBmFFOhDbm59iu1Fii1Q6SxyhXfvylq3UTHbg6o7j/g8k2dZyXWLvfdKB1vAPxNZnMgtKJcmu3kA==", - "dev": true, - "requires": { - "@babel/core": "^7.11.6", - "@jest/test-sequencer": "^29.5.0", - "@jest/types": "^29.5.0", - "babel-jest": "^29.5.0", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-circus": "^29.5.0", - "jest-environment-node": "^29.5.0", - "jest-get-type": "^29.4.3", - "jest-regex-util": "^29.4.3", - "jest-resolve": "^29.5.0", - "jest-runner": "^29.5.0", - "jest-util": "^29.5.0", - "jest-validate": "^29.5.0", - "micromatch": "^4.0.4", - "parse-json": "^5.2.0", - "pretty-format": "^29.5.0", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - } - }, - "jest-diff": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.5.0.tgz", - "integrity": "sha512-LtxijLLZBduXnHSniy0WMdaHjmQnt3g5sa16W4p0HqukYTTsyTW3GD1q41TyGl5YFXj/5B2U6dlh5FM1LIMgxw==", - "dev": true, - "requires": { - "chalk": "^4.0.0", - "diff-sequences": "^29.4.3", - "jest-get-type": "^29.4.3", - "pretty-format": "^29.5.0" - } - }, - "jest-docblock": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.4.3.tgz", - "integrity": "sha512-fzdTftThczeSD9nZ3fzA/4KkHtnmllawWrXO69vtI+L9WjEIuXWs4AmyME7lN5hU7dB0sHhuPfcKofRsUb/2Fg==", - "dev": true, - "requires": { - "detect-newline": "^3.0.0" - } - }, - "jest-each": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.5.0.tgz", - "integrity": "sha512-HM5kIJ1BTnVt+DQZ2ALp3rzXEl+g726csObrW/jpEGl+CDSSQpOJJX2KE/vEg8cxcMXdyEPu6U4QX5eruQv5hA==", - "dev": true, - "requires": { - "@jest/types": "^29.5.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.4.3", - "jest-util": "^29.5.0", - "pretty-format": "^29.5.0" - } - }, - "jest-environment-jsdom": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.1.2.tgz", - "integrity": "sha512-D+XNIKia5+uDjSMwL/G1l6N9MCb7LymKI8FpcLo7kkISjc/Sa9w+dXXEa7u1Wijo3f8sVLqfxdGqYtRhmca+Xw==", - "dev": true, - "requires": { - "@jest/environment": "^29.1.2", - "@jest/fake-timers": "^29.1.2", - "@jest/types": "^29.1.2", - "@types/jsdom": "^20.0.0", - "@types/node": "*", - "jest-mock": "^29.1.2", - "jest-util": "^29.1.2", - "jsdom": "^20.0.0" - } - }, - "jest-environment-node": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.5.0.tgz", - "integrity": "sha512-ExxuIK/+yQ+6PRGaHkKewYtg6hto2uGCgvKdb2nfJfKXgZ17DfXjvbZ+jA1Qt9A8EQSfPnt5FKIfnOO3u1h9qw==", - "dev": true, - "requires": { - "@jest/environment": "^29.5.0", - "@jest/fake-timers": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "jest-mock": "^29.5.0", - "jest-util": "^29.5.0" - } - }, - "jest-get-type": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.4.3.tgz", - "integrity": "sha512-J5Xez4nRRMjk8emnTpWrlkyb9pfRQQanDrvWHhsR1+VUfbwxi30eVcZFlcdGInRibU4G5LwHXpI7IRHU0CY+gg==", - "dev": true - }, - "jest-haste-map": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.5.0.tgz", - "integrity": "sha512-IspOPnnBro8YfVYSw6yDRKh/TiCdRngjxeacCps1cQ9cgVN6+10JUcuJ1EabrgYLOATsIAigxA0rLR9x/YlrSA==", - "dev": true, - "requires": { - "@jest/types": "^29.5.0", - "@types/graceful-fs": "^4.1.3", - "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "fsevents": "^2.3.2", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^29.4.3", - "jest-util": "^29.5.0", - "jest-worker": "^29.5.0", - "micromatch": "^4.0.4", - "walker": "^1.0.8" - } - }, - "jest-leak-detector": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.5.0.tgz", - "integrity": "sha512-u9YdeeVnghBUtpN5mVxjID7KbkKE1QU4f6uUwuxiY0vYRi9BUCLKlPEZfDGR67ofdFmDz9oPAy2G92Ujrntmow==", - "dev": true, - "requires": { - "jest-get-type": "^29.4.3", - "pretty-format": "^29.5.0" - } - }, - "jest-matcher-utils": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.5.0.tgz", - "integrity": "sha512-lecRtgm/rjIK0CQ7LPQwzCs2VwW6WAahA55YBuI+xqmhm7LAaxokSB8C97yJeYyT+HvQkH741StzpU41wohhWw==", - "dev": true, - "requires": { - "chalk": "^4.0.0", - "jest-diff": "^29.5.0", - "jest-get-type": "^29.4.3", - "pretty-format": "^29.5.0" - } - }, - "jest-message-util": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.5.0.tgz", - "integrity": "sha512-Kijeg9Dag6CKtIDA7O21zNTACqD5MD/8HfIV8pdD94vFyFuer52SigdC3IQMhab3vACxXMiFk+yMHNdbqtyTGA==", - "dev": true, - "requires": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.5.0", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.5.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - } - }, - "jest-mock": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.5.0.tgz", - "integrity": "sha512-GqOzvdWDE4fAV2bWQLQCkujxYWL7RxjCnj71b5VhDAGOevB3qj3Ovg26A5NI84ZpODxyzaozXLOh2NCgkbvyaw==", - "dev": true, - "requires": { - "@jest/types": "^29.5.0", - "@types/node": "*", - "jest-util": "^29.5.0" - } - }, - "jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "dev": true, - "requires": {} - }, - "jest-regex-util": { - "version": "29.4.3", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.4.3.tgz", - "integrity": "sha512-O4FglZaMmWXbGHSQInfXewIsd1LMn9p3ZXB/6r4FOkyhX2/iP/soMG98jGvk/A3HAN78+5VWcBGO0BJAPRh4kg==", - "dev": true - }, - "jest-resolve": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.5.0.tgz", - "integrity": "sha512-1TzxJ37FQq7J10jPtQjcc+MkCkE3GBpBecsSUWJ0qZNJpmg6m0D9/7II03yJulm3H/fvVjgqLh/k2eYg+ui52w==", - "dev": true, - "requires": { - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.5.0", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^29.5.0", - "jest-validate": "^29.5.0", - "resolve": "^1.20.0", - "resolve.exports": "^2.0.0", - "slash": "^3.0.0" - } - }, - "jest-resolve-dependencies": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.5.0.tgz", - "integrity": "sha512-sjV3GFr0hDJMBpYeUuGduP+YeCRbd7S/ck6IvL3kQ9cpySYKqcqhdLLC2rFwrcL7tz5vYibomBrsFYWkIGGjOg==", - "dev": true, - "requires": { - "jest-regex-util": "^29.4.3", - "jest-snapshot": "^29.5.0" - } - }, - "jest-runner": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.5.0.tgz", - "integrity": "sha512-m7b6ypERhFghJsslMLhydaXBiLf7+jXy8FwGRHO3BGV1mcQpPbwiqiKUR2zU2NJuNeMenJmlFZCsIqzJCTeGLQ==", - "dev": true, - "requires": { - "@jest/console": "^29.5.0", - "@jest/environment": "^29.5.0", - "@jest/test-result": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^29.4.3", - "jest-environment-node": "^29.5.0", - "jest-haste-map": "^29.5.0", - "jest-leak-detector": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-resolve": "^29.5.0", - "jest-runtime": "^29.5.0", - "jest-util": "^29.5.0", - "jest-watcher": "^29.5.0", - "jest-worker": "^29.5.0", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" - } - }, - "jest-runtime": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.5.0.tgz", - "integrity": "sha512-1Hr6Hh7bAgXQP+pln3homOiEZtCDZFqwmle7Ew2j8OlbkIu6uE3Y/etJQG8MLQs3Zy90xrp2C0BRrtPHG4zryw==", - "dev": true, - "requires": { - "@jest/environment": "^29.5.0", - "@jest/fake-timers": "^29.5.0", - "@jest/globals": "^29.5.0", - "@jest/source-map": "^29.4.3", - "@jest/test-result": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-mock": "^29.5.0", - "jest-regex-util": "^29.4.3", - "jest-resolve": "^29.5.0", - "jest-snapshot": "^29.5.0", - "jest-util": "^29.5.0", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - }, - "dependencies": { - "@jest/globals": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.5.0.tgz", - "integrity": "sha512-S02y0qMWGihdzNbUiqSAiKSpSozSuHX5UYc7QbnHP+D9Lyw8DgGGCinrN9uSuHPeKgSSzvPom2q1nAtBvUsvPQ==", - "dev": true, - "requires": { - "@jest/environment": "^29.5.0", - "@jest/expect": "^29.5.0", - "@jest/types": "^29.5.0", - "jest-mock": "^29.5.0" - } - } - } - }, - "jest-snapshot": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.5.0.tgz", - "integrity": "sha512-x7Wolra5V0tt3wRs3/ts3S6ciSQVypgGQlJpz2rsdQYoUKxMxPNaoHMGJN6qAuPJqS+2iQ1ZUn5kl7HCyls84g==", - "dev": true, - "requires": { - "@babel/core": "^7.11.6", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-jsx": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/traverse": "^7.7.2", - "@babel/types": "^7.3.3", - "@jest/expect-utils": "^29.5.0", - "@jest/transform": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/babel__traverse": "^7.0.6", - "@types/prettier": "^2.1.5", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^29.5.0", - "graceful-fs": "^4.2.9", - "jest-diff": "^29.5.0", - "jest-get-type": "^29.4.3", - "jest-matcher-utils": "^29.5.0", - "jest-message-util": "^29.5.0", - "jest-util": "^29.5.0", - "natural-compare": "^1.4.0", - "pretty-format": "^29.5.0", - "semver": "^7.3.5" - } - }, - "jest-util": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.5.0.tgz", - "integrity": "sha512-RYMgG/MTadOr5t8KdhejfvUU82MxsCu5MF6KuDUHl+NuwzUt+Sm6jJWxTJVrDR1j5M/gJVCPKQEpWXY+yIQ6lQ==", - "dev": true, - "requires": { - "@jest/types": "^29.5.0", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - } - }, - "jest-validate": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.5.0.tgz", - "integrity": "sha512-pC26etNIi+y3HV8A+tUGr/lph9B18GnzSRAkPaaZJIE1eFdiYm6/CewuiJQ8/RlfHd1u/8Ioi8/sJ+CmbA+zAQ==", - "dev": true, - "requires": { - "@jest/types": "^29.5.0", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.4.3", - "leven": "^3.1.0", - "pretty-format": "^29.5.0" - }, - "dependencies": { - "camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true - } - } - }, - "jest-watcher": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.5.0.tgz", - "integrity": "sha512-KmTojKcapuqYrKDpRwfqcQ3zjMlwu27SYext9pt4GlF5FUgB+7XE1mcCnSm6a4uUpFyQIkb6ZhzZvHl+jiBCiA==", - "dev": true, - "requires": { - "@jest/test-result": "^29.5.0", - "@jest/types": "^29.5.0", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "jest-util": "^29.5.0", - "string-length": "^4.0.1" - } - }, - "jest-worker": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.5.0.tgz", - "integrity": "sha512-NcrQnevGoSp4b5kg+akIpthoAFHxPBcb5P6mYPY0fUNT+sSvmtu6jlkEle3anczUKIKEbMxFimk9oTP/tpIPgA==", - "dev": true, - "requires": { - "@types/node": "*", - "jest-util": "^29.5.0", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "dependencies": { - "supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "requires": { - "has-flag": "^4.0.0" - } - } - } - }, - "js-sdsl": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.3.0.tgz", - "integrity": "sha512-mifzlm2+5nZ+lEcLJMoBK0/IH/bDg8XnJfd/Wq6IP+xoCjLZsTOnV2QpxlVbX9bMnkl5PdEjNtBJ9Cj1NjifhQ==", - "dev": true - }, - "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==", - "dev": true, - "requires": { - "argparse": "^2.0.1" - } - }, - "jsdom": { - "version": "20.0.3", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.3.tgz", - "integrity": "sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==", - "dev": true, - "requires": { - "abab": "^2.0.6", - "acorn": "^8.8.1", - "acorn-globals": "^7.0.0", - "cssom": "^0.5.0", - "cssstyle": "^2.3.0", - "data-urls": "^3.0.2", - "decimal.js": "^10.4.2", - "domexception": "^4.0.0", - "escodegen": "^2.0.0", - "form-data": "^4.0.0", - "html-encoding-sniffer": "^3.0.0", - "http-proxy-agent": "^5.0.0", - "https-proxy-agent": "^5.0.1", - "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.2", - "parse5": "^7.1.1", - "saxes": "^6.0.0", - "symbol-tree": "^3.2.4", - "tough-cookie": "^4.1.2", - "w3c-xmlserializer": "^4.0.0", - "webidl-conversions": "^7.0.0", - "whatwg-encoding": "^2.0.0", - "whatwg-mimetype": "^3.0.0", - "whatwg-url": "^11.0.0", - "ws": "^8.11.0", - "xml-name-validator": "^4.0.0" - } - }, - "jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true - }, - "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": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true - }, - "json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true - }, - "kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", - "dev": true - }, - "leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", - "dev": true - }, - "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" - } - }, - "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 - }, - "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, - "requires": { - "p-locate": "^5.0.0" - } - }, - "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 - }, - "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 - }, - "lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "requires": { - "yallist": "^3.0.2" - } - }, - "make-dir": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", - "dev": true, - "requires": { - "semver": "^6.0.0" - }, - "dependencies": { - "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", - "dev": true - } - } - }, - "make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true - }, - "makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "dev": true, - "requires": { - "tmpl": "1.0.5" - } - }, - "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-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "dev": true - }, - "mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, - "requires": { - "mime-db": "1.52.0" - } - }, - "mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "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" - } - }, - "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 - }, - "natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true - }, - "node-fetch": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", - "integrity": "sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg==", - "dev": true, - "requires": { - "whatwg-url": "^5.0.0" - }, - "dependencies": { - "tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true - }, - "webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true - }, - "whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "dev": true, - "requires": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - } - } - }, - "node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", - "dev": true - }, - "node-releases": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.10.tgz", - "integrity": "sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w==", - "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 - }, - "npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "requires": { - "path-key": "^3.0.0" - } - }, - "nwsapi": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.2.tgz", - "integrity": "sha512-90yv+6538zuvUMnN+zCr8LuV6bPFdq50304114vJYJ8RDyK8D5O9Phpbd6SZWgI7PwzmmfN1upeOJlvybDSgCw==", - "dev": true - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "requires": { - "wrappy": "1" - } - }, - "onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, - "requires": { - "mimic-fn": "^2.1.0" - } - }, - "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" - } - }, - "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, - "requires": { - "yocto-queue": "^0.1.0" - } - }, - "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, - "requires": { - "p-limit": "^3.0.2" - } - }, - "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "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" - } - }, - "parse5": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", - "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", - "dev": true, - "requires": { - "entities": "^4.4.0" - } - }, - "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 - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "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 - }, - "pirates": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", - "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==", - "dev": true - }, - "pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "requires": { - "find-up": "^4.0.0" - }, - "dependencies": { - "find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "requires": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - } - }, - "locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "requires": { - "p-locate": "^4.1.0" - } - }, - "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "requires": { - "p-limit": "^2.2.0" - } - } - } - }, - "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.7.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", - "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==", - "dev": true - }, - "pretty-format": { - "version": "29.5.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.5.0.tgz", - "integrity": "sha512-V2mGkI31qdttvTFX7Mt4efOqHXqJWMu4/r66Xh3Z3BwZaPfPJgp6/gbwoujRpPUtfEF6AUUWx3Jim3GCw5g/Qw==", - "dev": true, - "requires": { - "@jest/schemas": "^29.4.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true - } - } - }, - "prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "dev": true, - "requires": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" - } - }, - "psl": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", - "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", - "dev": true - }, - "punycode": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", - "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", - "dev": true - }, - "pure-rand": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.1.tgz", - "integrity": "sha512-t+x1zEHDjBwkDGY5v5ApnZ/utcd4XYDiJsaQQoptTXgUXX95sDg1elCdJghzicm7n2mbCBJ3uYWr6M22SO19rg==", - "dev": true - }, - "pyodide": { - "version": "0.22.1", - "resolved": "https://registry.npmjs.org/pyodide/-/pyodide-0.22.1.tgz", - "integrity": "sha512-6+PkFLTC+kcBKtFQxYBxR44J5IBxLm8UGkobLgZv1SxzV9qOU2rb0YYf0qDtlnfDiN/IQd2uckf+D8Zwe88Mqg==", - "dev": true, - "requires": { - "base-64": "^1.0.0", - "node-fetch": "^2.6.1", - "ws": "^8.5.0" - } - }, - "querystringify": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", - "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", - "dev": true - }, - "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 - }, - "react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", - "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-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true - }, - "requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true - }, - "resolve": { - "version": "1.22.1", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", - "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", - "dev": true, - "requires": { - "is-core-module": "^2.9.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - } - }, - "resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", - "dev": true, - "requires": { - "resolve-from": "^5.0.0" - }, - "dependencies": { - "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 - } - } - }, - "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 - }, - "resolve.exports": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.1.tgz", - "integrity": "sha512-OEJWVeimw8mgQuj3HfkNl4KqRevH7lzeQNaWRPfx0PPse7Jk6ozcsG4FKVgtzDsC1KUF+YlTHh17NcgHOPykLw==", - "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 - }, - "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" - } - }, - "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" - } - }, - "safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true - }, - "saxes": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", - "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", - "dev": true, - "requires": { - "xmlchars": "^2.2.0" - } - }, - "semver": { - "version": "7.3.8", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", - "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", - "dev": true, - "requires": { - "lru-cache": "^6.0.0" - }, - "dependencies": { - "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" - } - }, - "yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - } - } - }, - "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 - }, - "signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true - }, - "sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true - }, - "slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true - }, - "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 - }, - "source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "dev": true, - "requires": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true - }, - "stack-utils": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, - "requires": { - "escape-string-regexp": "^2.0.0" - }, - "dependencies": { - "escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true - } - } - }, - "string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, - "requires": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - } - }, - "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, - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - } - }, - "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-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", - "dev": true - }, - "strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true - }, - "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.2", - "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.0.2.tgz", - "integrity": "sha512-C4myMmRTO8iaC5Gg+N1ftK2WT4eXUTMAa+HEFPPrfVeO/NtqLTtAmV1HbqnuGtLwCek44Ra76fdGUkSqjiMPcQ==" - }, - "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" - } - }, - "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 - }, - "symbol-tree": { - "version": "3.2.4", - "dev": true - }, - "synclink": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/synclink/-/synclink-0.1.1.tgz", - "integrity": "sha512-34eBqFHZn3f2PX/tz/z0E+817Um6ESFNsBkMoGqoGgBX0qlLNlRXFoHSNIUSjTK8l5Qs4gL99Xwrz0vNAUrPEw==" - }, - "test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, - "requires": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" - } - }, - "text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true - }, - "tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", - "dev": true - }, - "to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", - "dev": true - }, - "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" - } - }, - "tough-cookie": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.2.tgz", - "integrity": "sha512-G9fqXWoYFZgTc2z8Q5zaHy/vJMjm+WV0AkAeHxVCQiEB1b+dGvWzFW6QV07cY5jQ5gRkeid2qIkzkxUnmoQZUQ==", - "dev": true, - "requires": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" - } - }, - "tr46": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", - "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", - "dev": true, - "requires": { - "punycode": "^2.1.1" - } - }, - "ts-jest": { - "version": "29.0.3", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.0.3.tgz", - "integrity": "sha512-Ibygvmuyq1qp/z3yTh9QTwVVAbFdDy/+4BtIQR2sp6baF2SJU/8CKK/hhnGIDY2L90Az2jIqTwZPnN2p+BweiQ==", - "dev": true, - "requires": { - "bs-logger": "0.x", - "fast-json-stable-stringify": "2.x", - "jest-util": "^29.0.0", - "json5": "^2.2.1", - "lodash.memoize": "4.x", - "make-error": "1.x", - "semver": "7.x", - "yargs-parser": "^21.0.1" - } - }, - "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-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true - }, - "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.8.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.4.tgz", - "integrity": "sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==", - "dev": true - }, - "universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", - "dev": true - }, - "update-browserslist-db": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", - "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", - "dev": true, - "requires": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" - } - }, - "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" - } - }, - "url-parse": { - "version": "1.5.10", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", - "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "dev": true, - "requires": { - "querystringify": "^2.1.1", - "requires-port": "^1.0.0" - } - }, - "v8-to-istanbul": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.0.tgz", - "integrity": "sha512-6z3GW9x8G1gd+JIIgQQQxXuiJtCXeAjp6RaPEPLv62mH3iPHPxV6W3robxtCzNErRo6ZwTmzWhsbNvjyEBKzKA==", - "dev": true, - "requires": { - "@jridgewell/trace-mapping": "^0.3.12", - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^1.6.0" - }, - "dependencies": { - "convert-source-map": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", - "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", - "dev": true - } - } - }, - "w3c-keyname": { - "version": "2.2.6", - "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.6.tgz", - "integrity": "sha512-f+fciywl1SJEniZHD6H+kUO8gOnwIr7f4ijKA6+ZvJFjeGi1r4PDLl53Ayud9O/rk64RqgoQine0feoeOU0kXg==" - }, - "w3c-xmlserializer": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz", - "integrity": "sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==", - "dev": true, - "requires": { - "xml-name-validator": "^4.0.0" - } - }, - "walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "dev": true, - "requires": { - "makeerror": "1.0.12" - } - }, - "webidl-conversions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", - "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", - "dev": true - }, - "whatwg-encoding": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", - "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", - "dev": true, - "requires": { - "iconv-lite": "0.6.3" - } - }, - "whatwg-mimetype": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", - "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", - "dev": true - }, - "whatwg-url": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", - "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", - "dev": true, - "requires": { - "tr46": "^3.0.0", - "webidl-conversions": "^7.0.0" - } - }, - "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 - }, - "wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "requires": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - } - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true - }, - "write-file-atomic": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", - "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "dev": true, - "requires": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" - } - }, - "ws": { - "version": "8.13.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", - "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", - "dev": true, - "requires": {} - }, - "xml-name-validator": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-4.0.0.tgz", - "integrity": "sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==", - "dev": true - }, - "xmlchars": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", - "dev": true - }, - "y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true - }, - "yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true - }, - "yargs": { - "version": "17.7.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.1.tgz", - "integrity": "sha512-cwiTb08Xuv5fqF4AovYacTFNxk62th7LKJ6BL9IGUpTJrWoU7/7WdQGTP2SjKf1dUNBGzDd28p/Yfs/GI6JrLw==", - "dev": true, - "requires": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - } - }, - "yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true - }, - "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 - } - } -} diff --git a/pyscriptjs/package.json b/pyscriptjs/package.json deleted file mode 100644 index 63fcc1b8a75..00000000000 --- a/pyscriptjs/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "pyscript", - "version": "0.0.1", - "scripts": { - "build": "npm run tsc && node esbuild.mjs", - "dev": "NODE_WATCH=1 node esbuild.mjs", - "tsc": "tsc --noEmit", - "format:check": "prettier --check './src/**/*.{mjs,js,html,ts}'", - "format": "prettier --write './src/**/*.{mjs,js,html,ts}'", - "lint": "eslint './src/**/*.{mjs,js,html,ts}'", - "lint:fix": "eslint --fix './src/**/*.{mjs,js,html,ts}'", - "xprelint": "npm run format", - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage", - "test:watch": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --watch" - }, - "devDependencies": { - "@jest/globals": "29.1.2", - "@types/codemirror": "^5.60.5", - "@types/jest": "29.1.2", - "@types/node": "18.8.3", - "@typescript-eslint/eslint-plugin": "5.39.0", - "@typescript-eslint/parser": "5.39.0", - "cross-env": "7.0.3", - "esbuild": "0.17.12", - "eslint": "8.25.0", - "jest": "29.1.2", - "jest-environment-jsdom": "29.1.2", - "prettier": "2.7.1", - "pyodide": "0.22.1", - "ts-jest": "29.0.3", - "tslib": "2.4.0", - "typescript": "4.8.4" - }, - "dependencies": { - "@codemirror/commands": "^6.2.2", - "@codemirror/lang-python": "^6.1.2", - "@codemirror/language": "^6.6.0", - "@codemirror/state": "^6.2.0", - "@codemirror/theme-one-dark": "^6.1.1", - "@codemirror/view": "^6.9.3", - "@hoodmane/toml-j0.4": "^1.1.2", - "codemirror": "6.0.1", - "synclink": "^0.1.1" - } -} diff --git a/pyscriptjs/public/.gitkeep b/pyscriptjs/public/.gitkeep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/pyscriptjs/public/index.html b/pyscriptjs/public/index.html deleted file mode 100644 index 8443107f8d8..00000000000 --- a/pyscriptjs/public/index.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - PyScript - - - -
-

<py-script>

- -
- - import sys - print(sys.version) - - -

Example

-
-<!DOCTYPE html>
-<html lang="en">
-    <head>
-    <meta charset="utf-8" />
-    <meta name="viewport" content="width=device-width,initial-scale=1" />
-    <title>PyScript Hello World</title>
-    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
-    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
-    </head>
-
-    <body>
-    Hello world! <br>
-    This is the current date and time, as computed by Python:
-    <py-script>
-from datetime import datetime
-now = datetime.now()
-now.strftime("%m/%d/%Y, %H:%M:%S")
-    </py-script>
-    </body>
-</html>
-
- - diff --git a/pyscriptjs/src/components/elements.ts b/pyscriptjs/src/components/elements.ts deleted file mode 100644 index 9c24841b7ce..00000000000 --- a/pyscriptjs/src/components/elements.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { InterpreterClient } from '../interpreter_client'; -import type { PyScriptApp } from '../main'; -import { make_PyRepl } from './pyrepl'; -import { make_PyWidget } from './pywidget'; - -function createCustomElements(interpreter: InterpreterClient, app: PyScriptApp) { - const PyWidget = make_PyWidget(interpreter); - const PyRepl = make_PyRepl(interpreter, app); - - /* eslint-disable @typescript-eslint/no-unused-vars */ - const xPyRepl = customElements.define('py-repl', PyRepl); - const xPyWidget = customElements.define('py-register-widget', PyWidget); - /* eslint-enable @typescript-eslint/no-unused-vars */ -} - -export { createCustomElements }; diff --git a/pyscriptjs/src/components/pyrepl.ts b/pyscriptjs/src/components/pyrepl.ts deleted file mode 100644 index 47ba551adad..00000000000 --- a/pyscriptjs/src/components/pyrepl.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { basicSetup, EditorView } from 'codemirror'; -import { python } from '@codemirror/lang-python'; -import { indentUnit } from '@codemirror/language'; -import { Compartment } from '@codemirror/state'; -import { keymap, Command } from '@codemirror/view'; -import { defaultKeymap } from '@codemirror/commands'; -import { oneDarkTheme } from '@codemirror/theme-one-dark'; - -import { ensureUniqueId, htmlDecode } from '../utils'; -import { pyExec } from '../pyexec'; -import { getLogger } from '../logger'; -import { InterpreterClient } from '../interpreter_client'; -import type { PyScriptApp } from '../main'; -import { Stdio } from '../stdio'; - -const logger = getLogger('py-repl'); -const RUNBUTTON = ``; - -export function make_PyRepl(interpreter: InterpreterClient, app: PyScriptApp) { - /* High level structure of py-repl DOM, and the corresponding JS names. - - this - boxDiv
- editorDiv
- outDiv
-
-
- */ - class PyRepl extends HTMLElement { - outDiv: HTMLElement; - editor: EditorView; - stdout_manager: Stdio | null; - stderr_manager: Stdio | null; - - connectedCallback() { - ensureUniqueId(this); - - if (!this.hasAttribute('exec-id')) { - this.setAttribute('exec-id', '0'); - } - if (!this.hasAttribute('root')) { - this.setAttribute('root', this.id); - } - - const pySrc = htmlDecode(this.innerHTML).trim(); - this.innerHTML = ''; - this.editor = this.makeEditor(pySrc); - const boxDiv = this.makeBoxDiv(); - this.appendChild(boxDiv); - this.editor.focus(); - logger.debug(`element ${this.id} successfully connected`); - } - - /** Create and configure the codemirror editor - */ - makeEditor(pySrc: string): EditorView { - const languageConf = new Compartment(); - const extensions = [ - indentUnit.of(' '), - basicSetup, - languageConf.of(python()), - keymap.of([ - ...defaultKeymap, - { key: 'Ctrl-Enter', run: this.execute.bind(this) as Command, preventDefault: true }, - { key: 'Shift-Enter', run: this.execute.bind(this) as Command, preventDefault: true }, - ]), - ]; - - if (this.getAttribute('theme') === 'dark') { - extensions.push(oneDarkTheme); - } - - return new EditorView({ - doc: pySrc, - extensions, - }); - } - - // ******** main entry point for py-repl DOM building ********** - // - // The following functions are written in a top-down, depth-first - // order (so that the order of code roughly matches the order of - // execution) - makeBoxDiv(): HTMLElement { - const boxDiv = document.createElement('div'); - boxDiv.className = 'py-repl-box'; - - const editorDiv = this.makeEditorDiv(); - this.outDiv = this.makeOutDiv(); - - boxDiv.appendChild(editorDiv); - boxDiv.appendChild(this.outDiv); - - return boxDiv; - } - - makeEditorDiv(): HTMLElement { - const editorDiv = document.createElement('div'); - editorDiv.className = 'py-repl-editor'; - editorDiv.setAttribute('aria-label', 'Python Script Area'); - editorDiv.appendChild(this.editor.dom); - - const runButton = this.makeRunButton(); - editorDiv.appendChild(runButton); - - return editorDiv; - } - - makeRunButton(): HTMLElement { - const runButton = document.createElement('button'); - runButton.className = 'absolute py-repl-run-button'; - runButton.innerHTML = RUNBUTTON; - runButton.setAttribute('aria-label', 'Python Script Run Button'); - runButton.addEventListener('click', this.execute.bind(this) as (e: MouseEvent) => void); - return runButton; - } - - makeOutDiv(): HTMLElement { - const outDiv = document.createElement('div'); - outDiv.className = 'py-repl-output'; - outDiv.id = this.id + '-repl-output'; - return outDiv; - } - - // ********************* execution logic ********************* - - /** Execute the python code written in the editor, and automatically - * display() the last evaluated expression - */ - async execute(): Promise { - const pySrc = this.getPySrc(); - const outEl = this.outDiv; - - // execute the python code - await app.plugins.beforePyReplExec({ interpreter: interpreter, src: pySrc, outEl: outEl, pyReplTag: this }); - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const { result } = await pyExec(interpreter, pySrc, outEl); - await app.plugins.afterPyReplExec({ - interpreter: interpreter, - src: pySrc, - outEl: outEl, - pyReplTag: this, - result, // eslint-disable-line @typescript-eslint/no-unsafe-assignment - }); - - this.autogenerateMaybe(); - } - - getPySrc(): string { - return this.editor.state.doc.toString(); - } - - // XXX the autogenerate logic is very messy. We should redo it, and it - // should be the default. - autogenerateMaybe(): void { - 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'); - - //Attributes to be copied from old REPL to auto-generated REPL - for (const attribute of ['root', 'output-mode', 'output', 'stderr']) { - const attr = this.getAttribute(attribute); - if (attr) { - newPyRepl.setAttribute(attribute, attr); - } - } - - newPyRepl.id = this.getAttribute('root') + '-' + nextExecId.toString(); - - if (this.hasAttribute('auto-generate')) { - newPyRepl.setAttribute('auto-generate', ''); - this.removeAttribute('auto-generate'); - } - - newPyRepl.setAttribute('exec-id', nextExecId.toString()); - if (this.parentElement) { - this.parentElement.appendChild(newPyRepl); - } - } - } - } - - return PyRepl; -} diff --git a/pyscriptjs/src/components/pyscript.ts b/pyscriptjs/src/components/pyscript.ts deleted file mode 100644 index 51737af7de0..00000000000 --- a/pyscriptjs/src/components/pyscript.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { htmlDecode, ensureUniqueId, createDeprecationWarning } from '../utils'; -import { getLogger } from '../logger'; -import { pyExec, displayPyException } from '../pyexec'; -import { _createAlertBanner } from '../exceptions'; -import { robustFetch } from '../fetch'; -import { PyScriptApp } from '../main'; -import { Stdio } from '../stdio'; -import { InterpreterClient } from '../interpreter_client'; - -const logger = getLogger('py-script'); - -export function make_PyScript(interpreter: InterpreterClient, app: PyScriptApp) { - class PyScript extends HTMLElement { - srcCode: string; - stdout_manager: Stdio | null; - stderr_manager: Stdio | null; - - async connectedCallback() { - /** - * Since connectedCallback is async, multiple py-script tags can be executed in - * an order which is not particularly sequential. The locking mechanism here ensures - * a sequential execution of multiple py-script tags present in one page. - * - * Concurrent access to the multiple py-script tags is thus avoided. - */ - app.incrementPendingTags(); - let releaseLock: () => void; - try { - releaseLock = await app.tagExecutionLock(); - ensureUniqueId(this); - // Save innerHTML information in srcCode so we can access it later - // once we clean innerHTML (which is required since we don't want - // source code to be rendered on the screen) - this.srcCode = this.innerHTML; - const pySrc = await this.getPySrc(); - this.innerHTML = ''; - - await app.plugins.beforePyScriptExec({ interpreter: interpreter, src: pySrc, pyScriptTag: this }); - /* eslint-disable @typescript-eslint/no-unsafe-assignment */ - const result = (await pyExec(interpreter, pySrc, this)).result; - await app.plugins.afterPyScriptExec({ - interpreter: interpreter, - src: pySrc, - pyScriptTag: this, - result: result, - }); - /* eslint-enable @typescript-eslint/no-unsafe-assignment */ - } finally { - releaseLock(); - app.decrementPendingTags(); - } - } - - async getPySrc(): Promise { - if (this.hasAttribute('src')) { - const url = this.getAttribute('src'); - try { - const response = await robustFetch(url); - return await response.text(); - } catch (err) { - const e = err as Error; - _createAlertBanner(e.message); - this.innerHTML = ''; - throw e; - } - } else { - return htmlDecode(this.srcCode); - } - } - } - - return PyScript; -} - -/** Defines all possible py-on* and their corresponding event types */ -const pyAttributeToEvent: Map = new Map([ - // Leaving pys-onClick and pys-onKeyDown for backward compatibility - ['pys-onClick', 'click'], - ['pys-onKeyDown', 'keydown'], - ['py-onClick', 'click'], - ['py-onKeyDown', 'keydown'], - // Window Events - ['py-afterprint', 'afterprint'], - ['py-beforeprint', 'beforeprint'], - ['py-beforeunload', 'beforeunload'], - ['py-error', 'error'], - ['py-hashchange', 'hashchange'], - ['py-load', 'load'], - ['py-message', 'message'], - ['py-offline', 'offline'], - ['py-online', 'online'], - ['py-pagehide', 'pagehide'], - ['py-pageshow', 'pageshow'], - ['py-popstate', 'popstate'], - ['py-resize', 'resize'], - ['py-storage', 'storage'], - ['py-unload', 'unload'], - - // Form Events - ['py-blur', 'blur'], - ['py-change', 'change'], - ['py-contextmenu', 'contextmenu'], - ['py-focus', 'focus'], - ['py-input', 'input'], - ['py-invalid', 'invalid'], - ['py-reset', 'reset'], - ['py-search', 'search'], - ['py-select', 'select'], - ['py-submit', 'submit'], - - // Keyboard Events - ['py-keydown', 'keydown'], - ['py-keypress', 'keypress'], - ['py-keyup', 'keyup'], - - // Mouse Events - ['py-click', 'click'], - ['py-dblclick', 'dblclick'], - ['py-mousedown', 'mousedown'], - ['py-mousemove', 'mousemove'], - ['py-mouseout', 'mouseout'], - ['py-mouseover', 'mouseover'], - ['py-mouseup', 'mouseup'], - ['py-mousewheel', 'mousewheel'], - ['py-wheel', 'wheel'], - - // Drag Events - ['py-drag', 'drag'], - ['py-dragend', 'dragend'], - ['py-dragenter', 'dragenter'], - ['py-dragleave', 'dragleave'], - ['py-dragover', 'dragover'], - ['py-dragstart', 'dragstart'], - ['py-drop', 'drop'], - ['py-scroll', 'scroll'], - - // Clipboard Events - ['py-copy', 'copy'], - ['py-cut', 'cut'], - ['py-paste', 'paste'], - - // Media Events - ['py-abort', 'abort'], - ['py-canplay', 'canplay'], - ['py-canplaythrough', 'canplaythrough'], - ['py-cuechange', 'cuechange'], - ['py-durationchange', 'durationchange'], - ['py-emptied', 'emptied'], - ['py-ended', 'ended'], - ['py-loadeddata', 'loadeddata'], - ['py-loadedmetadata', 'loadedmetadata'], - ['py-loadstart', 'loadstart'], - ['py-pause', 'pause'], - ['py-play', 'play'], - ['py-playing', 'playing'], - ['py-progress', 'progress'], - ['py-ratechange', 'ratechange'], - ['py-seeked', 'seeked'], - ['py-seeking', 'seeking'], - ['py-stalled', 'stalled'], - ['py-suspend', 'suspend'], - ['py-timeupdate', 'timeupdate'], - ['py-volumechange', 'volumechange'], - ['py-waiting', 'waiting'], - - // Misc Events - ['py-toggle', 'toggle'], -]); - -/** Initialize all elements with py-* handlers attributes */ -export async function initHandlers(interpreter: InterpreterClient) { - logger.debug('Initializing py-* event handlers...'); - for (const pyAttribute of pyAttributeToEvent.keys()) { - await createElementsWithEventListeners(interpreter, pyAttribute); - } -} - -/** Initializes an element with the given py-on* attribute and its handler */ -async function createElementsWithEventListeners(interpreter: InterpreterClient, pyAttribute: string) { - const matches: NodeListOf = document.querySelectorAll(`[${pyAttribute}]`); - for (const el of matches) { - // If the element doesn't have an id, let's add one automatically! - if (el.id.length === 0) { - ensureUniqueId(el); - } - const handlerCode = el.getAttribute(pyAttribute); - const event = pyAttributeToEvent.get(pyAttribute); - - if (pyAttribute === 'pys-onClick' || pyAttribute === 'pys-onKeyDown') { - const msg = - `The attribute 'pys-onClick' and 'pys-onKeyDown' are deprecated. Please 'py-click="myFunction()"' ` + - ` or 'py-keydown="myFunction()"' instead.`; - createDeprecationWarning(msg, msg); - const source = ` - from pyodide.ffi import create_proxy - Element("${el.id}").element.addEventListener("${event}", create_proxy(${handlerCode})) - `; - - // We meed to run the source code in a try/catch block, because - // the source code may contain a syntax error, which will cause - // the splashscreen to not be removed. - try { - await interpreter.run(source); - } catch (e) { - logger.error((e as Error).message); - } - } else { - el.addEventListener(event, () => { - void (async () => { - try { - await interpreter.run(handlerCode); - } catch (e) { - const err = e as Error; - displayPyException(err, el.parentElement); - } - })(); - }); - } - // 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('py-onClick'); - // // pyodide.runPython(handlerCode); - // } - } -} - -/** Mount all elements with attribute py-mount into the Python namespace */ -export async function mountElements(interpreter: InterpreterClient) { - const matches: NodeListOf = document.querySelectorAll('[py-mount]'); - logger.info(`py-mount: found ${matches.length} elements`); - - if (matches.length > 0) { - //last non-deprecated version: 2023.03.1 - const deprecationMessage = - 'The "py-mount" attribute is deprecated. Please add references to HTML Elements manually in your script.'; - createDeprecationWarning(deprecationMessage, '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 interpreter.run(source); -} diff --git a/pyscriptjs/src/components/pywidget.ts b/pyscriptjs/src/components/pywidget.ts deleted file mode 100644 index 86326e4defd..00000000000 --- a/pyscriptjs/src/components/pywidget.ts +++ /dev/null @@ -1,102 +0,0 @@ -import type { PyProxy, PyProxyCallable } from 'pyodide'; -import { getLogger } from '../logger'; -import { robustFetch } from '../fetch'; -import { InterpreterClient } from '../interpreter_client'; -import type { Remote } from 'synclink'; - -const logger = getLogger('py-register-widget'); - -function createWidget(interpreter: InterpreterClient, name: string, code: string, klass: string) { - class CustomWidget extends HTMLElement { - shadow: ShadowRoot; - wrapper: HTMLElement; - - name: string = name; - klass: string = klass; - code: string = code; - proxy: Remote; - proxyClass: Remote; - - 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); - } - - async connectedCallback() { - await interpreter.runButDontRaise(this.code); - this.proxyClass = (await interpreter.globals.get(this.klass)) as Remote; - this.proxy = (await this.proxyClass(this)) as Remote; - await this.proxy.connect(); - await this.registerWidget(); - } - - async registerWidget() { - logger.info('new widget registered:', this.name); - await interpreter.globals.set(this.id, this.proxy); - } - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const xPyWidget = customElements.define(name, CustomWidget); -} - -export function make_PyWidget(interpreter: InterpreterClient) { - 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); - - this.addAttributes('src', 'name', 'klass'); - } - - addAttributes(...attrs: string[]) { - for (const each of attrs) { - const property = each === 'src' ? 'source' : each; - if (this.hasAttribute(each)) { - this[property] = this.getAttribute(each); - } - } - } - - 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); - logger.debug('PyWidget: reading source', this.source); - this.code = await this.getSourceFromFile(this.source); - createWidget(interpreter, this.name, this.code, this.klass); - } - - async getSourceFromFile(s: string): Promise { - const response = await robustFetch(s); - return await response.text(); - } - } - - return PyWidget; -} diff --git a/pyscriptjs/src/exceptions.ts b/pyscriptjs/src/exceptions.ts deleted file mode 100644 index 540f19c10d8..00000000000 --- a/pyscriptjs/src/exceptions.ts +++ /dev/null @@ -1,104 +0,0 @@ -const CLOSEBUTTON = ``; - -type MessageType = 'text' | 'html'; - -/* -These error codes are used to identify the type of error that occurred. -The convention is: -* PY0 - errors that occur when fetching -* PY1 - errors that occur in config -* Py2 - errors that occur in plugins -* PY9 - Deprecation errors -*/ - -export enum ErrorCode { - GENERIC = 'PY0000', // Use this only for development then change to a more specific error code - FETCH_ERROR = 'PY0001', - FETCH_NAME_ERROR = 'PY0002', - // Currently these are created depending on error code received from fetching - FETCH_UNAUTHORIZED_ERROR = 'PY0401', - FETCH_FORBIDDEN_ERROR = 'PY0403', - FETCH_NOT_FOUND_ERROR = 'PY0404', - FETCH_SERVER_ERROR = 'PY0500', - FETCH_UNAVAILABLE_ERROR = 'PY0503', - BAD_CONFIG = 'PY1000', - MICROPIP_INSTALL_ERROR = 'PY1001', - BAD_PLUGIN_FILE_EXTENSION = 'PY2000', - NO_DEFAULT_EXPORT = 'PY2001', - TOP_LEVEL_AWAIT = 'PY9000', -} - -export class UserError extends Error { - messageType: MessageType; - errorCode: ErrorCode; - /** - * `isinstance` doesn't work correctly across multiple realms. - * Hence, `$$isUserError` flag / marker is used to identify a `UserError`. - */ - $$isUserError: boolean; - - constructor(errorCode: ErrorCode, message: string, t: MessageType = 'text') { - super(message); - this.errorCode = errorCode; - this.name = 'UserError'; - this.messageType = t; - this.message = `(${errorCode}): ${message}`; - this.$$isUserError = true; - } -} - -export class FetchError extends UserError { - errorCode: ErrorCode; - constructor(errorCode: ErrorCode, message: string) { - super(errorCode, message); - this.name = 'FetchError'; - } -} - -export class InstallError extends UserError { - errorCode: ErrorCode; - constructor(errorCode: ErrorCode, message: string) { - super(errorCode, message); - this.name = 'InstallError'; - } -} - -export function _createAlertBanner( - message: string, - level: 'error' | 'warning' = 'error', - messageType: MessageType = 'text', - logMessage = true, -) { - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - switch (`log-${level}-${logMessage}`) { - case 'log-error-true': - console.error(message); - break; - case 'log-warning-true': - console.warn(message); - break; - } - - const banner = document.createElement('div'); - banner.className = `alert-banner py-${level}`; - - if (messageType === 'html') { - banner.innerHTML = message; - } else { - banner.textContent = message; - } - - if (level === 'warning') { - const closeButton = document.createElement('button'); - - closeButton.id = 'alert-close-button'; - closeButton.addEventListener('click', () => { - banner.remove(); - }); - closeButton.innerHTML = CLOSEBUTTON; - - banner.appendChild(closeButton); - } - - document.body.prepend(banner); -} diff --git a/pyscriptjs/src/interpreter_client.ts b/pyscriptjs/src/interpreter_client.ts deleted file mode 100644 index 82b2fb449be..00000000000 --- a/pyscriptjs/src/interpreter_client.ts +++ /dev/null @@ -1,95 +0,0 @@ -import type { AppConfig } from './pyconfig'; -import { RemoteInterpreter } from './remote_interpreter'; -import type { PyProxyDict, PyProxy } from 'pyodide'; -import { getLogger } from './logger'; -import type { Stdio } from './stdio'; -import * as Synclink from 'synclink'; - -const logger = getLogger('pyscript/interpreter'); - -/* -InterpreterClient class is responsible to request code execution -(among other things) from a `RemoteInterpreter` -*/ -export class InterpreterClient extends Object { - _remote: Synclink.Remote; - _unwrapped_remote: RemoteInterpreter; - config: AppConfig; - /** - * global symbols table for the underlying interface. - * */ - globals: Synclink.Remote; - stdio: Stdio; - - constructor( - config: AppConfig, - stdio: Stdio, - remote: Synclink.Remote, - unwrapped_remote: RemoteInterpreter, - ) { - super(); - this.config = config; - this._remote = remote; - this._unwrapped_remote = unwrapped_remote; - this.stdio = stdio; - } - - /** - * initializes the remote interpreter, which further loads the underlying - * interface. - * */ - async initializeRemote(): Promise { - await this._unwrapped_remote.loadInterpreter(this.config, this.stdio); - // await this._remote.loadInterpreter(this.config, Synclink.proxy(this.stdio)); - this.globals = this._remote.globals; - } - - /** - * Run user Python code. See also the _run_pyscript docstring. - * - * The result is wrapped in an object to avoid accidentally awaiting a - * Python Task or Future returned as the result of the computation. - * - * @param code the code to run - * @param id The id for the default display target (or undefined if no - * default display target). - * @returns Either: - * 1. An Object of the form {result: the_result} if the result is - * serializable (or transferable), or - * 2. a Synclink Proxy wrapping an object of this if the result is not - * serializable. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async run(code: string, id?: string): Promise<{ result: any }> { - return this._remote.pyscript_py._run_pyscript(code, id); - } - - /** - * Same as run, but Python exceptions are not propagated: instead, they - * are logged to the console. - * - * This is a bad API and should be killed/refactored/changed eventually, - * but for now we have code which relies on it. - * */ - async runButDontRaise(code: string): Promise { - let result: unknown; - try { - result = (await this.run(code)).result; - } catch (error: unknown) { - logger.error('Error:', error); - } - return result; - } - - async pyimport(mod_name: string): Promise> { - return this._remote.pyimport(mod_name); - } - - async mkdir(path: string) { - await this._remote.FS.mkdir(path); - } - - async writeFile(path: string, content: string) { - await this._remote.FS.writeFile(path, content, { encoding: 'utf8' }); - } -} diff --git a/pyscriptjs/src/logger.ts b/pyscriptjs/src/logger.ts deleted file mode 100644 index a31ecef8d2b..00000000000 --- a/pyscriptjs/src/logger.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* Very simple logger interface. - - Each module is expected to create its own logger by doing e.g.: - - const logger = getLogger('my-prefix'); - - and then use it instead of console: - - logger.info('hello', 'world'); - logger.warn('...'); - logger.error('...'); - - The logger automatically adds the prefix "[my-prefix]" to all logs. - E.g., the above call would print: - - [my-prefix] hello world - - logger.log is intentionally omitted. The idea is that PyScript should not - write anything to console.log, to leave it free for the user. - - Currently, the logger does not to anything more than that. In the future, - we might want to add additional features such as the ability to - enable/disable logs on a global or per-module basis. -*/ - -interface Logger { - debug(message: string, ...args: unknown[]): void; - info(message: string, ...args: unknown[]): void; - warn(message: string, ...args: unknown[]): void; - error(message: string | Error, ...args: unknown[]): void; -} - -const _cache = new Map(); - -function getLogger(prefix: string): Logger { - let logger = _cache.get(prefix); - if (logger === undefined) { - logger = _makeLogger(prefix); - _cache.set(prefix, logger); - } - return logger; -} - -function _makeLogger(prefix: string): Logger { - prefix = `[${prefix}] `; - - function make(level: 'info' | 'debug' | 'warn' | 'error') { - const out_fn = console[level].bind(console) as typeof console.log; - function fn(fmt: string, ...args: unknown[]) { - out_fn(prefix + fmt, ...args); - } - return fn; - } - - // 'log' is intentionally omitted - const debug = make('debug'); - const info = make('info'); - const warn = make('warn'); - const error = make('error'); - - return { debug, info, warn, error }; -} - -export { getLogger }; diff --git a/pyscriptjs/src/main.ts b/pyscriptjs/src/main.ts deleted file mode 100644 index 88bdb3bf3ed..00000000000 --- a/pyscriptjs/src/main.ts +++ /dev/null @@ -1,443 +0,0 @@ -import './styles/pyscript_base.css'; - -import { loadConfigFromElement } from './pyconfig'; -import type { AppConfig } from './pyconfig'; -import { InterpreterClient } from './interpreter_client'; -import { version } from './version'; -import { PluginManager, define_custom_element, Plugin } from './plugin'; -import { make_PyScript, initHandlers, mountElements } from './components/pyscript'; -import { getLogger } from './logger'; -import { showWarning, globalExport, createLock } from './utils'; -import { calculateFetchPaths } from './plugins/calculateFetchPaths'; -import { createCustomElements } from './components/elements'; -import { UserError, ErrorCode, _createAlertBanner } from './exceptions'; -import { type Stdio, StdioMultiplexer, DEFAULT_STDIO } from './stdio'; -import { PyTerminalPlugin } from './plugins/pyterminal'; -import { SplashscreenPlugin } from './plugins/splashscreen'; -import { ImportmapPlugin } from './plugins/importmap'; -import { StdioDirector as StdioDirector } from './plugins/stdiodirector'; -import type { PyProxy } from 'pyodide'; -import { RemoteInterpreter } from './remote_interpreter'; -import { robustFetch } from './fetch'; -import * as Synclink from 'synclink'; - -const logger = getLogger('pyscript/main'); - -/** - * Monkey patching the error transfer handler to preserve the `$$isUserError` - * marker so as to detect `UserError` subclasses in the error handling code. - */ -const throwHandler = Synclink.transferHandlers.get('throw') as Synclink.TransferHandler< - { value: unknown }, - { value: { $$isUserError: boolean } } ->; -const old_error_transfer_handler = throwHandler.serialize.bind(throwHandler) as typeof throwHandler.serialize; -function new_error_transfer_handler({ value }: { value: { $$isUserError: boolean } }) { - const result = old_error_transfer_handler({ value }); - result[0].value.$$isUserError = value.$$isUserError; - return result; -} -throwHandler.serialize = new_error_transfer_handler; - -/* High-level overview of the lifecycle of a PyScript App: - - 1. pyscript.js is loaded by the browser. PyScriptApp().main() is called - - 2. loadConfig(): search for py-config and compute the config for the app - - 3. (it used to be "show the splashscreen", but now it's a plugin) - - 4. loadInterpreter(): start downloading the actual interpreter (e.g. pyodide.js) - - --- wait until (4) has finished --- - - 5. now the pyodide src is available. Initialize the engine - - 6. setup the environment, install packages - - 6.5: call the Plugin.afterSetup() hook - - 7. connect the py-script web component. This causes the execution of all the - user scripts - - 8. initialize the rest of web components such as py-button, py-repl, etc. - -More concretely: - - - Points 1-4 are implemented sequentially in PyScriptApp.main(). - - - PyScriptApp.loadInterpreter adds a ", -} - - -# these are set by _set_version_info -__version__ = None -version_info = None - - -def _set_version_info(version_from_interpreter: str): - """Sets the __version__ and version_info properties from provided JSON data - Args: - version_from_interpreter (str): A "dotted" representation of the version: - YYYY.MM.m(m).releaselevel - Year, Month, and Minor should be integers; releaselevel can be any string - """ - global __version__ - global version_info - - __version__ = version_from_interpreter - - version_parts = version_from_interpreter.split(".") - year = int(version_parts[0]) - month = int(version_parts[1]) - minor = int(version_parts[2]) - if len(version_parts) > 3: - releaselevel = version_parts[3] - else: - releaselevel = "" - - VersionInfo = namedtuple("version_info", ("year", "month", "minor", "releaselevel")) - version_info = VersionInfo(year, month, minor, releaselevel) - - # we ALSO set PyScript.__version__ and version_info for backwards - # compatibility. Should be killed eventually. - PyScript.__version__ = __version__ - PyScript.version_info = version_info - - -class HTML: - """ - Wrap a string so that display() can render it as plain HTML - """ - - def __init__(self, html): - self._html = html - - def _repr_html_(self): - return self._html - - -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 html.escape(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: - js.console.warn( - 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 - - -def run_until_complete(f): - _ = loop.run_until_complete(f) - - -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) - js.console.warn( - dedent( - """PyScript Deprecation Warning: PyScript.write is - marked as deprecated and will be removed sometime soon. Please, use - Element().write instead.""" - ) - ) - - -@contextmanager -def _display_target(target_id): - get_current_display_target._id = target_id - try: - yield - finally: - get_current_display_target._id = None - - -def get_current_display_target(): - return get_current_display_target._id - - -get_current_display_target._id = None - - -def display(*values, target=None, append=True): - if target is None: - target = get_current_display_target() - if target is None: - raise Exception( - "Implicit target not allowed here. Please use display(..., target=...)" - ) - for v in values: - Element(target).write(v, append=append) - - -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 = js.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): - html, mime_type = format_mime(value) - if html == "\n": - return - - if append: - child = js.document.createElement("div") - self.element.appendChild(child) - - if append and self.element.children: - out_element = self.element.children[-1] - else: - out_element = self.element - - if mime_type in ("application/javascript", "text/html"): - script_element = js.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: - js.console.warn(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 - to.element.after(clone) - else: - # 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): - if isinstance(classname, list): - for cl in classname: - self.element.classList.add(cl) - else: - 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 = js.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): - new_child = create("div", self._id, "py-li-element") - new_child._element.innerHTML = dedent( - f""" - - """ - ) - 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("py-li-element") - 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): - 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 = js.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): - 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 TopLevelAsyncFinder(ast.NodeVisitor): - def is_source_top_level_await(self, source): - self.async_found = False - node = ast.parse(source) - self.generic_visit(node) - return self.async_found - - def visit_Await(self, node): - self.async_found = True - - def visit_AsyncFor(self, node): - self.async_found = True - - def visit_AsyncWith(self, node): - self.async_found = True - - def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef): - pass # Do not visit children of async function defs - - -def uses_top_level_await(source: str) -> bool: - return TopLevelAsyncFinder().is_source_top_level_await(source) - - -class Plugin: - def __init__(self, name=None): - if not name: - name = self.__class__.__name__ - - self.name = name - self._custom_elements = [] - self.app = None - - def init(self, app): - self.app = app - - def configure(self, config): - pass - - def afterSetup(self, interpreter): - pass - - def afterStartup(self, interpreter): - pass - - def beforePyScriptExec(self, interpreter, src, pyScriptTag): - pass - - def afterPyScriptExec(self, interpreter, src, pyScriptTag, result): - pass - - def beforePyReplExec(self, interpreter, src, outEl, pyReplTag): - pass - - def afterPyReplExec(self, interpreter, src, outEl, pyReplTag, result): - pass - - def onUserError(self, error): - pass - - def register_custom_element(self, tag): - """ - Decorator to register a new custom element as part of a Plugin and associate - tag to it. Internally, it delegates the registration to the PyScript internal - [JS] plugin manager, who actually creates the JS custom element that can be - attached to the page and instantiate an instance of the class passing the custom - element to the plugin constructor. - - Exammple: - >> plugin = Plugin("PyTutorial") - >> @plugin.register_custom_element("py-tutor") - >> class PyTutor: - >> def __init__(self, element): - >> self.element = element - """ - # TODO: Ideally would be better to use the logger. - js.console.info(f"Defining new custom element {tag}") - - def wrapper(class_): - # TODO: this is very pyodide specific but will have to do - # until we have JS interface that works across interpreters - define_custom_element(tag, create_proxy(class_)) # noqa: F821 - - self._custom_elements.append(tag) - return create_proxy(wrapper) - - -class DeprecatedGlobal: - """ - Proxy for globals which are deprecated. - - The intendend usage is as follows: - - # in the global namespace - Element = pyscript.DeprecatedGlobal('Element', pyscript.Element, "...") - console = pyscript.DeprecatedGlobal('console', js.console, "...") - ... - - The proxy forwards __getattr__ and __call__ to the underlying object, and - emit a warning on the first usage. - - This way users see a warning only if they actually access the top-level - name. - """ - - def __init__(self, name, obj, message): - self.__name = name - self.__obj = obj - self.__message = message - self.__warning_already_shown = False - - def __repr__(self): - return f"" - - def _show_warning(self, message): - """ - NOTE: this is overridden by unit tests - """ - # this showWarning is implemented in js and injected into this - # namespace by main.ts - showWarning(message, "html") # noqa: F821 - - def _show_warning_maybe(self): - if self.__warning_already_shown: - return - self._show_warning(self.__message) - self.__warning_already_shown = True - - def __getattr__(self, attr): - self._show_warning_maybe() - return getattr(self.__obj, attr) - - def __call__(self, *args, **kwargs): - self._show_warning_maybe() - return self.__obj(*args, **kwargs) - - def __iter__(self): - self._show_warning_maybe() - return iter(self.__obj) - - def __getitem__(self, key): - self._show_warning_maybe() - return self.__obj[key] - - def __setitem__(self, key, value): - self._show_warning_maybe() - self.__obj[key] = value - - -class PyScript: - """ - This class is deprecated since 2022.12.1. - - All its old functionalities are available as module-level functions. This - class should be killed eventually. - """ - - loop = loop - - @staticmethod - def run_until_complete(f): - run_until_complete(f) - - @staticmethod - def write(element_id, value, append=False, exec_id=0): - write(element_id, value, append, exec_id) - - -def _install_deprecated_globals_2022_12_1(ns): - """ - Install into the given namespace all the globals which have been - deprecated since the 2022.12.1 release. Eventually they should be killed. - """ - - def deprecate(name, obj, instead): - message = f"Direct usage of {name} is deprecated. " + instead - ns[name] = DeprecatedGlobal(name, obj, message) - - # function/classes defined in pyscript.py ===> pyscript.XXX - pyscript_names = [ - "PyItemTemplate", - "PyListTemplate", - "PyWidgetTheme", - "add_classes", - "create", - "loop", - ] - for name in pyscript_names: - deprecate( - name, globals()[name], f"Please use pyscript.{name} instead." - ) - - # stdlib modules ===> import XXX - stdlib_names = [ - "asyncio", - "base64", - "io", - "sys", - "time", - "datetime", - "pyodide", - "micropip", - ] - for name in stdlib_names: - obj = __import__(name) - deprecate(name, obj, f"Please use import {name} instead.") - - # special case - deprecate( - "dedent", dedent, "Please use from textwrap import dedent instead." - ) - - # these are names that used to leak in the globals but they are just - # implementation details. People should not use them. - private_names = [ - "eval_formatter", - "format_mime", - "identity", - "render_image", - "MIME_RENDERERS", - "MIME_METHODS", - ] - for name in private_names: - obj = globals()[name] - message = ( - f"{name} is deprecated. " - "This is a private implementation detail of pyscript. " - "You should not use it." - ) - ns[name] = DeprecatedGlobal(name, obj, message) - - # these names are available as js.XXX - for name in ["document", "console"]: - obj = getattr(js, name) - deprecate(name, obj, f"Please use js.{name} instead.") - - # PyScript is special, use a different message - message = ( - "The PyScript object is deprecated. " - "Please use pyscript instead." - ) - ns["PyScript"] = DeprecatedGlobal("PyScript", PyScript, message) - - -def _run_pyscript(code: str, id: str = None) -> JsProxy: - """Execute user code inside context managers. - - Uses the __main__ global namespace. - - The output is wrapped inside a JavaScript object since an object is not - thenable. This is so we do not accidentally `await` the result of the python - execution, even if it's awaitable (Future, Task, etc.) - - Parameters - ---------- - code : - The code to run - - id : - The id for the default display target (or None if no default display target). - - Returns - ------- - A Js Object of the form {result: the_result} - """ - import __main__ - - with _display_target(id): - result = eval_code(code, globals=__main__.__dict__) - - return js.Object.new(result=result) diff --git a/pyscriptjs/src/python_package.ts b/pyscriptjs/src/python_package.ts deleted file mode 100644 index beac1ff78a9..00000000000 --- a/pyscriptjs/src/python_package.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file exists because I can only convince jest to mock real file system -// files, not fake modules. This confuses me because jest.mock has a virtual -// option for mocking things that don't live in the file system but it doesn't -// seem to work. - -// @ts-ignore -import python_package from 'pyscript_python_package.esbuild_injected.json'; -declare const python_package: { dirs: string[]; files: [string, string][] }; -export { python_package }; diff --git a/pyscriptjs/src/remote_interpreter.ts b/pyscriptjs/src/remote_interpreter.ts deleted file mode 100644 index 3e2bba27479..00000000000 --- a/pyscriptjs/src/remote_interpreter.ts +++ /dev/null @@ -1,279 +0,0 @@ -import type { AppConfig } from './pyconfig'; -import { getLogger } from './logger'; -import { Stdio } from './stdio'; -import { InstallError, ErrorCode } from './exceptions'; -import { robustFetch } from './fetch'; -import type { loadPyodide as loadPyodideDeclaration, PyodideInterface, PyProxy, PyProxyDict } from 'pyodide'; -import type { ProxyMarked } from 'synclink'; -import * as Synclink from 'synclink'; - -import { python_package } from './python_package'; - -declare const loadPyodide: typeof loadPyodideDeclaration; -const logger = getLogger('pyscript/pyodide'); - -export type InterpreterInterface = (PyodideInterface & ProxyMarked) | null; - -interface Micropip extends PyProxy { - install(packageName: string | string[]): Promise; -} - -type FSInterface = { - writeFile(path: string, data: Uint8Array | string, options?: { canOwn?: boolean; encoding?: string }): void; - mkdirTree(path: string): void; - mkdir(path: string): void; -} & ProxyMarked; - -type PATHFSInterface = { - resolve(path: string): string; -} & ProxyMarked; - -type PATHInterface = { - dirname(path: string): string; -} & ProxyMarked; - -type PyScriptPyModule = ProxyMarked & { - _set_version_info(ver: string): void; - uses_top_level_await(code: string): boolean; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _run_pyscript(code: string, display_target_id?: string): { result: any }; -}; - -/* -RemoteInterpreter class is responsible to process requests from the -`InterpreterClient` class -- these can be requests for installation of -a package, executing code, etc. - -Currently, the only interpreter available is Pyodide as indicated by the -`InterpreterInterface` type above. This serves as a Union of types of -different interpreters which will be added in near future. - -Methods available handle loading of the interpreter, initialization, -running code, loading and installation of packages, loading from files etc. - -The class will be turned `abstract` in future, to support more runtimes -such as MicroPython. - */ -export class RemoteInterpreter extends Object { - src: string; - interface: InterpreterInterface; - FS: FSInterface; - PATH: PATHInterface; - PATH_FS: PATHFSInterface; - pyscript_py: PyScriptPyModule; - - globals: PyProxyDict & ProxyMarked; - // TODO: Remove this once `runtimes` is removed! - interpreter: InterpreterInterface & ProxyMarked; - - constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js') { - super(); - this.src = src; - } - - /** - * loads the interface for the interpreter and saves an instance of it - * in the `this.interface` property along with calling of other - * additional convenience functions. - * */ - - /** - * Although `loadPyodide` is used below, - * notice that it is not imported i.e. - * import { loadPyodide } from 'pyodide'; - * is not used at the top of this file. - * - * This is because, if it's used, loadPyodide - * behaves mischievously i.e. it tries to load - * `pyodide.asm.js` and `pyodide_py.tar` but - * with paths that are wrong such as: - * - * http://127.0.0.1:8080/build/pyodide_py.tar - * which results in a 404 since `build` doesn't - * contain these files and is clearly the wrong - * path. - */ - async loadInterpreter(config: AppConfig, stdio: Stdio): Promise { - this.interface = Synclink.proxy( - await loadPyodide({ - stdout: (msg: string) => { - // TODO: add syncify when moved to worker - stdio.stdout_writeline(msg); - }, - stderr: (msg: string) => { - stdio.stderr_writeline(msg); - }, - fullStdLib: false, - }), - ); - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - this.FS = this.interface.FS; - // eslint-disable-next-line - this.PATH = (this.interface as any)._module.PATH; - // eslint-disable-next-line - this.PATH_FS = (this.interface as any)._module.PATH_FS; - - // TODO: Remove this once `runtimes` is removed! - this.interpreter = this.interface; - - // Write pyscript package into file system - for (const dir of python_package.dirs) { - this.FS.mkdir('/home/pyodide/' + dir); - } - for (const [path, value] of python_package.files) { - this.FS.writeFile('/home/pyodide/' + path, value); - } - //Refresh the module cache so Python consistently finds pyscript module - this.invalidate_module_path_cache(); - - this.globals = Synclink.proxy(this.interface.globals as PyProxyDict); - logger.info('importing pyscript'); - this.pyscript_py = Synclink.proxy(this.interface.pyimport('pyscript')) as PyProxy & typeof this.pyscript_py; - - if (config.packages) { - logger.info('Found packages in configuration to install. Loading micropip...'); - await this.loadPackage('micropip'); - } - logger.info('pyodide loaded and initialized'); - this.pyscript_py._run_pyscript('print("Python initialization complete")'); - } - - /** - * delegates the registration of JS modules to - * the underlying interface. - * */ - registerJsModule(name: string, module: object): void { - this.interface.registerJsModule(name, module); - } - - /** - * delegates the loading of packages to - * the underlying interface. - * */ - async loadPackage(names: string | string[]): Promise { - logger.info(`pyodide.loadPackage: ${names.toString()}`); - // the new way in v0.22.1 is to pass it as a dict of options i.e. - // { messageCallback: logger.info.bind(logger), errorCallback: logger.info.bind(logger) } - // but one of our tests tries to use a locally downloaded older version of pyodide - // for which the signature of `loadPackage` accepts the above params as args i.e. - // the call uses `logger.info.bind(logger), logger.info.bind(logger)`. - const messageCallback = logger.info.bind(logger) as typeof logger.info; - if (this.interpreter.version.startsWith('0.22')) { - await this.interface.loadPackage(names, { - messageCallback, - errorCallback: messageCallback, - }); - } else { - // @ts-expect-error Types don't include this deprecated call signature - await this.interface.loadPackage(names, messageCallback, messageCallback); - } - } - - /** - * delegates the installation of packages - * (using a package manager, which can be specific to - * the interface) to the underlying interface. - * - * For Pyodide, we use `micropip` - * */ - async installPackage(package_name: string | string[]): Promise { - if (package_name.length > 0) { - logger.info(`micropip install ${package_name.toString()}`); - - const micropip = this.interface.pyimport('micropip') as Micropip; - try { - await micropip.install(package_name); - micropip.destroy(); - } catch (err) { - const e = err as Error; - let fmt_names: string; - if (Array.isArray(package_name)) { - fmt_names = package_name.join(', '); - } else { - fmt_names = package_name; - } - let exceptionMessage = `Unable to install package(s) '${fmt_names}'.`; - - // If we can't fetch `package_name` micropip.install throws a huge - // Python traceback in `e.message` this logic is to handle the - // error and throw a more sensible error message instead of the - // huge traceback. - if (e.message.includes("Can't find a pure Python 3 wheel")) { - exceptionMessage += - ` Reason: Can't find a pure Python 3 Wheel for package(s) '${fmt_names}'.` + - `See: https://pyodide.org/en/stable/usage/faq.html#micropip-can-t-find-a-pure-python-wheel ` + - `for more information.`; - } else if (e.message.includes("Can't fetch metadata")) { - exceptionMessage += - ' Unable to find package in PyPI. ' + - 'Please make sure you have entered a correct package name.'; - } else { - exceptionMessage += - ` Reason: ${e.message}. Please open an issue at ` + - `https://github.com/pyscript/pyscript/issues/new if you require help or ` + - `you think it's a bug.`; - } - - logger.error(e); - - throw new InstallError(ErrorCode.MICROPIP_INSTALL_ERROR, exceptionMessage); - } - } - } - - /** - * - * @param path : the path in the filesystem - * @param url : the url to be fetched - * - * Given a file available at `url` URL (eg: `http://dummy.com/hi.py`), the - * function downloads the file and saves it to the `path` (eg: - * `a/b/c/foo.py`) on the FS. - * - * Example usage: await loadFromFile(`a/b/c/foo.py`, - * `http://dummy.com/hi.py`) - * - * Write content of `http://dummy.com/hi.py` to `a/b/c/foo.py` - * - * NOTE: The `path` parameter expects to have the `filename` in it i.e. - * `a/b/c/foo.py` is valid while `a/b/c` (i.e. only the folders) are - * incorrect. - * - * The path will be resolved relative to the current working directory, - * which is initially `/home/pyodide`. So by default `a/b.py` will be placed - * in `/home/pyodide/a/b.py`, `../a/b.py` will be placed into `/home/a/b.py` - * and `/a/b.py` will be placed into `/a/b.py`. - */ - async loadFileFromURL(path: string, url: string): Promise { - path = this.PATH_FS.resolve(path); - const dir: string = this.PATH.dirname(path); - this.FS.mkdirTree(dir); - - // `robustFetch` checks for failures in getting a response - const response = await robustFetch(url); - const buffer = await response.arrayBuffer(); - const data = new Uint8Array(buffer); - - this.FS.writeFile(path, data, { canOwn: true }); - } - - /** - * delegates clearing importlib's module path - * caches to the underlying interface - */ - invalidate_module_path_cache(): void { - const importlib = this.interface.pyimport('importlib') as PyProxy & { invalidate_caches(): void }; - importlib.invalidate_caches(); - } - - pyimport(mod_name: string): PyProxy & Synclink.ProxyMarked { - return Synclink.proxy(this.interface.pyimport(mod_name)); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setHandler(func_name: string, handler: any): void { - const pyscript_module = this.interface.pyimport('pyscript'); - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - pyscript_module[func_name] = handler; - } -} diff --git a/pyscriptjs/src/stdio.ts b/pyscriptjs/src/stdio.ts deleted file mode 100644 index 73b95df60a7..00000000000 --- a/pyscriptjs/src/stdio.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { createSingularWarning, escape } from './utils'; - -export interface Stdio { - stdout_writeline: (msg: string) => void; - stderr_writeline: (msg: string) => void; -} - -/** Default implementation of Stdio: stdout and stderr are both sent to the - * console - */ -export const DEFAULT_STDIO: Stdio = { - stdout_writeline: console.log, - stderr_writeline: console.log, -}; - -/** Stdio provider which captures and store the messages. - * Useful for tests. - */ -export class CaptureStdio implements Stdio { - captured_stdout: string; - captured_stderr: string; - - constructor() { - this.reset(); - } - - reset() { - this.captured_stdout = ''; - this.captured_stderr = ''; - } - - stdout_writeline(msg: string) { - this.captured_stdout += msg + '\n'; - } - - stderr_writeline(msg: string) { - this.captured_stderr += msg + '\n'; - } -} - -/** Stdio provider for sending output to DOM element - * specified by ID. Used with "output" keyword. - * - */ -export class TargetedStdio implements Stdio { - source_element: HTMLElement; - source_attribute: string; - capture_stdout: boolean; - capture_stderr: boolean; - - constructor(source_element: HTMLElement, source_attribute: string, capture_stdout = true, capture_stderr = true) { - this.source_element = source_element; - this.source_attribute = source_attribute; - this.capture_stdout = capture_stdout; - this.capture_stderr = capture_stderr; - } - - /** Writes the given msg to an element with a given ID. The ID is the value an attribute - * of the source_element specified by source_attribute. - * Both the element to be targeted and the ID of the element to write to - * are determined at write-time, not when the TargetdStdio object is - * created. This way, if either the 'output' attribute of the HTML tag - * or the ID of the target element changes during execution of the Python - * code, the output is still routed (or not) as expected - * - * @param msg The output to be written - */ - writeline_by_attribute(msg: string) { - const target_id = this.source_element.getAttribute(this.source_attribute); - const target = document.getElementById(target_id); - if (target === null) { - // No matching ID - createSingularWarning( - `${this.source_attribute} = "${target_id}" does not match the id of any element on the page.`, - ); - } else { - msg = escape(msg).replace('\n', '
'); - if (!msg.endsWith('
') && !msg.endsWith('
')) { - msg = msg + '
'; - } - target.innerHTML += msg; - } - } - - stdout_writeline(msg: string) { - if (this.capture_stdout) { - this.writeline_by_attribute(msg); - } - } - - stderr_writeline(msg: string) { - if (this.capture_stderr) { - this.writeline_by_attribute(msg); - } - } -} - -/** Redirect stdio streams to multiple listeners - */ -export class StdioMultiplexer implements Stdio { - _listeners: Stdio[]; - - constructor() { - this._listeners = []; - } - - addListener(obj: Stdio) { - this._listeners.push(obj); - } - - removeListener(obj: Stdio) { - const index = this._listeners.indexOf(obj); - if (index > -1) { - this._listeners.splice(index, 1); - } - } - - stdout_writeline(msg: string) { - for (const obj of this._listeners) obj.stdout_writeline(msg); - } - - stderr_writeline(msg: string) { - for (const obj of this._listeners) obj.stderr_writeline(msg); - } -} diff --git a/pyscriptjs/src/styles/pyscript_base.css b/pyscriptjs/src/styles/pyscript_base.css deleted file mode 100644 index f6edd6a1806..00000000000 --- a/pyscriptjs/src/styles/pyscript_base.css +++ /dev/null @@ -1,349 +0,0 @@ -/* py-config - not a component */ -py-config { - display: none; -} -/* py-{el} - components not defined */ -py-script:not(:defined) { - display: none; -} - -py-repl:not(:defined) { - display: none; -} - -py-title:not(:defined) { - display: none; -} - -py-inputbox:not(:defined) { - display: none; -} - -py-button:not(:defined) { - display: none; -} - -py-box:not(:defined) { - display: none; -} - -html { - font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', - Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; - line-height: 1.5; -} - -.spinner::after { - content: ''; - box-sizing: border-box; - width: 40px; - height: 40px; - position: absolute; - top: calc(40% - 20px); - left: calc(50% - 20px); - border-radius: 50%; -} - -.spinner.smooth::after { - border-top: 4px solid rgba(255, 255, 255, 1); - border-left: 4px solid rgba(255, 255, 255, 1); - border-right: 4px solid rgba(255, 255, 255, 0); - animation: spinner 0.6s linear infinite; -} - -@keyframes spinner { - to { - transform: rotate(360deg); - } -} - -.label { - text-align: center; - width: 100%; - display: block; - color: rgba(255, 255, 255, 0.8); - font-size: 0.8rem; - margin-top: 6rem; -} - -/* Pop-up second layer begin */ - -.py-overlay { - position: fixed; - display: flex; - justify-content: center; - align-items: center; - color: white; - top: 0; - bottom: 0; - left: 0; - right: 0; - background: rgba(0, 0, 0, 0.5); - transition: opacity 500ms; - visibility: hidden; - color: visible; - opacity: 1; -} - -.py-overlay { - visibility: visible; - opacity: 1; -} - -.py-pop-up { - text-align: center; - width: 600px; -} - -.py-pop-up p { - margin: 5px; -} - -.py-pop-up a { - position: absolute; - color: white; - text-decoration: none; - font-size: 200%; - top: 3.5%; - right: 5%; -} - -/* Pop-up second layer end */ -.alert-banner { - position: relative; - padding: 0.5rem 1.5rem 0.5rem 0.5rem; - margin: 5px 0; -} - -.alert-banner p { - margin: 0; -} - -.py-error { - background-color: #ffe9e8; - border: solid; - border-color: #f0625f; - color: #9d041c; -} - -.py-warning { - background-color: rgb(255, 244, 229); - border: solid; - border-color: #ffa016; - color: #794700; -} - -.alert-banner.py-error > #alert-close-button { - color: #9d041c; -} - -.alert-banner.py-warning > #alert-close-button { - color: #794700; -} - -#alert-close-button { - position: absolute; - right: 0.5rem; - top: 0.5rem; - cursor: pointer; - background: transparent; - border: none; -} - -.py-box { - display: flex; - flex-direction: row; - justify-content: flex-start; -} - -.py-box div.py-box-child * { - max-width: 100%; -} - -.py-repl-box { - flex-direction: column; -} - -.py-repl-editor { - --tw-border-opacity: 1; - border-color: rgba(209, 213, 219, var(--tw-border-opacity)); - border-width: 1px; - position: relative; - --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); - --tw-ring-offset-width: 0px; - --tw-ring-offset-color: #fff; - --tw-ring-color: rgba(59, 130, 246, 0.5); - --tw-ring-offset-shadow: 0 0 #0000; - --tw-ring-shadow: 0 0 #0000; - --tw-shadow: 0 0 #0000; - position: relative; - - box-sizing: border-box; - border-width: 1px; - border-style: solid; - border-color: rgb(209, 213, 219); -} - -.editor-box:hover button { - opacity: 1; -} - -.py-repl-run-button { - opacity: 0; - bottom: 0.25rem; - right: 0.25rem; - position: absolute; - padding: 0; - line-height: inherit; - color: inherit; - cursor: pointer; - background-color: transparent; - background-image: none; - -webkit-appearance: button; - text-transform: none; - font-family: inherit; - font-size: 100%; - margin: 0; - text-rendering: auto; - letter-spacing: normal; - word-spacing: normal; - line-height: normal; - text-transform: none; - text-indent: 0px; - text-shadow: none; - display: inline-block; - text-align: center; - align-items: flex-start; - cursor: default; - box-sizing: border-box; - background-color: -internal-light-dark(rgb(239, 239, 239), rgb(59, 59, 59)); - margin: 0em; - padding: 1px 6px; - border: 0; -} - -.py-repl-run-button:hover { - opacity: 1; -} - -.py-title { - text-transform: uppercase; - text-align: center; -} - -.py-title h1 { - font-weight: 700; - font-size: 1.875rem; -} - -.py-input { - padding: 0.5rem; - --tw-border-opacity: 1; - border-color: rgba(209, 213, 219, var(--tw-border-opacity)); - border-width: 1px; - border-radius: 0.25rem; - margin-right: 0.75rem; - border-style: solid; - width: auto; -} - -.py-box input.py-input { - width: -webkit-fill-available; -} - -.central-content { - max-width: 20rem; - margin-left: auto; - margin-right: auto; -} - -input { - text-rendering: auto; - color: -internal-light-dark(black, white); - letter-spacing: normal; - word-spacing: normal; - line-height: normal; - text-transform: none; - text-indent: 0px; - text-shadow: none; - display: inline-block; - text-align: start; - appearance: auto; - -webkit-rtl-ordering: logical; - background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59)); - margin: 0em; - padding: 1px 2px; - border-width: 2px; - border-style: inset; - border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133)); - border-image: initial; -} - -.py-button { - --tw-text-opacity: 1; - color: rgba(255, 255, 255, var(--tw-text-opacity)); - padding: 0.5rem; - --tw-bg-opacity: 1; - background-color: rgba(37, 99, 235, var(--tw-bg-opacity)); - --tw-border-opacity: 1; - border-color: rgba(37, 99, 235, var(--tw-border-opacity)); - border-width: 1px; - border-radius: 0.25rem; - cursor: pointer; -} - -.py-li-element p { - margin: 5px; -} - -.py-li-element p { - display: inline; -} - -button, -input, -optgroup, -select, -textarea { - font-family: inherit; - font-size: 100%; - line-height: 1.15; - margin: 0; -} - -.line-through { - text-decoration: line-through; -} - -/* ===== py-terminal plugin ===== */ -/* XXX: it would be nice if these rules were stored in e.g. pyterminal.css and - bundled together at build time (by rollup?) */ - -.py-terminal { - min-height: 10em; - background-color: black; - color: white; - padding: 0.5rem; - overflow: auto; -} - -.py-terminal-hidden { - display: none; -} - -/* avoid changing the page layout when the terminal is docked and hidden */ -html:has(py-terminal[docked]:not(py-terminal[docked].py-terminal-hidden)) { - padding-bottom: 40vh; -} - -py-terminal[docked] { - position: fixed; - bottom: 0; - width: 100vw; - max-height: 40vh; - overflow: auto; -} - -py-terminal[docked] .py-terminal { - margin: 0; -} diff --git a/pyscriptjs/src/utils.ts b/pyscriptjs/src/utils.ts deleted file mode 100644 index 2f81a2cf902..00000000000 --- a/pyscriptjs/src/utils.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { _createAlertBanner } from './exceptions'; - -export function addClasses(element: HTMLElement, classes: string[]) { - for (const entry of classes) { - element.classList.add(entry); - } -} - -export function removeClasses(element: HTMLElement, classes: string[]) { - for (const entry of classes) { - element.classList.remove(entry); - } -} - -export function escape(str: string): string { - return str.replace(//g, '>'); -} - -export function htmlDecode(input: string): string | null { - const doc = new DOMParser().parseFromString(ltrim(escape(input)), 'text/html'); - return doc.documentElement.textContent; -} - -export 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 => { - return line.match(/^\s*/)?.pop()?.length; - }); - - const k = Math.min(...lengths); - - return k != 0 ? lines.map(line => line.substring(k)).join('\n') : code; -} - -let _uniqueIdCounter = 0; -export function ensureUniqueId(el: HTMLElement) { - if (el.id === '') el.id = `py-internal-${_uniqueIdCounter++}`; -} - -export function showWarning(msg: string, messageType: 'text' | 'html' = 'text'): void { - _createAlertBanner(msg, 'warning', messageType); -} - -export function readTextFromPath(path: string) { - const request = new XMLHttpRequest(); - request.open('GET', path, false); - request.send(); - const returnValue = request.responseText; - - return returnValue; -} - -export function inJest(): boolean { - return typeof process === 'object' && process.env.JEST_WORKER_ID !== undefined; -} - -export function globalExport(name: string, obj: object) { - // attach the given object to the global object, so that it is globally - // visible everywhere. Should be used very sparingly! - - globalThis[name] = obj; -} - -export function getAttribute(el: Element, attr: string): string | null { - if (el.hasAttribute(attr)) { - const value = el.getAttribute(attr); - if (value) { - return value; - } - } - return null; -} - -export function joinPaths(parts: string[], separator = '/') { - const res = parts - .map(function (part) { - return part.trim().replace(/(^[/]*|[/]*$)/g, ''); - }) - .filter(p => p !== '' && p !== '.') - .join(separator || '/'); - if (parts[0].startsWith('/')) { - return '/' + res; - } - return res; -} - -export function createDeprecationWarning(msg: string, elementName: string): void { - createSingularWarning(msg, elementName); -} - -/** Adds a warning banner with content {msg} at the top of the page if - * and only if no banner containing the {sentinelText} already exists. - * If sentinelText is null, the full text of {msg} is used instead - * - * @param msg {string} The full text content of the warning banner to be displayed - * @param sentinelText {string} [null] The text to match against existing warning banners. - * If null, the full text of 'msg' is used instead. - */ -export function createSingularWarning(msg: string, sentinelText: string | null = null): void { - const banners = document.getElementsByClassName('alert-banner py-warning'); - let bannerCount = 0; - for (const banner of banners) { - if (banner.innerHTML.includes(sentinelText ? sentinelText : msg)) { - bannerCount++; - } - } - if (bannerCount == 0) { - _createAlertBanner(msg, 'warning'); - } -} - -/** - * @returns A new asynchronous lock - * @private - */ -export function createLock(): () => Promise<() => void> { - // This is a promise that is resolved when the lock is open, not resolved when lock is held. - let _lock = Promise.resolve(); - - /** - * Acquire the async lock - * @returns A zero argument function that releases the lock. - * @private - */ - async function acquireLock() { - const old_lock = _lock; - let releaseLock: () => void; - _lock = new Promise(resolve => (releaseLock = resolve)); - await old_lock; - return releaseLock; - } - return acquireLock; -} diff --git a/pyscriptjs/src/version.ts b/pyscriptjs/src/version.ts deleted file mode 100644 index 28ec30db4aa..00000000000 --- a/pyscriptjs/src/version.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * @fileoverview Version of pyscript - * The version is based on calver which contains YEAR.MONTH.DAY.MODIFIER. - * The Modifier can be an optional text tag, such as "dev", "rc", etc. - * - * We are adding this file because we can't add version in main.js due to - * circular imports. - */ - -export const version = '2022.12.1.dev'; diff --git a/pyscriptjs/tests/integration/__init__.py b/pyscriptjs/tests/integration/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/pyscriptjs/tests/integration/conftest.py b/pyscriptjs/tests/integration/conftest.py deleted file mode 100644 index 2fe14436a31..00000000000 --- a/pyscriptjs/tests/integration/conftest.py +++ /dev/null @@ -1,169 +0,0 @@ -import shutil -import threading -from http.server import HTTPServer as SuperHTTPServer -from http.server import SimpleHTTPRequestHandler - -import pytest - -from .support import Logger - - -def pytest_cmdline_main(config): - """ - If we pass --clear-http-cache, we don't enter the main pytest logic, but - use our custom main instead - """ - - def mymain(config, session): - print() - print("-" * 20, "SmartRouter HTTP cache", "-" * 20) - # unfortunately pytest-cache doesn't offer a public API to selectively - # clear the cache, so we need to peek its internal. The good news is - # that pytest-cache is very old, stable and robust, so it's likely - # that this won't break anytime soon. - cache = config.cache - base = cache._cachedir.joinpath(cache._CACHE_PREFIX_VALUES, "pyscript") - if not base.exists(): - print("No cache found, nothing to do") - return 0 - # - print("Requests found in the cache:") - for f in base.rglob("*"): - if f.is_file(): - # requests are saved in dirs named pyscript/http:/foo/bar, let's turn - # them into a proper url - url = str(f.relative_to(base)) - url = url.replace(":/", "://") - print(" ", url) - shutil.rmtree(base) - print("Cache cleared") - return 0 - - if config.option.clear_http_cache: - from _pytest.main import wrap_session - - return wrap_session(config, mymain) - return None - - -def pytest_configure(config): - """ - THIS IS A WORKAROUND FOR A pytest QUIRK! - - At the moment of writing this conftest defines two new options, --dev and - --no-fake-server, but because of how pytest works, they are available only - if this is the "root conftest" for the test session. - - This means that if you are in the pyscriptjs directory: - - $ py.test # does NOT work - $ py.test tests/integration/ # works - - This happens because there is also test py-unit directory, so in the first - case the "root conftest" would be tests/conftest.py (which doesn't exist) - instead of this. - - There are various workarounds, but for now we can just detect it and - inform the user. - - Related StackOverflow answer: https://stackoverflow.com/a/51733980 - """ - if not hasattr(config.option, "dev"): - msg = """ - Running a bare "pytest" command from the pyscriptjs directory - is not supported. Please use one of the following commands: - - pytest tests/integration - - pytest tests/py-unit - - pytest tests/* - - cd tests/integration; pytest - """ - pytest.fail(msg) - else: - if config.option.dev: - config.option.headed = True - config.option.no_fake_server = True - - -@pytest.fixture(scope="session") -def logger(): - return Logger() - - -def pytest_addoption(parser): - parser.addoption( - "--no-fake-server", - action="store_true", - help="Use a real HTTP server instead of http://fakeserver", - ) - parser.addoption( - "--dev", - action="store_true", - help="Automatically open a devtools panel. Implies --headed and --no-fake-server", - ) - parser.addoption( - "--clear-http-cache", - action="store_true", - help="Clear the cache of HTTP requests for SmartRouter", - ) - - -@pytest.fixture(scope="session") -def browser_type_launch_args(request): - """ - Override the browser_type_launch_args defined by pytest-playwright to - support --devtools. - - NOTE: this has been tested with pytest-playwright==0.3.0. It might break - with newer versions of it. - """ - # this calls the "original" fixture defined by pytest_playwright.py - launch_options = request.getfixturevalue("browser_type_launch_args") - if request.config.option.dev: - launch_options["devtools"] = True - return launch_options - - -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(logger): - class MyHTTPRequestHandler(SimpleHTTPRequestHandler): - def end_headers(self): - self.send_my_headers() - SimpleHTTPRequestHandler.end_headers(self) - - def send_my_headers(self): - self.send_header("Cross-Origin-Embedder-Policy", "require-corp") - self.send_header("Cross-Origin-Opener-Policy", "same-origin") - - def log_message(self, fmt, *args): - logger.log("http_server", fmt % args, color="blue") - - host, port = "localhost", 8080 - base_url = f"http://{host}:{port}" - - # serve_Run forever under thread - server = HTTPServer((host, port), MyHTTPRequestHandler) - - 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/integration/support.py b/pyscriptjs/tests/integration/support.py deleted file mode 100644 index 96dcf5b06bd..00000000000 --- a/pyscriptjs/tests/integration/support.py +++ /dev/null @@ -1,789 +0,0 @@ -import dataclasses -import math -import os -import pdb -import re -import sys -import time -import traceback -import urllib -from dataclasses import dataclass - -import py -import pytest -from playwright.sync_api import Error as PlaywrightError - -ROOT = py.path.local(__file__).dirpath("..", "..", "..") -BUILD = ROOT.join("pyscriptjs", "build") - - -@pytest.mark.usefixtures("init") -class PyScriptTest: - """ - Base class to write PyScript integration tests, based on playwright. - - It provides a simple API to generate HTML files and load them in - playwright. - - It also provides a Pythonic API on top of playwright for the most - common tasks; in particular: - - - self.console collects all the JS console.* messages. Look at the doc - of ConsoleMessageCollection for more details. - - - self.check_js_errors() checks that no JS errors have been thrown - - - after each test, self.check_js_errors() is automatically run to ensure - that no JS error passes uncaught. - - - self.wait_for_console waits until the specified message appears in the - console - - - self.wait_for_pyscript waits until all the PyScript tags have been - evaluated - - - self.pyscript_run is the main entry point for pyscript tests: it - creates an HTML page to run the specified snippet. - """ - - # Pyodide always print()s this message upon initialization. Make it - # available to all tests so that it's easiert to check. - PY_COMPLETE = "Python initialization complete" - - @pytest.fixture() - def init(self, request, tmpdir, logger, page): - """ - Fixture to automatically initialize all the tests in this class and its - subclasses. - - The magic is done by the decorator @pytest.mark.usefixtures("init"), - which tells pytest to automatically use this fixture for all the test - method of this class. - - Using the standard pytest behavior, we can request more fixtures: - tmpdir, and page; 'page' is a fixture provided by pytest-playwright. - - Then, we save these fixtures on the self and proceed with more - initialization. The end result is that the requested fixtures are - automatically made available as self.xxx in all methods. - """ - self.testname = request.function.__name__.replace("test_", "") - self.tmpdir = tmpdir - # create a symlink to BUILD inside tmpdir - tmpdir.join("build").mksymlinkto(BUILD) - self.tmpdir.chdir() - self.logger = logger - - if request.config.option.no_fake_server: - # use a real HTTP server. Note that as soon as we request the - # fixture, the server automatically starts in its own thread. - self.http_server = request.getfixturevalue("http_server") - self.router = None - self.is_fake_server = False - else: - # use the internal playwright routing - self.http_server = "http://fake_server" - self.router = SmartRouter( - "fake_server", - cache=request.config.cache, - logger=logger, - usepdb=request.config.option.usepdb, - ) - self.router.install(page) - self.is_fake_server = True - # - self.init_page(page) - # - # this extra print is useful when using pytest -s, else we start printing - # in the middle of the line - print() - # - # if you use pytest --headed you can see the browser page while - # playwright executes the tests, but the page is closed very quickly - # as soon as the test finishes. To avoid that, we automatically start - # a pdb so that we can wait as long as we want. - yield - if request.config.option.headed: - pdb.Pdb.intro = ( - "\n" - "This (Pdb) was started automatically because you passed --headed:\n" - "the execution of the test pauses here to give you the time to inspect\n" - "the browser. When you are done, type one of the following commands:\n" - " (Pdb) continue\n" - " (Pdb) cont\n" - " (Pdb) c\n" - ) - pdb.set_trace() - - def init_page(self, page): - self.page = page - - # set default timeout to 60000 millliseconds from 30000 - page.set_default_timeout(60000) - - self.console = ConsoleMessageCollection(self.logger) - self._js_errors = [] - page.on("console", self._on_console) - page.on("pageerror", self._on_pageerror) - - def run_js(self, code): - """ - allows top level await to be present in the `code` parameter - """ - self.page.evaluate( - """(async () => { - try {%s} - catch(e) { - console.error(e); - } - })();""" - % code - ) - - def teardown_method(self): - # we call check_js_errors on teardown: this means that if there are still - # non-cleared errors, the test will fail. If you expect errors in your - # page and they should not cause the test to fail, you should call - # self.check_js_errors() in the test itself. - self.check_js_errors() - - def _on_console(self, msg): - self.console.add_message(msg.type, msg.text) - - def _on_pageerror(self, error): - self.console.add_message("js_error", error.stack) - self._js_errors.append(error) - - def check_js_errors(self, *expected_messages): - """ - Check whether JS errors were reported. - - expected_messages is a list of strings of errors that you expect they - were raised in the page. They are checked using a simple 'in' check, - equivalent to this: - if expected_message in actual_error_message: - ... - - If an error was expected but not found, it raises - DidNotRaiseJsError(). - - If there are MORE errors other than the expected ones, it raises JsErrors. - - Upon return, all the errors are cleared, so a subsequent call to - check_js_errors will not raise, unless NEW JS errors have been reported - in the meantime. - """ - expected_messages = list(expected_messages) - js_errors = self._js_errors[:] - - for i, msg in enumerate(expected_messages): - for j, error in enumerate(js_errors): - if msg is not None and error is not None and msg in error.message: - # we matched one expected message with an error, remove both - expected_messages[i] = None - js_errors[j] = None - - # if everything is find, now expected_messages and js_errors contains - # only Nones. If they contain non-None elements, it means that we - # either have messages which are expected-but-not-found or errors - # which are found-but-not-expected. - expected_messages = [msg for msg in expected_messages if msg is not None] - js_errors = [err for err in js_errors if err is not None] - self.clear_js_errors() - - if expected_messages: - # expected-but-not-found - raise JsErrorsDidNotRaise(expected_messages, js_errors) - - if js_errors: - # found-but-not-expected - raise JsErrors(js_errors) - - def clear_js_errors(self): - """ - Clear all JS errors. - """ - self._js_errors = [] - - def writefile(self, filename, content): - """ - Very thin helper to write a file in the tmpdir - """ - f = self.tmpdir.join(filename) - f.dirpath().ensure(dir=True) - f.write(content) - - def goto(self, path): - self.logger.reset() - self.logger.log("page.goto", path, color="yellow") - url = f"{self.http_server}/{path}" - self.page.goto(url, timeout=0) - - def wait_for_console(self, text, *, timeout=None, check_js_errors=True): - """ - Wait until the given message appear in the console. - - Note: it must be the *exact* string as printed by e.g. console.log. - If you need more control on the predicate (e.g. if you want to match a - substring), use self.page.expect_console_message directly. - - timeout is expressed in milliseconds. If it's None, it will use - playwright's own default value, which is 30 seconds). - - If check_js_errors is True (the default), it also checks that no JS - errors were raised during the waiting. - """ - - def pred(msg): - return msg.text == text - - try: - with self.page.expect_console_message(pred, timeout=timeout): - pass - finally: - # raise JsError if there were any javascript exception. Note that - # this might happen also in case of a TimeoutError. In that case, - # the JsError will shadow the TimeoutError but this is correct, - # because it's very likely that the console message never appeared - # precisely because of the exception in JS. - if check_js_errors: - self.check_js_errors() - - def wait_for_pyscript(self, *, timeout=None, check_js_errors=True): - """ - Wait until pyscript has been fully loaded. - - Timeout is expressed in milliseconds. If it's None, it will use - playwright's own default value, which is 30 seconds). - - If check_js_errors is True (the default), it also checks that no JS - errors were raised during the waiting. - """ - # this is printed by interpreter.ts:Interpreter.initialize - self.wait_for_console( - "[pyscript/main] PyScript page fully initialized", - timeout=timeout, - check_js_errors=check_js_errors, - ) - # We still don't know why this wait is necessary, but without it - # events aren't being triggered in the tests. - self.page.wait_for_timeout(100) - - def pyscript_run(self, snippet, *, extra_head="", wait_for_pyscript=True): - """ - Main entry point for pyscript tests. - - snippet contains a fragment of HTML which will be put inside a full - HTML document. In particular, the automatically contains the - correct - {extra_head} - - - {snippet} - - - """ - filename = f"{self.testname}.html" - self.writefile(filename, doc) - self.goto(filename) - if wait_for_pyscript: - self.wait_for_pyscript() - - def iter_locator(self, loc): - """ - Helper method to iterate over all the elements which are matched by a - locator, since playwright does not seem to support it natively. - """ - n = loc.count() - elems = [loc.nth(i) for i in range(n)] - return iter(elems) - - def assert_no_banners(self): - """ - Ensure that there are no alert banners on the page, which are used for - errors and warnings. Raise AssertionError if any if found. - """ - loc = self.page.locator(".alert-banner") - n = loc.count() - if n > 0: - text = "\n".join(loc.all_inner_texts()) - raise AssertionError(f"Found {n} alert banners:\n" + text) - - def assert_banner_message(self, expected_message): - """ - Ensure that there is an alert banner on the page with the given message. - Currently it only handles a single. - """ - banner = self.page.wait_for_selector(".alert-banner") - banner_text = banner.inner_text() - - if expected_message not in banner_text: - raise AssertionError( - f"Expected message '{expected_message}' does not " - f"match banner text '{banner_text}'" - ) - return True - - def check_tutor_generated_code(self, modules_to_check=None): - """ - Ensure that the source code viewer injected by the PyTutor plugin - is presend. Raise AssertionError if not found. - - Args: - - modules_to_check(str): iterable with names of the python modules - that have been included in the tutor config - and needs to be checked (if they are included - in the displayed source code) - - Returns: - None - """ - # Given: a page that has a tag - assert self.page.locator("py-tutor").count() - - # EXPECT that" - # - # the page has the "view-code-button" - view_code_button = self.page.locator("#view-code-button") - vcb_count = view_code_button.count() - if vcb_count != 1: - raise AssertionError( - f"Found {vcb_count} code view button. Should have been 1!" - ) - - # the page has the code-section element - code_section = self.page.locator("#code-section") - code_section_count = code_section.count() - code_msg = ( - f"One (and only one) code section should exist. Found: {code_section_count}" - ) - assert code_section_count == 1, code_msg - - pyconfig_tag = self.page.locator("py-config") - code_section_inner_html = code_section.inner_html() - - # the code_section has the index.html section - assert "

index.html

" in code_section_inner_html - - # the section has the tags highlighting the HTML code - assert ( - '
'
-            '    ' in code_section_inner_html
-        )
-
-        # if modules were included, these are also presented in the code section
-        if modules_to_check:
-            for module in modules_to_check:
-                assert f"{module}" in code_section_inner_html
-
-        # the section also includes the config
-        assert "<py-config" in code_section_inner_html
-
-        # the contents of the py-config tag are included in the code section
-        assert pyconfig_tag.inner_html() in code_section_inner_html
-
-        # the code section to be invisible by default (by having the hidden class)
-        assert "code-section-hidden" in code_section.get_attribute("class")
-
-        # once the view_code_button is pressed, the code section becomes visible
-        view_code_button.click()
-        assert "code-section-visible" in code_section.get_attribute("class")
-
-
-# ============== Helpers and utility functions ==============
-
-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
-
-
-def wait_for_render(page, selector, pattern):
-    """
-    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(pattern)
-    py_rendered = False  # Flag to be set to True when condition met
-
-    for _ in range(TEST_ITERATIONS):
-        content = page.inner_html(selector)
-        if re_sub_content.search(content):
-            py_rendered = True
-            break
-        time.sleep(TEST_TIME_INCREMENT)
-
-    assert py_rendered  # nosec
-
-
-class JsErrors(Exception):
-    """
-    Represent one or more exceptions which happened in JS.
-
-    It's a thin wrapper around playwright.sync_api.Error, with two important
-    differences:
-
-    1. it has a better name: if you see JsError in a traceback, it's
-       immediately obvious that it's a JS exception.
-
-    2. Show also the JS stacktrace by default, contrarily to
-       playwright.sync_api.Error
-    """
-
-    def __init__(self, errors):
-        n = len(errors)
-        assert n != 0
-        lines = [f"JS errors found: {n}"]
-        for err in errors:
-            lines.append(self.format_playwright_error(err))
-        msg = "\n".join(lines)
-        super().__init__(msg)
-        self.errors = errors
-
-    @staticmethod
-    def format_playwright_error(error):
-        # apparently, playwright Error.stack contains all the info that we
-        # want: exception name, message and stacktrace. The docs say that
-        # error.stack is optional, so fallback to the standard repr if it's
-        # unavailable.
-        return error.stack or str(error)
-
-
-class JsErrorsDidNotRaise(Exception):
-    """
-    Exception raised by check_js_errors when the expected JS error messages
-    are not found.
-    """
-
-    def __init__(self, expected_messages, errors):
-        lines = ["The following JS errors were expected but could not be found:"]
-        for msg in expected_messages:
-            lines.append("    - " + msg)
-        if errors:
-            lines.append("---")
-            lines.append("The following JS errors were raised but not expected:")
-            for err in errors:
-                lines.append(JsErrors.format_playwright_error(err))
-        msg = "\n".join(lines)
-        super().__init__(msg)
-        self.expected_messages = expected_messages
-        self.errors = errors
-
-
-class ConsoleMessageCollection:
-    """
-    Helper class to collect and expose ConsoleMessage in a Pythonic way.
-
-    Usage:
-
-      console.log.messages: list of ConsoleMessage with type=='log'
-      console.log.lines:    list of strings
-      console.log.text:     the whole text as single string
-
-      console.debug.*       same as above, but with different types
-      console.info.*
-      console.error.*
-      console.warning.*
-
-      console.js_error.*    this is a special category which does not exist in the
-                            browser: it prints uncaught JS exceptions
-
-      console.all.*         same as the individual categories but considering
-                            all messages which were sent to the console
-    """
-
-    @dataclass
-    class Message:
-        type: str  # 'log', 'info', 'debug', etc.
-        text: str
-
-    class View:
-        """
-        Filter console messages by the given msg_type
-        """
-
-        def __init__(self, console, msg_type):
-            self.console = console
-            self.msg_type = msg_type
-
-        @property
-        def messages(self):
-            if self.msg_type is None:
-                return self.console._messages
-            else:
-                return [
-                    msg for msg in self.console._messages if msg.type == self.msg_type
-                ]
-
-        @property
-        def lines(self):
-            return [msg.text for msg in self.messages]
-
-        @property
-        def text(self):
-            return "\n".join(self.lines)
-
-    _COLORS = {
-        "warning": "brown",
-        "error": "darkred",
-        "js_error": "red",
-    }
-
-    def __init__(self, logger):
-        self.logger = logger
-        self._messages = []
-        self.all = self.View(self, None)
-        self.log = self.View(self, "log")
-        self.debug = self.View(self, "debug")
-        self.info = self.View(self, "info")
-        self.error = self.View(self, "error")
-        self.warning = self.View(self, "warning")
-        self.js_error = self.View(self, "js_error")
-
-    def add_message(self, type, text):
-        # log the message: pytest will capture the output and display the
-        # messages if the test fails.
-        msg = self.Message(type=type, text=text)
-        category = f"console.{msg.type}"
-        color = self._COLORS.get(msg.type)
-        self.logger.log(category, msg.text, color=color)
-        self._messages.append(msg)
-
-
-class Logger:
-    """
-    Helper class to log messages to stdout.
-
-    Features:
-      - nice formatted category
-      - keep track of time passed since the last reset
-      - support colors
-
-    NOTE: the (lowercase) logger fixture is defined in conftest.py
-    """
-
-    def __init__(self):
-        self.reset()
-        # capture things like [pyscript/main]
-        self.prefix_regexp = re.compile(r"(\[.+?\])")
-
-    def reset(self):
-        self.start_time = time.time()
-
-    def colorize_prefix(self, text, *, color):
-        # find the first occurrence of something like [pyscript/main] and
-        # colorize it
-        start, end = Color.escape_pair(color)
-        return self.prefix_regexp.sub(rf"{start}\1{end}", text, 1)
-
-    def log(self, category, text, *, color=None):
-        delta = time.time() - self.start_time
-        text = self.colorize_prefix(text, color="teal")
-        line = f"[{delta:6.2f} {category:16}] {text}"
-        if color:
-            line = Color.set(color, line)
-        print(line)
-
-
-class Color:
-    """
-    Helper method to print colored output using ANSI escape codes.
-    """
-
-    black = "30"
-    darkred = "31"
-    darkgreen = "32"
-    brown = "33"
-    darkblue = "34"
-    purple = "35"
-    teal = "36"
-    lightgray = "37"
-    darkgray = "30;01"
-    red = "31;01"
-    green = "32;01"
-    yellow = "33;01"
-    blue = "34;01"
-    fuchsia = "35;01"
-    turquoise = "36;01"
-    white = "37;01"
-
-    @classmethod
-    def set(cls, color, string):
-        start, end = cls.escape_pair(color)
-        return f"{start}{string}{end}"
-
-    @classmethod
-    def escape_pair(cls, color):
-        try:
-            color = getattr(cls, color)
-        except AttributeError:
-            pass
-        start = f"\x1b[{color}m"
-        end = "\x1b[00m"
-        return start, end
-
-
-class SmartRouter:
-    """
-    A smart router to be used in conjunction with playwright.Page.route.
-
-    Main features:
-
-      - it intercepts the requests to a local "fake server" and serve them
-        statically from disk
-
-      - it intercepts the requests to the network and cache the results
-        locally
-    """
-
-    @dataclass
-    class CachedResponse:
-        """
-        We cannot put playwright's APIResponse instances inside _cache, because
-        they are valid only in the context of the same page. As a workaround,
-        we manually save status, headers and body of each cached response.
-        """
-
-        status: int
-        headers: dict
-        body: str
-
-        def asdict(self):
-            return dataclasses.asdict(self)
-
-        @classmethod
-        def fromdict(cls, d):
-            return cls(**d)
-
-    def __init__(self, fake_server, *, cache, logger, usepdb=False):
-        """
-        fake_server: the domain name of the fake server
-        """
-        self.fake_server = fake_server
-        self.cache = cache  # this is pytest-cache, it survives across sessions
-        self.logger = logger
-        self.usepdb = usepdb
-        self.page = None
-        self.requests = []  # (status, kind, url)
-
-    def install(self, page):
-        """
-        Install the smart router on a page
-        """
-        self.page = page
-        self.page.route("**", self.router)
-
-    def router(self, route):
-        """
-        Intercept and fulfill playwright requests.
-
-        NOTE!
-        If we raise an exception inside router, playwright just hangs and the
-        exception seems not to be propagated outside. It's very likely a
-        playwright bug.
-
-        This means that for example pytest doesn't have any chance to
-        intercept the exception and fail in a meaningful way.
-
-        As a workaround, we try to intercept exceptions by ourselves, print
-        something reasonable on the console and abort the request (hoping that
-        the test will fail cleaninly, that's the best we can do). We also try
-        to respect pytest --pdb, for what it's possible.
-        """
-        try:
-            return self._router(route)
-        except Exception:
-            print("***** Error inside Fake_Server.router *****")
-            info = sys.exc_info()
-            print(traceback.format_exc())
-            if self.usepdb:
-                pdb.post_mortem(info[2])
-            route.abort()
-
-    def log_request(self, status, kind, url):
-        self.requests.append((status, kind, url))
-        color = "blue" if status == 200 else "red"
-        self.logger.log("request", f"{status} - {kind} - {url}", color=color)
-
-    def _router(self, route):
-        full_url = route.request.url
-        url = urllib.parse.urlparse(full_url)
-        assert url.scheme in ("http", "https")
-
-        # requests to http://fake_server/ are served from the current dir and
-        # never cached
-        if url.netloc == self.fake_server:
-            self.log_request(200, "fake_server", full_url)
-            assert url.path[0] == "/"
-            relative_path = url.path[1:]
-            if os.path.exists(relative_path):
-                route.fulfill(status=200, path=relative_path)
-            else:
-                route.fulfill(status=404)
-            return
-
-        # network requests might be cached
-        resp = self.fetch_from_cache(full_url)
-        if resp is not None:
-            kind = "CACHED"
-        else:
-            kind = "NETWORK"
-            resp = self.fetch_from_network(route.request)
-            self.save_resp_to_cache(full_url, resp)
-
-        self.log_request(resp.status, kind, full_url)
-        route.fulfill(status=resp.status, headers=resp.headers, body=resp.body)
-
-    def clear_cache(self, url):
-        key = "pyscript/" + url
-        self.cache.set(key, None)
-
-    def save_resp_to_cache(self, url, resp):
-        key = "pyscript/" + url
-        data = resp.asdict()
-        # cache.set encodes it as JSON, and "bytes" are not supported: let's
-        # encode them as latin-1
-        data["body"] = data["body"].decode("latin-1")
-        self.cache.set(key, data)
-
-    def fetch_from_cache(self, url):
-        key = "pyscript/" + url
-        data = self.cache.get(key, None)
-        if data is None:
-            return None
-        # see the corresponding comment in save_resp_to_cache
-        data["body"] = data["body"].encode("latin-1")
-        return self.CachedResponse(**data)
-
-    def fetch_from_network(self, request):
-        # sometimes the network is flaky and if the first request doesn't
-        # work, a subsequent one works. Instead of giving up immediately,
-        # let's try twice
-        try:
-            api_response = self.page.request.fetch(request)
-        except PlaywrightError:
-            # sleep a bit and try again
-            time.sleep(0.5)
-            api_response = self.page.request.fetch(request)
-
-        cached_response = self.CachedResponse(
-            status=api_response.status,
-            headers=api_response.headers,
-            body=api_response.body(),
-        )
-        return cached_response
diff --git a/pyscriptjs/tests/integration/test_00_support.py b/pyscriptjs/tests/integration/test_00_support.py
deleted file mode 100644
index 078bb33f3b6..00000000000
--- a/pyscriptjs/tests/integration/test_00_support.py
+++ /dev/null
@@ -1,418 +0,0 @@
-import re
-import textwrap
-
-import pytest
-from playwright import sync_api
-
-from .support import JsErrors, JsErrorsDidNotRaise, PyScriptTest
-
-
-class TestSupport(PyScriptTest):
-    """
-    These are NOT tests about PyScript.
-
-    They test the PyScriptTest class, i.e. we want to ensure that all the
-    testing machinery that we have works correctly.
-    """
-
-    def test_basic(self):
-        """
-        Very basic test, just to check that we can write, serve and read a simple
-        HTML (no pyscript yet)
-        """
-        doc = """
-        
-          
-            

Hello world

- - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - content = self.page.content() - assert "

Hello world

" in content - - def test_await_with_run_js(self): - self.run_js( - """ - function resolveAfter200MilliSeconds(x) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(x); - }, 200); - }); - } - - const x = await resolveAfter200MilliSeconds(10); - console.log(x); - """ - ) - - assert self.console.log.lines[-1] == "10" - - def test_console(self): - """ - Test that we capture console.log messages correctly. - """ - doc = """ - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - assert len(self.console.all.messages) == 6 - assert self.console.all.lines == [ - "my log 1", - "my debug", - "my info", - "my error", - "my warning", - "my log 2", - ] - - # fmt: off - assert self.console.all.text == textwrap.dedent(""" - my log 1 - my debug - my info - my error - my warning - my log 2 - """).strip() - # fmt: on - - assert self.console.log.lines == ["my log 1", "my log 2"] - assert self.console.debug.lines == ["my debug"] - - def test_check_js_errors_simple(self): - doc = """ - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - with pytest.raises(JsErrors) as exc: - self.check_js_errors() - # check that the exception message contains the error message and the - # stack trace - msg = str(exc.value) - expected = textwrap.dedent( - f""" - JS errors found: 1 - Error: this is an error - at {self.http_server}/mytest.html:.* - """ - ).strip() - assert re.search(expected, msg) - # - # after a call to check_js_errors, the errors are cleared - self.check_js_errors() - # - # JS exceptions are also available in self.console.js_error - assert self.console.js_error.lines[0].startswith("Error: this is an error") - - def test_check_js_errors_expected(self): - doc = """ - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - self.check_js_errors("this is an error") - - def test_check_js_errors_expected_but_didnt_raise(self): - doc = """ - - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - with pytest.raises(JsErrorsDidNotRaise) as exc: - self.check_js_errors( - "this is an error 1", - "this is an error 2", - "this is an error 3", - "this is an error 4", - ) - # - msg = str(exc.value) - expected = textwrap.dedent( - """ - The following JS errors were expected but could not be found: - - this is an error 1 - - this is an error 3 - """ - ).strip() - assert re.search(expected, msg) - - def test_check_js_errors_multiple(self): - doc = """ - - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - with pytest.raises(JsErrors) as exc: - self.check_js_errors() - # - msg = str(exc.value) - expected = textwrap.dedent( - """ - JS errors found: 2 - Error: error 1 - at http://fake_server/mytest.html:.* - Error: error 2 - at http://fake_server/mytest.html:.* - """ - ).strip() - assert re.search(expected, msg) - # - # check that errors are cleared - self.check_js_errors() - - def test_check_js_errors_some_expected_but_others_not(self): - doc = """ - - - - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - with pytest.raises(JsErrors) as exc: - self.check_js_errors("expected 1", "expected 3") - # - msg = str(exc.value) - expected = textwrap.dedent( - """ - JS errors found: 2 - Error: NOT expected 2 - at http://fake_server/mytest.html:.* - Error: NOT expected 4 - at http://fake_server/mytest.html:.* - """ - ).strip() - assert re.search(expected, msg) - - def test_check_js_errors_expected_not_found_but_other_errors(self): - doc = """ - - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - with pytest.raises(JsErrorsDidNotRaise) as exc: - self.check_js_errors("this is not going to be found") - # - msg = str(exc.value) - expected = textwrap.dedent( - """ - The following JS errors were expected but could not be found: - - this is not going to be found - --- - The following JS errors were raised but not expected: - Error: error 1 - at http://fake_server/mytest.html:.* - Error: error 2 - at http://fake_server/mytest.html:.* - """ - ).strip() - assert re.search(expected, msg) - - def test_clear_js_errors(self): - doc = """ - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - self.clear_js_errors() - # self.check_js_errors does not raise, because the errors have been - # cleared - self.check_js_errors() - - def test_wait_for_console(self): - """ - Test that self.wait_for_console actually waits. - If it's buggy, the test will try to read self.console.log BEFORE the - log has been written and it will fail. - """ - doc = """ - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - # we use a timeout of 500ms to give plenty of time to the page to - # actually run the setTimeout callback - self.wait_for_console("Page loaded!", timeout=200) - assert self.console.log.lines[-1] == "Page loaded!" - - def test_wait_for_console_exception_1(self): - """ - Test that if a JS exception is raised while waiting for the console, we - report the exception and not the timeout. - - There are two main cases: - 1. there is an exception and the console message does not appear - 2. there is an exception but the console message appears anyway - - This test checks for case 1. Case 2 is tested by - test_wait_for_console_exception_2 - """ - # case 1: there is an exception and the console message does not appear - doc = """ - - - - - - """ - self.writefile("mytest.html", doc) - # "Page loaded!" will never appear, of course. - self.goto("mytest.html") - with pytest.raises(JsErrors) as exc: - self.wait_for_console("Page loaded!", timeout=200) - assert "this is an error" in str(exc.value) - assert isinstance(exc.value.__context__, sync_api.TimeoutError) - # - # if we use check_js_errors=False, the error are ignored, but we get the - # Timeout anyway - self.goto("mytest.html") - with pytest.raises(sync_api.TimeoutError): - self.wait_for_console("Page loaded!", timeout=200, check_js_errors=False) - # we still got a JsErrors, so we need to manually clear it, else the - # test fails at teardown - self.clear_js_errors() - - def test_wait_for_console_exception_2(self): - """ - See the description in test_wait_for_console_exception_1. - """ - # case 2: there is an exception, but the console message appears - doc = """ - - - - - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - with pytest.raises(JsErrors) as exc: - self.wait_for_console("Page loaded!", timeout=200) - assert "this is an error" in str(exc.value) - # - # with check_js_errors=False, the Error is ignored and the - # wait_for_console succeeds - self.goto("mytest.html") - self.wait_for_console("Page loaded!", timeout=200, check_js_errors=False) - # clear the errors, else the test fails at teardown - self.clear_js_errors() - - def test_iter_locator(self): - doc = """ - - -
foo
-
bar
-
baz
- - - """ - self.writefile("mytest.html", doc) - self.goto("mytest.html") - divs = self.page.locator("div") - assert divs.count() == 3 - texts = [el.inner_text() for el in self.iter_locator(divs)] - assert texts == ["foo", "bar", "baz"] - - def test_smartrouter_cache(self): - if self.router is None: - pytest.skip("Cannot test SmartRouter with --dev") - - # this is not an image but who cares, I just want the browser to make - # an HTTP request - URL = "https://raw.githubusercontent.com/pyscript/pyscript/main/README.md" - doc = f""" - - - - - - """ - self.writefile("mytest.html", doc) - # - self.router.clear_cache(URL) - self.goto("mytest.html") - assert self.router.requests == [ - (200, "fake_server", "http://fake_server/mytest.html"), - (200, "NETWORK", URL), - ] - # - # let's visit the page again, now it should be cached - self.goto("mytest.html") - assert self.router.requests == [ - # 1st visit - (200, "fake_server", "http://fake_server/mytest.html"), - (200, "NETWORK", URL), - # 2nd visit - (200, "fake_server", "http://fake_server/mytest.html"), - (200, "CACHED", URL), - ] - - def test_404(self): - """ - Test that we capture a 404 in loading a page that does not exist. - """ - self.goto("this_url_does_not_exist.html") - assert [ - "Failed to load resource: the server responded with a status of 404 (Not Found)" - ] == self.console.all.lines diff --git a/pyscriptjs/tests/integration/test_01_basic.py b/pyscriptjs/tests/integration/test_01_basic.py deleted file mode 100644 index 4978c785d47..00000000000 --- a/pyscriptjs/tests/integration/test_01_basic.py +++ /dev/null @@ -1,361 +0,0 @@ -import re - -import pytest - -from .support import JsErrors, PyScriptTest - - -class TestBasic(PyScriptTest): - def test_pyscript_hello(self): - self.pyscript_run( - """ - - print('hello pyscript') - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == "hello pyscript" - - def test_python_exception(self): - self.pyscript_run( - """ - - print('hello pyscript') - raise Exception('this is an error') - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert "hello pyscript" in self.console.log.lines - # check that we sent the traceback to the console - tb_lines = self.console.error.lines[-1].splitlines() - assert tb_lines[0] == "[pyexec] Python exception:" - assert tb_lines[1] == "Traceback (most recent call last):" - assert tb_lines[-1] == "Exception: this is an error" - # - # check that we show the traceback in the page. Note that here we - # display the "raw" python traceback, without the "[pyexec] Python - # exception:" line (which is useful in the console, but not for the - # user) - pre = self.page.locator("py-script > pre") - tb_lines = pre.inner_text().splitlines() - assert tb_lines[0] == "Traceback (most recent call last):" - assert tb_lines[-1] == "Exception: this is an error" - - def test_python_exception_in_event_handler(self): - self.pyscript_run( - """ - - - def onclick(): - raise Exception("this is an error inside handler") - - """ - ) - - self.page.locator("button").click() - - ## error in console - tb_lines = self.console.error.lines[-1].splitlines() - assert tb_lines[0] == "[pyexec] Python exception:" - assert tb_lines[1] == "Traceback (most recent call last):" - assert tb_lines[-1] == "Exception: this is an error inside handler" - - ## error in DOM - tb_lines = self.page.locator(".py-error").inner_text().splitlines() - assert tb_lines[0] == "Traceback (most recent call last):" - assert tb_lines[-1] == "Exception: this is an error inside handler" - - def test_execution_in_order(self): - """ - Check that they py-script tags are executed in the same order they are - defined - """ - self.pyscript_run( - """ - import js; js.console.log('one') - js.console.log('two') - js.console.log('three') - js.console.log('four') - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-4:] == [ - "one", - "two", - "three", - "four", - ] - - def test_escaping_of_angle_brackets(self): - """ - Check that py-script tags escape angle brackets - """ - self.pyscript_run( - """ - import js; js.console.log(1<2, 1>2) - js.console.log("
")
- """ - ) - - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-2:] == ["true false", "
"] - - def test_packages(self): - self.pyscript_run( - """ - - # we use asciitree because it's one of the smallest packages - # which are built and distributed with pyodide - packages = ["asciitree"] - - - import js - import asciitree - js.console.log('hello', asciitree.__name__) - - """ - ) - - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-3:] == [ - "Loading asciitree", # printed by pyodide - "Loaded asciitree", # printed by pyodide - "hello asciitree", # printed by us - ] - - def test_non_existent_package(self): - self.pyscript_run( - """ - - packages = ["nonexistendright"] - - """, - wait_for_pyscript=False, - ) - - expected_alert_banner_msg = ( - "(PY1001): Unable to install package(s) 'nonexistendright'. " - "Unable to find package in PyPI. Please make sure you have " - "entered a correct package name." - ) - - alert_banner = self.page.wait_for_selector(".alert-banner") - assert expected_alert_banner_msg in alert_banner.inner_text() - - def test_no_python_wheel(self): - self.pyscript_run( - """ - - packages = ["opsdroid"] - - """, - wait_for_pyscript=False, - ) - - expected_alert_banner_msg = ( - "(PY1001): Unable to install package(s) 'opsdroid'. " - "Reason: Can't find a pure Python 3 Wheel for package(s) 'opsdroid'" - ) - - alert_banner = self.page.wait_for_selector(".alert-banner") - assert expected_alert_banner_msg in alert_banner.inner_text() - - def test_dynamically_add_py_script_tag(self): - self.pyscript_run( - """ - - - """ - ) - self.page.locator("button").click() - - self.page.wait_for_selector("py-terminal") - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == "hello world" - - def test_py_script_src_attribute(self): - self.writefile("foo.py", "print('hello from foo')") - self.pyscript_run( - """ - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == "hello from foo" - - def test_py_script_src_not_found(self): - self.pyscript_run( - """ - - """ - ) - assert self.PY_COMPLETE in self.console.log.lines - - assert "Failed to load resource" in self.console.error.lines[0] - with pytest.raises(JsErrors) as exc: - self.check_js_errors() - - error_msgs = str(exc.value) - - expected_msg = "(PY0404): Fetching from URL foo.py failed with error 404" - - assert expected_msg in error_msgs - assert self.assert_banner_message(expected_msg) - - pyscript_tag = self.page.locator("py-script") - assert pyscript_tag.inner_html() == "" - - def test_js_version(self): - self.pyscript_run( - """ - - - """ - ) - self.page.add_script_tag(content="console.log(pyscript.version)") - - assert ( - re.match(r"\d{4}\.\d{2}\.\d+(\.[a-zA-Z0-9]+)?", self.console.log.lines[-1]) - is not None - ) - - def test_python_version(self): - self.pyscript_run( - """ - - import js - js.console.log(pyscript.__version__) - js.console.log(str(pyscript.version_info)) - - """ - ) - assert ( - re.match(r"\d{4}\.\d{2}\.\d+(\.[a-zA-Z0-9]+)?", self.console.log.lines[-2]) - is not None - ) - assert ( - re.match( - r"version_info\(year=\d{4}, month=\d{2}, " - r"minor=\d+, releaselevel='([a-zA-Z0-9]+)?'\)", - self.console.log.lines[-1], - ) - is not None - ) - - def test_assert_no_banners(self): - """ - Test that the DOM doesn't contain error/warning banners - """ - self.pyscript_run( - """ - - import pyscript - pyscript.showWarning("hello") - pyscript.showWarning("world") - - """ - ) - with pytest.raises(AssertionError, match="Found 2 alert banners"): - self.assert_no_banners() - - def test_deprecated_globals(self): - self.pyscript_run( - """ - - # trigger various warnings - create("div", classes="a b c") - assert sys.__name__ == 'sys' - dedent("") - format_mime("") - assert MIME_RENDERERS['text/html'] is not None - console.log("hello") - PyScript.loop - - -
- """ - ) - banner = self.page.locator(".py-warning") - messages = banner.all_inner_texts() - assert messages == [ - "The PyScript object is deprecated. Please use pyscript instead.", - "Direct usage of console is deprecated. Please use js.console instead.", - "MIME_RENDERERS is deprecated. This is a private implementation detail of pyscript. You should not use it.", # noqa: E501 - "format_mime is deprecated. This is a private implementation detail of pyscript. You should not use it.", # noqa: E501 - "Direct usage of dedent is deprecated. Please use from textwrap import dedent instead.", - "Direct usage of sys is deprecated. Please use import sys instead.", - "Direct usage of create is deprecated. Please use pyscript.create instead.", - ] - - def test_getPySrc_returns_source_code(self): - self.pyscript_run( - """ - - print("hello world!") - - """ - ) - - pyscript_tag = self.page.locator("py-script") - assert pyscript_tag.inner_html() == "" - assert ( - pyscript_tag.evaluate("node => node.getPySrc()") - == 'print("hello world!")\n' - ) - - @pytest.mark.skip(reason="pys-onClick is broken, we should kill it, see #1213") - def test_pys_onClick_shows_deprecation_warning(self): - self.pyscript_run( - """ - - - def myfunc(): - print("hello world") - - - """ - ) - banner = self.page.locator(".alert-banner") - expected_message = ( - "The attribute 'pys-onClick' and 'pys-onKeyDown' are " - "deprecated. Please 'py-click=\"myFunction()\"' or " - "'py-keydown=\"myFunction()\"' instead." - ) - assert banner.inner_text() == expected_message - - def test_py_attribute_without_id(self): - self.pyscript_run( - """ - - - def myfunc(): - print("hello world!") - - """ - ) - btn = self.page.wait_for_selector("button") - btn.click() - assert self.console.log.lines[-1] == "hello world!" - assert self.console.error.lines == [] - - def test_py_mount_shows_deprecation_warning(self): - # last non-deprecated version: 2023.03.1 - self.pyscript_run( - """ -
- """ - ) - banner = self.page.locator(".alert-banner") - expected_message = ( - 'The "py-mount" attribute is deprecated. ' - + "Please add references to HTML Elements manually in your script." - ) - assert banner.inner_text() == expected_message diff --git a/pyscriptjs/tests/integration/test_02_display.py b/pyscriptjs/tests/integration/test_02_display.py deleted file mode 100644 index 670eed6c040..00000000000 --- a/pyscriptjs/tests/integration/test_02_display.py +++ /dev/null @@ -1,404 +0,0 @@ -import base64 -import html -import io -import os -import re - -import numpy as np -from PIL import Image - -from .support import PyScriptTest, wait_for_render - - -class TestOutput(PyScriptTest): - def test_simple_display(self): - self.pyscript_run( - """ - - display('hello world') - - """ - ) - node_list = self.page.query_selector_all(r'[id^="py-internal"]') - pattern = r"
hello world
" - assert re.search(pattern, node_list[0].inner_html()) - assert len(node_list) == 1 - - def test_consecutive_display(self): - self.pyscript_run( - """ - - display('hello 1') - -

hello 2

- - display('hello 3') - - """ - ) - inner_text = self.page.inner_text("body") - lines = inner_text.splitlines() - lines = [line for line in lines if line != ""] # remove empty lines - assert lines == ["hello 1", "hello 2", "hello 3"] - - def test_target_attribute(self): - self.pyscript_run( - """ - - display('hello world', target="mydiv") - -
- """ - ) - mydiv = self.page.locator("#mydiv") - assert mydiv.inner_text() == "hello world" - - def test_consecutive_display_target(self): - self.pyscript_run( - """ - - display('hello 1') - -

hello in between 1 and 2

- - display('hello 2', target="second") - - - display('hello 3') - - """ - ) - inner_text = self.page.inner_text("body") - lines = inner_text.splitlines() - lines = [line for line in lines if line != ""] # remove empty lines - assert lines == ["hello 1", "hello in between 1 and 2", "hello 2", "hello 3"] - - def test_multiple_display_calls_same_tag(self): - self.pyscript_run( - """ - - display('hello') - display('world') - - """ - ) - tag = self.page.locator("py-script") - lines = tag.inner_text().splitlines() - assert lines == ["hello", "world"] - - def test_implicit_target_from_a_different_tag(self): - self.pyscript_run( - """ - - def say_hello(): - display('hello') - - - - say_hello() - - """ - ) - py1 = self.page.locator("#py1") - py2 = self.page.locator("#py2") - assert py1.inner_text() == "" - assert py2.inner_text() == "hello" - - def test_no_implicit_target(self): - self.pyscript_run( - """ - - def display_hello(): - # this fails because we don't have any implicit target - # from event handlers - display('hello world') - - - """ - ) - self.page.locator("text=Click me").click() - ## error in console - tb_lines = self.console.error.lines[-1].splitlines() - assert tb_lines[0] == "[pyexec] Python exception:" - assert tb_lines[1] == "Traceback (most recent call last):" - assert ( - tb_lines[-1] - == "Exception: Implicit target not allowed here. Please use display(..., target=...)" - ) - - text = self.page.text_content("body") - assert "hello world" not in text - - def test_explicit_target_pyscript_tag(self): - self.pyscript_run( - """ - - def display_hello(): - display('hello', target='second-pyscript-tag') - - - display_hello() - - """ - ) - text = self.page.locator("id=second-pyscript-tag").inner_text() - assert text == "hello" - - def test_explicit_target_on_button_tag(self): - self.pyscript_run( - """ - - def display_hello(): - display('hello', target='my-button') - - - """ - ) - self.page.locator("text=Click me").click() - text = self.page.locator("id=my-button").inner_text() - assert "hello" in text - - def test_explicit_different_target_from_call(self): - self.pyscript_run( - """ - - def display_hello(): - display('hello', target='second-pyscript-tag') - - - print('nothing to see here') - - - display_hello() - - """ - ) - text = self.page.locator("id=second-pyscript-tag").all_inner_texts() - assert "hello" in text - - def test_append_true(self): - self.pyscript_run( - """ - - display('hello world', append=True) - - """ - ) - node_list = self.page.query_selector_all(r'[id^="py-internal"]') - pattern = r"
hello world
" - assert re.search(pattern, node_list[0].inner_html()) - assert len(node_list) == 1 - - def test_append_false(self): - self.pyscript_run( - """ - - display('hello world', append=False) - - """ - ) - inner_html = self.page.content() - pattern = r'hello world' - assert re.search(pattern, inner_html) - - def test_display_multiple_values(self): - self.pyscript_run( - """ - - hello = 'hello' - world = 'world' - display(hello, world) - - """ - ) - inner_text = self.page.inner_text("html") - assert inner_text == "hello\nworld" - - def test_display_multiple_append_false(self): - self.pyscript_run( - """ - - display('hello', append=False) - display('world', append=False) - - """ - ) - inner_html = self.page.content() - pattern = r'world' - assert re.search(pattern, inner_html) - - def test_display_multiple_append_false_with_target(self): - self.pyscript_run( - """ -
- - class Circle: - r = 0 - def _repr_svg_(self): - return ( - f'' - f'' - ) - - circle = Circle() - - circle.r += 5 - display(circle, target="circle-div", append=False) - circle.r += 5 - display(circle, target="circle-div", append=False) - - """ - ) - innerhtml = self.page.locator("id=circle-div").inner_html() - assert ( - innerhtml - == '' # noqa: E501 - ) - - def test_display_list_dict_tuple(self): - self.pyscript_run( - """ - - l = ['A', 1, '!'] - d = {'B': 2, 'List': l} - t = ('C', 3, '!') - display(l, d, t) - - """ - ) - inner_text = self.page.inner_text("html") - print(inner_text) - assert ( - inner_text - == "['A', 1, '!']\n{'B': 2, 'List': ['A', 1, '!']}\n('C', 3, '!')" - ) - - def test_display_should_escape(self): - self.pyscript_run( - """ - - display("

hello world

") -
- """ - ) - out = self.page.locator("py-script > div") - assert out.inner_html() == html.escape("

hello world

") - assert out.inner_text() == "

hello world

" - - def test_display_HTML(self): - self.pyscript_run( - """ - - display(HTML("

hello world

")) -
- """ - ) - out = self.page.locator("py-script > div") - assert out.inner_html() == "

hello world

" - assert out.inner_text() == "hello world" - - def test_image_display(self): - self.pyscript_run( - """ - packages = ["matplotlib"] - - import matplotlib.pyplot as plt - xpoints = [3, 6, 9] - ypoints = [1, 2, 3] - plt.plot(xpoints, ypoints) - display(plt) - - """ - ) - wait_for_render(self.page, "*", " - print('print from python') - console.log('print from js') - console.error('error from js'); - - """ - ) - inner_html = self.page.content() - assert re.search("", inner_html) - console_text = self.console.all.lines - assert "print from python" in console_text - assert "print from js" in console_text - assert "error from js" in console_text - - def test_text_HTML_and_console_output(self): - self.pyscript_run( - """ - - display('this goes to the DOM') - print('print from python') - console.log('print from js') - console.error('error from js'); - - """ - ) - inner_text = self.page.inner_text("py-script") - assert inner_text == "this goes to the DOM" - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-2:] == [ - "print from python", - "print from js", - ] - print(self.console.error.lines) - assert self.console.error.lines[-1] == "error from js" - - def test_console_line_break(self): - self.pyscript_run( - """ - - print('1print\\n2print') - print('1console\\n2console') - - """ - ) - console_text = self.console.all.lines - assert console_text.index("1print") == (console_text.index("2print") - 1) - assert console_text.index("1console") == (console_text.index("2console") - 1) - - def test_image_renders_correctly(self): - """This is just a sanity check to make sure that images are rendered correctly.""" - buffer = io.BytesIO() - img = Image.new("RGB", (4, 4), color=(0, 0, 0)) - img.save(buffer, format="PNG") - - b64_img = base64.b64encode(buffer.getvalue()).decode("utf-8") - expected_img_src = f"data:image/png;charset=utf-8;base64,{b64_img}" - - self.pyscript_run( - """ - - packages = ["pillow"] - - -
- - from PIL import Image - img = Image.new("RGB", (4, 4), color=(0, 0, 0)) - display(img, target='img-target', append=False) - - """ - ) - - rendered_img_src = self.page.locator("img").get_attribute("src") - assert rendered_img_src == expected_img_src diff --git a/pyscriptjs/tests/integration/test_03_element.py b/pyscriptjs/tests/integration/test_03_element.py deleted file mode 100644 index aa592fa576a..00000000000 --- a/pyscriptjs/tests/integration/test_03_element.py +++ /dev/null @@ -1,297 +0,0 @@ -from .support import PyScriptTest - - -class TestElement(PyScriptTest): - """Test the Element api""" - - def test_element_id(self): - """Test the element id""" - self.pyscript_run( - """ -
- - from pyscript import Element - el = Element("foo") - print(el.id) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == "foo" - - py_terminal = self.page.wait_for_selector("py-terminal") - assert "foo" in py_terminal.inner_text() - - def test_element_value(self): - """Test the element value""" - self.pyscript_run( - """ - - - from pyscript import Element - el = Element("foo") - print(el.value) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == "bar" - - py_terminal = self.page.wait_for_selector("py-terminal") - assert "bar" in py_terminal.inner_text() - - def test_element_innerHtml(self): - """Test the element innerHtml""" - self.pyscript_run( - """ -
bar
- - from pyscript import Element - el = Element("foo") - print(el.innerHtml) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == "bar" - - py_terminal = self.page.wait_for_selector("py-terminal") - assert "bar" in py_terminal.inner_text() - - def test_element_write_no_append(self): - """Test the element write""" - self.pyscript_run( - """ -
- - from pyscript import Element - el = Element("foo") - el.write("Hello!") - el.write("World!") - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - div = self.page.wait_for_selector("#foo") - assert "World!" in div.inner_text() - - def test_element_write_append(self): - """Test the element write""" - self.pyscript_run( - """ -
- - from pyscript import Element - el = Element("foo") - el.write("Hello!") - el.write("World!", append=True) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - parent_div = self.page.wait_for_selector("#foo") - - assert "Hello!" in parent_div.inner_text() - # confirm that the second write was appended - assert "Hello!
World!
" in parent_div.inner_html() - - def test_element_clear_div(self): - """Test the element clear""" - self.pyscript_run( - """ -
Hello!
- - from pyscript import Element - el = Element("foo") - el.clear() - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - div = self.page.locator("#foo") - assert div.inner_text() == "" - - def test_element_clear_input(self): - """Test the element clear""" - self.pyscript_run( - """ - - - from pyscript import Element - el = Element("foo") - el.clear() - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - input = self.page.wait_for_selector("#foo") - assert input.input_value() == "" - - def test_element_select(self): - """Test the element select""" - self.pyscript_run( - """ - - - from pyscript import Element - el = Element("foo") - el.select("bar", from_content=True) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - select = self.page.wait_for_selector("#foo") - assert select.inner_text() == "Bar" - - def test_element_clone_no_id(self): - """Test the element clone""" - self.pyscript_run( - """ -
Hello!
- - from pyscript import Element - el = Element("foo") - el.clone() - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - divs = self.page.locator("#foo") - assert divs.count() == 2 - assert divs.first.inner_text() == "Hello!" - assert divs.last.inner_text() == "Hello!" - - def test_element_clone_with_id(self): - """Test the element clone""" - self.pyscript_run( - """ -
Hello!
- - from pyscript import Element - el = Element("foo") - el.clone(new_id="bar") - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - divs = self.page.locator("#foo") - assert divs.count() == 1 - assert divs.inner_text() == "Hello!" - - clone = self.page.locator("#bar") - assert clone.inner_text() == "Hello!" - - def test_element_clone_to_other_element(self): - """Test the element clone""" - self.pyscript_run( - """ -
-
- Bond -
-
- James -
-
- - from pyscript import Element - - bond_div = Element("bond") - james_div = Element("james") - - bond_div.clone(new_id="bond-2", to=james_div) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - bond_divs = self.page.locator("#bond") - james_divs = self.page.locator("#james") - bond_2_divs = self.page.locator("#bond-2") - - assert bond_divs.count() == 1 - assert james_divs.count() == 1 - assert bond_2_divs.count() == 1 - - container_div = self.page.locator("#container") - # Make sure that the clones are rendered in the right order - assert container_div.inner_text() == "Bond\nJames\nBond" - - def test_element_remove_single_class(self): - """Test the element remove_class""" - self.pyscript_run( - """ -
- - from pyscript import Element - el = Element("foo") - el.remove_class("bar") - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - div = self.page.locator("#foo") - assert div.get_attribute("class") == "baz" - - def test_element_remove_multiple_classes(self): - """Test the element remove_class""" - self.pyscript_run( - """ -
- - from pyscript import Element - el = Element("foo") - el.remove_class(["foo", "baz", "bar"]) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - div = self.page.locator("#foo") - assert div.get_attribute("class") == "" - - def test_element_add_single_class(self): - """Test the element add_class""" - self.pyscript_run( - """ - -
Hi!
- - from pyscript import Element - el = Element("foo") - el.add_class("red") - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - div = self.page.locator("#foo") - assert div.get_attribute("class") == "red" - - def test_element_add_multiple_class(self): - """Test the element add_class""" - self.pyscript_run( - """ - -
Hi!
- - from pyscript import Element - el = Element("foo") - el.add_class(["red", "bold"]) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - - div = self.page.locator("#foo") - assert div.get_attribute("class") == "red bold" diff --git a/pyscriptjs/tests/integration/test_assets/line_plot.png b/pyscriptjs/tests/integration/test_assets/line_plot.png deleted file mode 100644 index 6909b373ac7..00000000000 Binary files a/pyscriptjs/tests/integration/test_assets/line_plot.png and /dev/null differ diff --git a/pyscriptjs/tests/integration/test_assets/tripcolor.png b/pyscriptjs/tests/integration/test_assets/tripcolor.png deleted file mode 100644 index 898786a26e6..00000000000 Binary files a/pyscriptjs/tests/integration/test_assets/tripcolor.png and /dev/null differ diff --git a/pyscriptjs/tests/integration/test_async.py b/pyscriptjs/tests/integration/test_async.py deleted file mode 100644 index be4eb4fc554..00000000000 --- a/pyscriptjs/tests/integration/test_async.py +++ /dev/null @@ -1,208 +0,0 @@ -import pytest - -from .support import PyScriptTest - - -class TestAsync(PyScriptTest): - # ensure_future() and create_task() should behave similarly; - # we'll use the same source code to test both - coroutine_script = """ - - import js - import asyncio - js.console.log("first") - async def main(): - await asyncio.sleep(1) - js.console.log("third") - asyncio.{func}(main()) - js.console.log("second") - - """ - - def test_asyncio_ensure_future(self): - self.pyscript_run(self.coroutine_script.format(func="ensure_future")) - self.wait_for_console("third") - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-3:] == ["first", "second", "third"] - - def test_asyncio_create_task(self): - self.pyscript_run(self.coroutine_script.format(func="create_task")) - self.wait_for_console("third") - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-3:] == ["first", "second", "third"] - - def test_asyncio_gather(self): - self.pyscript_run( - """ - - import asyncio - import js - from pyodide.ffi import to_js - - async def coro(delay): - await asyncio.sleep(delay) - return(delay) - - async def get_results(): - results = await asyncio.gather(*[coro(d) for d in range(3,0,-1)]) - js.console.log(str(results)) #Compare to string representation, not Proxy - js.console.log("DONE") - - asyncio.ensure_future(get_results()) - - """ - ) - self.wait_for_console("DONE") - assert self.console.log.lines[-2:] == ["[3, 2, 1]", "DONE"] - - def test_multiple_async(self): - self.pyscript_run( - """ - - import js - import asyncio - async def a_func(): - for i in range(3): - js.console.log('A', i) - await asyncio.sleep(0.1) - asyncio.ensure_future(a_func()) - - - - import js - import asyncio - async def b_func(): - for i in range(3): - js.console.log('B', i) - await asyncio.sleep(0.1) - js.console.log('b func done') - asyncio.ensure_future(b_func()) - - """ - ) - self.wait_for_console("b func done") - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[1:] == [ - "A 0", - "B 0", - "A 1", - "B 1", - "A 2", - "B 2", - "b func done", - ] - - def test_multiple_async_multiple_display_targeted(self): - self.pyscript_run( - """ - - import js - import asyncio - - async def a_func(): - for i in range(2): - display(f'A{i}', target='pyA') - await asyncio.sleep(0.1) - asyncio.ensure_future(a_func()) - - - - import js - import asyncio - - async def a_func(): - for i in range(2): - display(f'B{i}', target='pyB') - await asyncio.sleep(0.1) - js.console.log("B DONE") - - asyncio.ensure_future(a_func()) - - """ - ) - self.wait_for_console("B DONE") - inner_text = self.page.inner_text("html") - assert "A0\nA1\nB0\nB1" in inner_text - - @pytest.mark.xfail(reason="fails after introducing synclink, fix me soon!") - def test_async_display_untargeted(self): - self.pyscript_run( - """ - - import asyncio - import js - - async def a_func(): - try: - display('A') - await asyncio.sleep(0.1) - except Exception as err: - js.console.error(str(err)) - await asyncio.sleep(1) - js.console.log("DONE") - - asyncio.ensure_future(a_func()) - - """ - ) - self.wait_for_console("DONE") - assert ( - self.console.error.lines[-1] - == "Implicit target not allowed here. Please use display(..., target=...)" - ) - - @pytest.mark.xfail(reason="fails after introducing synclink, fix me soon!") - def test_sync_and_async_order(self): - """ - The order of execution is defined as follows: - 1. first, we execute all the py-script tag in order - 2. then, we start all the tasks which were scheduled with create_task - - Note that tasks are started *AFTER* all py-script tags have been - executed. That's why the console.log() inside mytask1 and mytask2 are - executed after e.g. js.console.log("6"). - """ - src = """ - - import js - js.console.log("1") - - - - import asyncio - import js - - async def mytask1(): - js.console.log("7") - await asyncio.sleep(0) - js.console.log("9") - - js.console.log("2") - asyncio.create_task(mytask1()) - js.console.log("3") - - - - import js - js.console.log("4") - - - - import asyncio - import js - - async def mytask2(): - js.console.log("8") - await asyncio.sleep(0) - js.console.log("10") - js.console.log("DONE") - - js.console.log("5") - asyncio.create_task(mytask2()) - js.console.log("6") - - """ - self.pyscript_run(src, wait_for_pyscript=False) - self.wait_for_console("DONE") - lines = self.console.log.lines[-11:] - assert lines == ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "DONE"] diff --git a/pyscriptjs/tests/integration/test_importmap.py b/pyscriptjs/tests/integration/test_importmap.py deleted file mode 100644 index a809b24929d..00000000000 --- a/pyscriptjs/tests/integration/test_importmap.py +++ /dev/null @@ -1,68 +0,0 @@ -import pytest - -from .support import PyScriptTest - - -@pytest.mark.xfail(reason="See PR #938") -class TestImportmap(PyScriptTest): - def test_importmap(self): - src = """ - export function say_hello(who) { - console.log("hello from", who); - } - """ - self.writefile("mymod.js", src) - # - self.pyscript_run( - """ - - - - - - import mymod - mymod.say_hello("Python") - - """ - ) - assert self.console.log.lines == [ - "hello from JS", - self.PY_COMPLETE, - "hello from Python", - ] - - def test_invalid_json(self): - self.pyscript_run( - """ - - - - print("hello world") - - """, - wait_for_pyscript=False, - ) - # this error is raised by the browser itself, when *it* tries to parse - # the import map - self.check_js_errors("Failed to parse import map") - - self.wait_for_pyscript() - assert self.console.log.lines == [ - self.PY_COMPLETE, - "hello world", - ] - # this warning is shown by pyscript, when *we* try to parse the import - # map - banner = self.page.locator(".py-warning") - assert "Failed to parse import map" in banner.inner_text() diff --git a/pyscriptjs/tests/integration/test_interpreter.py b/pyscriptjs/tests/integration/test_interpreter.py deleted file mode 100644 index 9a8e6bb3cc7..00000000000 --- a/pyscriptjs/tests/integration/test_interpreter.py +++ /dev/null @@ -1,95 +0,0 @@ -from .support import PyScriptTest - - -class TestInterpreterAccess(PyScriptTest): - """Test accessing Python objects from JS via pyscript.interpreter""" - - def test_interpreter_python_access(self): - self.pyscript_run( - """ - - x = 1 - def py_func(): - return 2 - - """ - ) - - self.run_js( - """ - const x = await pyscript.interpreter.globals.get('x'); - const py_func = await pyscript.interpreter.globals.get('py_func'); - const py_func_res = await py_func(); - console.log(`x is ${x}`); - console.log(`py_func() returns ${py_func_res}`); - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-2:] == [ - "x is 1", - "py_func() returns 2", - ] - - def test_interpreter_script_execution(self): - """Test running Python code from js via pyscript.interpreter""" - self.pyscript_run("") - - self.run_js( - """ - const interface = pyscript.interpreter._remote.interface; - await interface.runPython('print("Interpreter Ran This")'); - """ - ) - - expected_message = "Interpreter Ran This" - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == expected_message - - py_terminal = self.page.wait_for_selector("py-terminal") - assert py_terminal.text_content() == expected_message - - def test_backward_compatibility_runtime_script_execution(self): - """Test running Python code from js via pyscript.runtime""" - self.pyscript_run("") - - self.run_js( - """ - const interface = pyscript.runtime._remote.interpreter; - await interface.runPython('print("Interpreter Ran This")'); - """ - ) - - expected_message = "Interpreter Ran This" - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == expected_message - - py_terminal = self.page.wait_for_selector("py-terminal") - assert py_terminal.text_content() == expected_message - - def test_backward_compatibility_runtime_python_access(self): - """Test accessing Python objects from JS via pyscript.runtime""" - self.pyscript_run( - """ - - x = 1 - def py_func(): - return 2 - - """ - ) - - self.run_js( - """ - const x = await pyscript.interpreter.globals.get('x'); - const py_func = await pyscript.interpreter.globals.get('py_func'); - const py_func_res = await py_func(); - console.log(`x is ${x}`); - console.log(`py_func() returns ${py_func_res}`); - """ - ) - - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-2:] == [ - "x is 1", - "py_func() returns 2", - ] diff --git a/pyscriptjs/tests/integration/test_plugins.py b/pyscriptjs/tests/integration/test_plugins.py deleted file mode 100644 index 0ec6ff9a732..00000000000 --- a/pyscriptjs/tests/integration/test_plugins.py +++ /dev/null @@ -1,414 +0,0 @@ -from .support import PyScriptTest - -# Source code of a simple plugin that creates a Custom Element for testing purposes -CE_PLUGIN_CODE = """ -from pyscript import Plugin -from js import console - -plugin = Plugin('py-upper') - -console.log("py_upper Plugin loaded") - -@plugin.register_custom_element('py-up') -class Upper: - def __init__(self, element): - self.element = element - - def connect(self): - console.log("Upper plugin connected") - return self.element.originalInnerHTML.upper() -""" - -# Source of a plugin hooks into the PyScript App lifecycle events -HOOKS_PLUGIN_CODE = """ -from pyscript import Plugin -from js import console - -class TestLogger(Plugin): - def configure(self, config): - console.log('configure called') - - def beforeLaunch(self, config): - console.log('beforeLaunch called') - - def afterSetup(self, config): - console.log('afterSetup called') - - def afterStartup(self, config): - console.log('afterStartup called') - - def beforePyScriptExec(self, interpreter, src, pyScriptTag): - console.log(f'beforePyScriptExec called') - console.log(f'before_src:{src}') - - def afterPyScriptExec(self, interpreter, src, pyScriptTag, result): - console.log(f'afterPyScriptExec called') - console.log(f'after_src:{src}') - - def onUserError(self, config): - console.log('onUserError called') - - -plugin = TestLogger() -""" - -# Source of script that defines a plugin with only beforePyScriptExec and -# afterPyScriptExec methods -PYSCRIPT_HOOKS_PLUGIN_CODE = """ -from pyscript import Plugin -from js import console - -class ExecTestLogger(Plugin): - - async def beforePyScriptExec(self, interpreter, src, pyScriptTag): - console.log(f'beforePyScriptExec called') - console.log(f'before_src:{src}') - console.log(f'before_id:{pyScriptTag.id}') - - async def afterPyScriptExec(self, interpreter, src, pyScriptTag, result): - console.log(f'afterPyScriptExec called') - console.log(f'after_src:{src}') - console.log(f'after_id:{pyScriptTag.id}') - console.log(f'result:{result}') - - -plugin = ExecTestLogger() -""" - -# Source of script that defines a plugin with only beforePyScriptExec and -# afterPyScriptExec methods -PYREPL_HOOKS_PLUGIN_CODE = """ -from pyscript import Plugin -from js import console - -console.warn("This is in pyrepl hooks file") - -class PyReplTestLogger(Plugin): - - def beforePyReplExec(self, interpreter, src, outEl, pyReplTag): - console.log(f'beforePyReplExec called') - console.log(f'before_src:{src}') - console.log(f'before_id:{pyReplTag.id}') - - def afterPyReplExec(self, interpreter, src, outEl, pyReplTag, result): - console.log(f'afterPyReplExec called') - console.log(f'after_src:{src}') - console.log(f'after_id:{pyReplTag.id}') - console.log(f'result:{result}') - - -plugin = PyReplTestLogger() -""" - -# Source of a script that doesn't call define a `plugin` attribute -NO_PLUGIN_CODE = """ -from pyscript import Plugin -from js import console - -class TestLogger(Plugin): - pass -""" - -# Source code of a simple plugin that creates a Custom Element for testing purposes -CODE_CE_PLUGIN_BAD_RETURNS = """ -from pyscript import Plugin -from js import console - -plugin = Plugin('py-broken') - -@plugin.register_custom_element('py-up') -class Upper: - def __init__(self, element): - self.element = element - - def connect(self): - # Just returning something... anything other than a string should be ignore - return Plugin -""" -HTML_TEMPLATE_WITH_TAG = """ - - plugins = [ - "./{plugin_name}.py" - ] - - - <{tagname}> - {html} - -""" -HTML_TEMPLATE_NO_TAG = """ - - plugins = [ - "./{plugin_name}.py" - ] - -""" - - -def prepare_test( - plugin_name, code, tagname="", html="", template=HTML_TEMPLATE_WITH_TAG -): - """ - Prepares the test by writing a new plugin file named `plugin_name`.py, with `code` as its - content and run `pyscript_run` on `template` formatted with the above inputs to create the - page HTML code. - - For example: - - >> @prepare_test('py-upper', CE_PLUGIN_CODE, tagname='py-up', html="Hello World") - >> def my_foo(...): - >> ... - - will: - - * write a new `py-upper.py` file to the FS - * the contents of `py-upper.py` is equal to CE_PLUGIN_CODE - * call self.pyscript_run with the following string: - ''' - - plugins = [ - "./py-upper.py" - ] - - - - {html} - - ''' - * call `my_foo` just like a normal decorator would - - """ - - def dec(f): - def _inner(self, *args, **kws): - self.writefile(f"{plugin_name}.py", code) - page_html = template.format( - plugin_name=plugin_name, tagname=tagname, html=html - ) - self.pyscript_run(page_html) - return f(self, *args, **kws) - - return _inner - - return dec - - -class TestPlugin(PyScriptTest): - @prepare_test("py-upper", CE_PLUGIN_CODE, tagname="py-up", html="Hello World") - def test_py_plugin_inline(self): - """Test that a regular plugin that returns new HTML content from connected works""" - # GIVEN a plugin that returns the all caps version of the tag innerHTML and logs text - # during it's execution/hooks - - # EXPECT the plugin logs to be present in the console logs - log_lines = self.console.log.lines - for log_line in ["py_upper Plugin loaded", "Upper plugin connected"]: - assert log_line in log_lines - - # EXPECT the inner text of the Plugin CustomElement to be all caps - rendered_text = self.page.locator("py-up").inner_text() - assert rendered_text == "HELLO WORLD" - - @prepare_test("hooks_logger", HOOKS_PLUGIN_CODE, template=HTML_TEMPLATE_NO_TAG) - def test_execution_hooks(self): - """Test that a Plugin that hooks into the PyScript App events, gets called - for each one of them""" - # GIVEN a plugin that logs specific strings for each app execution event - hooks_available = ["afterSetup", "afterStartup"] - hooks_unavailable = [ - "configure", - "beforeLaunch", - "beforePyScriptExec", - "afterPyScriptExec", - "beforePyReplExec", - "afterPyReplExec", - ] - - # EXPECT it to log the correct logs for the events it intercepts - log_lines = self.console.log.lines - num_calls = { - method: log_lines.count(f"{method} called") for method in hooks_available - } - expected_calls = {method: 1 for method in hooks_available} - assert num_calls == expected_calls - - # EXPECT it to NOT be called (hence not log anything) the events that happen - # before it's ready, hence is not called - unavailable_called = { - method: f"{method} called" in log_lines for method in hooks_unavailable - } - assert unavailable_called == {method: False for method in hooks_unavailable} - - # TODO: It'd be actually better to check that the events get called in order - - @prepare_test( - "exec_test_logger", - PYSCRIPT_HOOKS_PLUGIN_CODE, - template=HTML_TEMPLATE_NO_TAG + "\nx=2; x", - ) - def test_pyscript_exec_hooks(self): - """Test that the beforePyScriptExec and afterPyScriptExec hooks work as intended""" - assert self.page.locator("py-script") is not None - - log_lines: list[str] = self.console.log.lines - - assert "beforePyScriptExec called" in log_lines - assert "afterPyScriptExec called" in log_lines - - # These could be made better with a utility function that found log lines - # that match a filter function, or start with something - assert "before_src:x=2; x" in log_lines - assert "before_id:pyid" in log_lines - assert "after_src:x=2; x" in log_lines - assert "after_id:pyid" in log_lines - assert "result:2" in log_lines - - @prepare_test( - "pyrepl_test_logger", - PYREPL_HOOKS_PLUGIN_CODE, - template=HTML_TEMPLATE_NO_TAG + "\nx=2; x", - ) - def test_pyrepl_exec_hooks(self): - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - # allow afterPyReplExec to also finish before the test finishes - self.wait_for_console("result:2") - - log_lines: list[str] = self.console.log.lines - - assert "beforePyReplExec called" in log_lines - assert "afterPyReplExec called" in log_lines - - # These could be made better with a utility function that found log lines - # that match a filter function, or start with something - assert "before_src:x=2; x" in log_lines - assert "before_id:pyid" in log_lines - assert "after_src:x=2; x" in log_lines - assert "after_id:pyid" in log_lines - assert "result:2" in log_lines - - @prepare_test("no_plugin", NO_PLUGIN_CODE) - def test_no_plugin_attribute_error(self): - """ - Test a plugin that do not add the `plugin` attribute to its module - """ - # GIVEN a Plugin NO `plugin` attribute in it's module - error_msg = ( - "[pyscript/main] Cannot find plugin on Python module no_plugin! Python plugins " - 'modules must contain a "plugin" attribute. For more information check the ' - "plugins documentation." - ) - # EXPECT an error for the missing attribute - assert error_msg in self.console.error.lines - - def test_fetch_python_plugin(self): - """ - Test that we can fetch a plugin from a remote URL. Note we need to use - the 'raw' URL for the plugin, otherwise the request will be rejected - by cors policy. - """ - self.pyscript_run( - """ - - plugins = [ - "https://raw.githubusercontent.com/FabioRosado/pyscript-plugins/main/python/hello-world.py" - ] - - - - """ - ) - - hello_element = self.page.locator("py-hello-world") - assert hello_element.inner_html() == '
Hello World!
' - - def test_fetch_js_plugin(self): - self.pyscript_run( - """ - - plugins = [ - "https://raw.githubusercontent.com/FabioRosado/pyscript-plugins/main/js/hello-world.js" - ] - - """ - ) - - hello_element = self.page.locator("py-hello-world") - assert hello_element.inner_html() == "

Hello, world!

" - - def test_fetch_js_plugin_bare(self): - self.pyscript_run( - """ - - plugins = [ - "https://raw.githubusercontent.com/FabioRosado/pyscript-plugins/main/js/hello-world-base.js" - ] - - """ - ) - - hello_element = self.page.locator("py-hello-world") - assert hello_element.inner_html() == "

Hello, world!

" - - def test_fetch_plugin_no_file_extension(self): - self.pyscript_run( - """ - - plugins = [ - "http://non-existent.blah/hello-world" - ] - - """, - wait_for_pyscript=False, - ) - - expected_msg = ( - "(PY2000): Unable to load plugin from " - "'http://non-existent.blah/hello-world'. Plugins " - "need to contain a file extension and be either a " - "python or javascript file." - ) - - assert self.assert_banner_message(expected_msg) - - def test_fetch_js_plugin_non_existent(self): - self.pyscript_run( - """ - - plugins = [ - "http://non-existent.example.com/hello-world.js" - ] - - """, - wait_for_pyscript=False, - ) - - expected_msg = ( - "(PY0001): Fetching from URL " - "http://non-existent.example.com/hello-world.js failed " - "with error 'Failed to fetch'. Are your filename and " - "path correct?" - ) - - assert self.assert_banner_message(expected_msg) - - def test_fetch_js_no_export(self): - self.pyscript_run( - """ - - plugins = [ - "https://raw.githubusercontent.com/FabioRosado/pyscript-plugins/main/js/hello-world-no-export.js" - ] - - """, - wait_for_pyscript=False, - ) - - expected_message = ( - "(PY2001): Unable to load plugin from " - "'https://raw.githubusercontent.com/FabioRosado/pyscript-plugins" - "/main/js/hello-world-no-export.js'. " - "Plugins need to contain a default export." - ) - - assert self.assert_banner_message(expected_message) diff --git a/pyscriptjs/tests/integration/test_py_config.py b/pyscriptjs/tests/integration/test_py_config.py deleted file mode 100644 index a9bfb648450..00000000000 --- a/pyscriptjs/tests/integration/test_py_config.py +++ /dev/null @@ -1,317 +0,0 @@ -import os -import tarfile -import tempfile - -import pytest -import requests - -from .support import PyScriptTest - -URL = "https://github.com/pyodide/pyodide/releases/download/0.20.0/pyodide-build-0.20.0.tar.bz2" -TAR_NAME = "pyodide-build-0.20.0.tar.bz2" - - -@pytest.fixture -def tar_location(request): - val = request.config.cache.get("pyodide-0.20-tar", None) - if val is None: - response = requests.get(URL, stream=True) - TMP_DIR = tempfile.mkdtemp() - TMP_TAR_LOCATION = os.path.join(TMP_DIR, TAR_NAME) - with open(TMP_TAR_LOCATION, "wb") as f: - f.write(response.raw.read()) - val = TMP_TAR_LOCATION - request.config.cache.set("pyodide-0.20-tar", val) - return val - - -def unzip(location, extract_to="."): - file = tarfile.open(name=location, mode="r:bz2") - file.extractall(path=extract_to) - - -class TestConfig(PyScriptTest): - def test_py_config_inline(self): - self.pyscript_run( - """ - - name = "foobar" - - - - import js - config = js.pyscript_get_config() - js.console.log("config name:", config.name) - - """ - ) - assert self.console.log.lines[-1] == "config name: foobar" - - def test_py_config_external(self): - pyconfig_toml = """ - name = "app with external config" - """ - self.writefile("pyconfig.toml", pyconfig_toml) - self.pyscript_run( - """ - - - - - import js - config = js.pyscript_get_config() - js.console.log("config name:", config.name) - - """ - ) - assert self.console.log.lines[-1] == "config name: app with external config" - - # The default pyodide version is 0.22.1 as of writing - # this test which is newer than the one we are loading below - # (after downloading locally) -- which is 0.20.0 - - # The test checks if loading a different interpreter is possible - # and that too from a locally downloaded file without needing - # the use of explicit `indexURL` calculation. - def test_interpreter_config(self, tar_location): - unzip( - location=tar_location, - extract_to=self.tmpdir, - ) - - self.pyscript_run( - """ - - { - "interpreters": [{ - "src": "/pyodide/pyodide.js", - "name": "pyodide-0.20.0", - "lang": "python" - }] - } - - - - import sys, js - pyodide_version = sys.modules["pyodide"].__version__ - js.console.log("version", pyodide_version) - display(pyodide_version) - - """, - ) - - assert self.console.log.lines[-1] == "version 0.20.0" - version = self.page.locator("py-script").inner_text() - assert version == "0.20.0" - - def test_runtime_still_works_but_shows_deprecation_warning(self, tar_location): - unzip( - location=tar_location, - extract_to=self.tmpdir, - ) - - self.pyscript_run( - """ - - { - "runtimes": [{ - "src": "/pyodide/pyodide.js", - "name": "pyodide-0.20.0", - "lang": "python" - }] - } - - - - import sys, js - pyodide_version = sys.modules["pyodide"].__version__ - js.console.log("version", pyodide_version) - display(pyodide_version) - - """, - ) - - assert self.console.log.lines[-1] == "version 0.20.0" - version = self.page.locator("py-script").inner_text() - assert version == "0.20.0" - - deprecation_banner = self.page.wait_for_selector(".alert-banner") - expected_message = ( - "The configuration option `config.runtimes` is deprecated. " - "Please use `config.interpreters` instead." - ) - assert deprecation_banner.inner_text() == expected_message - - def test_invalid_json_config(self): - # we need wait_for_pyscript=False because we bail out very soon, - # before being able to write 'PyScript page fully initialized' - self.pyscript_run( - """ - - [[ - - """, - wait_for_pyscript=False, - ) - banner = self.page.wait_for_selector(".py-error") - assert "SyntaxError: Unexpected end of JSON input" in self.console.error.text - expected = ( - "(PY1000): The config supplied: [[ is an invalid JSON and cannot be " - "parsed: SyntaxError: Unexpected end of JSON input" - ) - assert banner.inner_text() == expected - - def test_invalid_toml_config(self): - # we need wait_for_pyscript=False because we bail out very soon, - # before being able to write 'PyScript page fully initialized' - self.pyscript_run( - """ - - [[ - - """, - wait_for_pyscript=False, - ) - banner = self.page.wait_for_selector(".py-error") - assert "SyntaxError: Expected DoubleQuote" in self.console.error.text - expected = ( - "(PY1000): The config supplied: [[ is an invalid TOML and cannot be parsed: " - "SyntaxError: Expected DoubleQuote, Whitespace, or [a-z], [A-Z], " - '[0-9], "-", "_" but "\\n" found.' - ) - assert banner.inner_text() == expected - - def test_multiple_py_config(self): - self.pyscript_run( - """ - - name = "foobar" - - - - this is ignored and won't even be parsed - - - - import js - config = js.pyscript_get_config() - js.console.log("config name:", config.name) - - """ - ) - banner = self.page.wait_for_selector(".py-warning") - expected = ( - "Multiple tags detected. Only the first " - "is going to be parsed, all the others will be ignored" - ) - assert banner.text_content() == expected - - def test_no_interpreter(self): - snippet = """ - - { - "interpreters": [] - } - - """ - self.pyscript_run(snippet, wait_for_pyscript=False) - div = self.page.wait_for_selector(".py-error") - assert ( - div.text_content() == "(PY1000): Fatal error: config.interpreter is empty" - ) - - def test_multiple_interpreter(self): - snippet = """ - - { - "interpreters": [ - { - "src": "https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js", - "name": "pyodide-0.22.1", - "lang": "python" - }, - { - "src": "http://...", - "name": "this will be ignored", - "lang": "this as well" - } - ] - } - - - - import js - js.console.log("hello world"); - - """ - self.pyscript_run(snippet) - banner = self.page.wait_for_selector(".py-warning") - expected = ( - "Multiple interpreters are not supported yet.Only the first will be used" - ) - assert banner.text_content() == expected - assert self.console.log.lines[-1] == "hello world" - - def test_paths(self): - self.writefile("a.py", "x = 'hello from A'") - self.writefile("b.py", "x = 'hello from B'") - self.pyscript_run( - """ - - [[fetch]] - files = ["./a.py", "./b.py"] - - - - import js - import a, b - js.console.log(a.x) - js.console.log(b.x) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-2:] == [ - "hello from A", - "hello from B", - ] - - def test_paths_that_do_not_exist(self): - self.pyscript_run( - """ - - [[fetch]] - files = ["./f.py"] - - """, - wait_for_pyscript=False, - ) - - expected = "(PY0404): Fetching from URL ./f.py failed with " "error 404" - - inner_html = self.page.locator(".py-error").inner_html() - - assert expected in inner_html - assert expected in self.console.error.lines[-1] - - def test_paths_from_packages(self): - self.writefile("utils/__init__.py", "") - self.writefile("utils/a.py", "x = 'hello from A'") - self.pyscript_run( - """ - - [[fetch]] - from = "utils" - to_folder = "pkg" - files = ["__init__.py", "a.py"] - - - - import js - from pkg.a import x - js.console.log(x) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == "hello from A" diff --git a/pyscriptjs/tests/integration/test_py_repl.py b/pyscriptjs/tests/integration/test_py_repl.py deleted file mode 100644 index 18217ca1b4f..00000000000 --- a/pyscriptjs/tests/integration/test_py_repl.py +++ /dev/null @@ -1,577 +0,0 @@ -import platform - -from .support import PyScriptTest - - -class TestPyRepl(PyScriptTest): - def _replace(self, py_repl, newcode): - """ - Clear the editor and write new code in it. - WARNING: this assumes that the textbox has already the focus - """ - # clear the editor, write new code - if "macOS" in platform.platform(): - self.page.keyboard.press("Meta+A") - else: - self.page.keyboard.press("Control+A") - - self.page.keyboard.press("Backspace") - self.page.keyboard.type(newcode) - - def test_repl_loads(self): - self.pyscript_run( - """ - - """ - ) - py_repl = self.page.query_selector("py-repl .py-repl-box") - assert py_repl - - def test_execute_preloaded_source(self): - """ - Unfortunately it tests two things at once, but it's impossible to write a - smaller test. I think this is the most basic test that we can write. - - We test that: - 1. the source code that we put in the tag is loaded inside the editor - 2. clicking the button executes it - """ - self.pyscript_run( - """ - - print('hello from py-repl') - - """ - ) - py_repl = self.page.locator("py-repl") - src = py_repl.inner_text() - assert "print('hello from py-repl')" in src - py_repl.locator("button").click() - self.page.wait_for_selector("py-terminal") - assert self.console.log.lines[-1] == "hello from py-repl" - - def test_execute_code_typed_by_the_user(self): - self.pyscript_run( - """ - - """ - ) - py_repl = self.page.locator("py-repl") - py_repl.type('print("hello")') - py_repl.locator("button").click() - self.page.wait_for_selector("py-terminal") - assert self.console.log.lines[-1] == "hello" - - def test_execute_on_shift_enter(self): - self.pyscript_run( - """ - - print("hello world") - - """ - ) - self.page.wait_for_selector("py-repl .py-repl-run-button") - self.page.keyboard.press("Shift+Enter") - self.page.wait_for_selector("py-terminal") - - assert self.console.log.lines[0] == self.PY_COMPLETE - assert self.console.log.lines[-1] == "hello world" - - # Shift-enter should not add a newline to the editor - assert self.page.locator(".cm-line").count() == 1 - - def test_display(self): - self.pyscript_run( - """ - - display('hello world') - - """ - ) - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert out_div.inner_text() == "hello world" - - def test_show_last_expression(self): - """ - Test that we display() the value of the last expression, as you would - expect by a REPL - """ - self.pyscript_run( - """ - - 42 - - """ - ) - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert out_div.inner_text() == "42" - - def test_show_last_expression_with_output(self): - """ - Test that we display() the value of the last expression, as you would - expect by a REPL - """ - self.pyscript_run( - """ -
- - 42 - - """ - ) - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - out_div = py_repl.locator("div.py-repl-output") - assert out_div.all_inner_texts()[0] == "" - - out_div = self.page.wait_for_selector("#repl-target") - assert out_div.inner_text() == "42" - - def test_run_clears_previous_output(self): - """ - Check that we clear the previous output of the cell before executing it - again - """ - self.pyscript_run( - """ - - display('hello world') - - """ - ) - py_repl = self.page.locator("py-repl") - self.page.keyboard.press("Shift+Enter") - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert out_div.inner_text() == "hello world" - # clear the editor, write new code, execute - self._replace(py_repl, "display('another output')") - self.page.keyboard.press("Shift+Enter") - # test runner can be too fast, the line below should wait for output to change - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert out_div.inner_text() == "another output" - - def test_python_exception(self): - """ - See also test01_basic::test_python_exception, since it's very similar - """ - self.pyscript_run( - """ - - raise Exception('this is an error') - - """ - ) - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - self.page.wait_for_selector(".py-error") - # - # check that we sent the traceback to the console - tb_lines = self.console.error.lines[-1].splitlines() - assert tb_lines[0] == "[pyexec] Python exception:" - assert tb_lines[1] == "Traceback (most recent call last):" - assert tb_lines[-1] == "Exception: this is an error" - # - # check that we show the traceback in the page - err_pre = py_repl.locator("div.py-repl-output > pre.py-error") - tb_lines = err_pre.inner_text().splitlines() - assert tb_lines[0] == "Traceback (most recent call last):" - assert tb_lines[-1] == "Exception: this is an error" - - def test_multiple_repls(self): - """ - Multiple repls showing in the correct order in the page - """ - self.pyscript_run( - """ - display("first") - display("second") - """ - ) - first_py_repl = self.page.get_by_text("first") - first_py_repl.click() - self.page.keyboard.press("Shift+Enter") - self.page.wait_for_selector("#py-internal-0-repl-output") - assert self.page.inner_text("#py-internal-0-repl-output") == "first" - - second_py_repl = self.page.get_by_text("second") - second_py_repl.click() - self.page.keyboard.press("Shift+Enter") - self.page.wait_for_selector("#py-internal-1-repl-output") - assert self.page.inner_text("#py-internal-1-repl-output") == "second" - - def test_python_exception_after_previous_output(self): - self.pyscript_run( - """ - - display('hello world') - - """ - ) - py_repl = self.page.locator("py-repl") - self.page.keyboard.press("Shift+Enter") - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert out_div.inner_text() == "hello world" - # - # clear the editor, write new code, execute - self._replace(py_repl, "0/0") - self.page.keyboard.press("Shift+Enter") - # test runner can be too fast, the line below should wait for output to change - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert "hello world" not in out_div.inner_text() - assert "ZeroDivisionError" in out_div.inner_text() - - def test_hide_previous_error_after_successful_run(self): - """ - this tests the fact that a new error div should be created once there's an - error but also that it should disappear automatically once the error - is fixed - """ - self.pyscript_run( - """ - - raise Exception('this is an error') - - """ - ) - py_repl = self.page.locator("py-repl") - self.page.keyboard.press("Shift+Enter") - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert "this is an error" in out_div.inner_text() - # - self._replace(py_repl, "display('hello')") - self.page.keyboard.press("Shift+Enter") - # test runner can be too fast, the line below should wait for output to change - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert out_div.inner_text() == "hello" - - def test_output_attribute_does_not_exist(self): - """ - If we try to use an attribute which doesn't exist, we display an error - instead - """ - self.pyscript_run( - """ - - print('I will not be executed') - - """ - ) - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - - banner = self.page.wait_for_selector(".py-warning") - - banner_content = banner.inner_text() - expected = ( - 'output = "I-dont-exist" does not match the id of any element on the page.' - ) - assert banner_content == expected - - def test_auto_generate(self): - self.pyscript_run( - """ - - - """ - ) - py_repls = self.page.locator("py-repl") - outputs = py_repls.locator("div.py-repl-output") - assert py_repls.count() == 1 - assert outputs.count() == 1 - # - # evaluate the py-repl, and wait for the newly generated one - self.page.keyboard.type("'hello'") - self.page.keyboard.press("Shift+Enter") - self.page.locator('py-repl[exec-id="1"]').wait_for() - assert py_repls.count() == 2 - assert outputs.count() == 2 - # - # now we type something else: the new py-repl should have the focus - self.page.keyboard.type("'world'") - self.page.keyboard.press("Shift+Enter") - self.page.locator('py-repl[exec-id="2"]').wait_for() - assert py_repls.count() == 3 - assert outputs.count() == 3 - # - # check that the code and the outputs are in order - out_texts = [el.inner_text() for el in self.iter_locator(outputs)] - assert out_texts == ["hello", "world", ""] - - def test_multiple_repls_mixed_display_order(self): - """ - Displaying several outputs that don't obey the order in which the original - repl displays were created using the auto_generate attr - """ - self.pyscript_run( - """ - display("root first") - display("root second") - """ - ) - - second_py_repl = self.page.get_by_text("root second") - second_py_repl.click() - self.page.keyboard.press("Shift+Enter") - self.page.wait_for_selector("#py-internal-1-repl-output") - self.page.keyboard.type("display('second children')") - self.page.keyboard.press("Shift+Enter") - self.page.wait_for_selector("#py-internal-1-1-repl-output") - - first_py_repl = self.page.get_by_text("root first") - first_py_repl.click() - self.page.keyboard.press("Shift+Enter") - self.page.wait_for_selector("#py-internal-0-repl-output") - self.page.keyboard.type("display('first children')") - self.page.keyboard.press("Shift+Enter") - self.page.wait_for_selector("#py-internal-0-1-repl-output") - - assert self.page.inner_text("#py-internal-1-1-repl-output") == "second children" - assert self.page.inner_text("#py-internal-0-1-repl-output") == "first children" - - def test_repl_output_attribute(self): - # Test that output attribute sends stdout to the element - # with the given ID, but not display() - self.pyscript_run( - """ -
- - print('print from py-repl') - display('display from py-repl') - - - """ - ) - - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - - target = self.page.wait_for_selector("#repl-target") - assert "print from py-repl" in target.inner_text() - - out_div = self.page.wait_for_selector("#py-internal-0-repl-output") - assert out_div.inner_text() == "display from py-repl" - - self.assert_no_banners() - - def test_repl_output_display_async(self): - # py-repls running async code are not expected to - # send display to element element - self.pyscript_run( - """ -
- - import asyncio - import js - - async def print_it(): - await asyncio.sleep(1) - print('print from py-repl') - - - async def display_it(): - display('display from py-repl') - await asyncio.sleep(2) - - async def done(): - await asyncio.sleep(3) - js.console.log("DONE") - - - - asyncio.ensure_future(print_it()); - asyncio.ensure_future(display_it()); - asyncio.ensure_future(done()); - - """ - ) - - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - - self.wait_for_console("DONE") - - assert self.page.locator("#repl-target").text_content() == "" - self.assert_no_banners() - - def test_repl_stdio_dynamic_tags(self): - self.pyscript_run( - """ -
-
- - import js - - print("first.") - - # Using string, since no clean way to write to the - # code contents of the CodeMirror in a PyRepl - newTag = 'print("second.")' - js.document.body.innerHTML += newTag - - """ - ) - - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - - assert self.page.wait_for_selector("#first").inner_text() == "first.\n" - - second_repl = self.page.locator("py-repl#second-repl") - second_repl.locator("button").click() - assert self.page.wait_for_selector("#second").inner_text() == "second.\n" - - def test_repl_output_id_errors(self): - self.pyscript_run( - """ - - print("bad.") - print("bad.") - - - - print("bad.") - - """ - ) - py_repls = self.page.query_selector_all("py-repl") - for repl in py_repls: - repl.query_selector_all("button")[0].click() - - banner = self.page.wait_for_selector(".py-warning") - - banner_content = banner.inner_text() - expected = ( - 'output = "not-on-page" does not match the id of any element on the page.' - ) - - assert banner_content == expected - - def test_repl_stderr_id_errors(self): - self.pyscript_run( - """ - - import sys - print("bad.", file=sys.stderr) - print("bad.", file=sys.stderr) - - - - print("bad.", file=sys.stderr) - - """ - ) - py_repls = self.page.query_selector_all("py-repl") - for repl in py_repls: - repl.query_selector_all("button")[0].click() - - banner = self.page.wait_for_selector(".py-warning") - - banner_content = banner.inner_text() - expected = ( - 'stderr = "not-on-page" does not match the id of any element on the page.' - ) - - assert banner_content == expected - - def test_repl_output_stderr(self): - # Test that stderr works, and routes to the same location as stdout - # Also, repls with the stderr attribute route to an additional location - self.pyscript_run( - """ -
-
- - import sys - print("one.", file=sys.stderr) - print("two.") - - """ - ) - - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - - assert self.page.wait_for_selector("#stdout-div").inner_text() == "one.\ntwo.\n" - assert self.page.wait_for_selector("#stderr-div").inner_text() == "one.\n" - self.assert_no_banners() - - def test_repl_output_attribute_change(self): - # If the user changes the 'output' attribute of a tag mid-execution, - # Output should no longer go to the selected div and a warning should appear - self.pyscript_run( - """ -
-
- - - print("one.") - - # Change the 'output' attribute of this tag - import js - this_tag = js.document.getElementById("repl-tag") - - this_tag.setAttribute("output", "second") - print("two.") - - this_tag.setAttribute("output", "third") - print("three.") - - """ - ) - - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - - assert self.page.wait_for_selector("#first").inner_text() == "one.\n" - assert self.page.wait_for_selector("#second").inner_text() == "two.\n" - - expected_alert_banner_msg = ( - 'output = "third" does not match the id of any element on the page.' - ) - - alert_banner = self.page.wait_for_selector(".alert-banner") - assert expected_alert_banner_msg in alert_banner.inner_text() - - def test_repl_output_element_id_change(self): - # If the user changes the ID of the targeted DOM element mid-execution, - # Output should no longer go to the selected element and a warning should appear - self.pyscript_run( - """ -
-
- - - print("one.") - - # Change the ID of the targeted DIV to something else - import js - target_tag = js.document.getElementById("first") - - # should fail and show banner - target_tag.setAttribute("id", "second") - print("two.") - - # But changing both the 'output' attribute and the id of the target - # should work - target_tag.setAttribute("id", "third") - js.document.getElementById("pyscript-tag").setAttribute("output", "third") - print("three.") - - """ - ) - - py_repl = self.page.locator("py-repl") - py_repl.locator("button").click() - - # Note the ID of the div has changed by the time of this assert - assert self.page.wait_for_selector("#third").inner_text() == "one.\nthree.\n" - - expected_alert_banner_msg = ( - 'output = "first" does not match the id of any element on the page.' - ) - alert_banner = self.page.wait_for_selector(".alert-banner") - assert expected_alert_banner_msg in alert_banner.inner_text() diff --git a/pyscriptjs/tests/integration/test_py_terminal.py b/pyscriptjs/tests/integration/test_py_terminal.py deleted file mode 100644 index 96f7098e78e..00000000000 --- a/pyscriptjs/tests/integration/test_py_terminal.py +++ /dev/null @@ -1,148 +0,0 @@ -from playwright.sync_api import expect - -from .support import PyScriptTest - - -class TestPyTerminal(PyScriptTest): - def test_py_terminal(self): - """ - 1. should redirect stdout and stderr to the DOM - - 2. they also go to the console as usual - - 3. note that the console also contains PY_COMPLETE, which is a pyodide - initialization message, but py-terminal doesn't. This is by design - """ - self.pyscript_run( - """ - - - - import sys - print('hello world') - print('this goes to stderr', file=sys.stderr) - print('this goes to stdout') - - """ - ) - term = self.page.locator("py-terminal") - term_lines = term.inner_text().splitlines() - assert term_lines == [ - "hello world", - "this goes to stderr", - "this goes to stdout", - ] - assert self.console.log.lines[-3:] == [ - "hello world", - "this goes to stderr", - "this goes to stdout", - ] - - def test_two_terminals(self): - """ - Multiple s can cohexist. - A receives only output from the moment it is added to - the DOM. - """ - self.pyscript_run( - """ - - - - import js - print('one') - term2 = js.document.createElement('py-terminal') - term2.id = 'term2' - js.document.body.append(term2) - - print('two') - print('three') - - """ - ) - term1 = self.page.locator("#term1") - term2 = self.page.locator("#term2") - term1_lines = term1.inner_text().splitlines() - term2_lines = term2.inner_text().splitlines() - assert term1_lines == ["one", "two", "three"] - assert term2_lines == ["two", "three"] - - def test_auto_attribute(self): - self.pyscript_run( - """ - - - - """ - ) - term = self.page.locator("py-terminal") - expect(term).to_be_hidden() - self.page.locator("button").click() - expect(term).to_be_visible() - assert term.inner_text() == "hello world\n" - - def test_config_auto(self): - """ - config.terminal == "auto" is the default: a is - automatically added to the page - """ - self.pyscript_run( - """ - - """ - ) - term = self.page.locator("py-terminal") - expect(term).to_be_hidden() - assert "No found, adding one" in self.console.info.text - # - self.page.locator("button").click() - expect(term).to_be_visible() - assert term.inner_text() == "hello world\n" - - def test_config_true(self): - """ - If we set config.terminal == true, a is automatically added - """ - self.pyscript_run( - """ - - terminal = true - - - - print('hello world') - - """ - ) - term = self.page.locator("py-terminal") - expect(term).to_be_visible() - assert term.inner_text() == "hello world\n" - - def test_config_false(self): - """ - If we set config.terminal == false, no is added - """ - self.pyscript_run( - """ - - terminal = false - - """ - ) - term = self.page.locator("py-terminal") - assert term.count() == 0 - - def test_config_docked(self): - """ - config.docked == "docked" is also the default: a is - automatically added to the page - """ - self.pyscript_run( - """ - - """ - ) - term = self.page.locator("py-terminal") - self.page.locator("button").click() - expect(term).to_be_visible() - assert term.get_attribute("docked") == "" diff --git a/pyscriptjs/tests/integration/test_splashscreen.py b/pyscriptjs/tests/integration/test_splashscreen.py deleted file mode 100644 index 4ae7354cb1a..00000000000 --- a/pyscriptjs/tests/integration/test_splashscreen.py +++ /dev/null @@ -1,142 +0,0 @@ -import pytest -from playwright.sync_api import expect - -from .support import PyScriptTest - - -class TestSplashscreen(PyScriptTest): - def test_autoshow_and_autoclose(self): - """ - By default, we show the splashscreen and we close it when the loading is - complete. - - XXX: this test is a bit fragile: now it works reliably because the - startup is so slow that when we do expect(div).to_be_visible(), the - splashscreen is still there. But in theory, if the startup become very - fast, it could happen that by the time we arrive in python lang, it - has already been removed. - """ - self.pyscript_run( - """ - - print('hello pyscript') - - """, - wait_for_pyscript=False, - ) - div = self.page.locator("py-splashscreen > div") - expect(div).to_be_visible() - expect(div).to_contain_text("Python startup...") - assert "Python startup..." in self.console.info.text - # - # now we wait for the startup to complete - self.wait_for_pyscript() - # - # and now the splashscreen should have been removed - expect(div).to_be_hidden() - assert self.page.locator("py-locator").count() == 0 - - assert self.console.log.lines[0] == self.PY_COMPLETE - assert "hello pyscript" in self.console.log.lines - - def test_autoclose_false(self): - self.pyscript_run( - """ - - [splashscreen] - autoclose = false - - - print('hello pyscript') - - """, - ) - div = self.page.locator("py-splashscreen > div") - expect(div).to_be_visible() - expect(div).to_contain_text("Python startup...") - expect(div).to_contain_text("Startup complete") - assert self.console.log.lines[0] == self.PY_COMPLETE - assert "hello pyscript" in self.console.log.lines - - def test_autoclose_loader_deprecated(self): - self.pyscript_run( - """ - - autoclose_loader = false - - - print('hello pyscript') - - """, - ) - warning = self.page.locator(".py-warning") - inner_text = warning.inner_html() - assert "The setting autoclose_loader is deprecated" in inner_text - - div = self.page.locator("py-splashscreen > div") - expect(div).to_be_visible() - expect(div).to_contain_text("Python startup...") - expect(div).to_contain_text("Startup complete") - assert self.console.log.lines[0] == self.PY_COMPLETE - assert "hello pyscript" in self.console.log.lines - - @pytest.mark.skip(reason="pys-onClick is broken, we should kill it, see #1213") - def test_splashscreen_closes_on_error_with_pys_onClick(self): - self.pyscript_run( - """ - - - - from js import console - - def myFunc(*args, **kwargs): - text = Element('test-input').element.value - Element('test-output').element.innerText = text - - - """, - ) - - assert self.page.locator("py-splashscreen").count() == 0 - assert "Python exception" in self.console.error.text - - def test_splashscreen_disabled_option(self): - self.pyscript_run( - """ - - [splashscreen] - enabled = false - - - - def test(): - print("Hello pyscript!") - test() - - """, - ) - assert self.page.locator("py-splashscreen").count() == 0 - assert self.console.log.lines[-1] == "Hello pyscript!" - py_terminal = self.page.wait_for_selector("py-terminal") - assert py_terminal.inner_text() == "Hello pyscript!\n" - - def test_splashscreen_custom_message(self): - self.pyscript_run( - """ - - [splashscreen] - autoclose = false - - - - from js import document - - splashscreen = document.querySelector("py-splashscreen") - splashscreen.log("Hello, world!") - - """, - ) - - splashscreen = self.page.locator("py-splashscreen") - assert splashscreen.count() == 1 - assert "Hello, world!" in splashscreen.inner_text() diff --git a/pyscriptjs/tests/integration/test_stdio_handling.py b/pyscriptjs/tests/integration/test_stdio_handling.py deleted file mode 100644 index 73730f5f70e..00000000000 --- a/pyscriptjs/tests/integration/test_stdio_handling.py +++ /dev/null @@ -1,367 +0,0 @@ -import pytest - -from .support import PyScriptTest - - -class TestOutputHandling(PyScriptTest): - # Source of a script to test the TargetedStdio functionality - - def test_targeted_stdio_solo(self): - self.pyscript_run( - """ - - terminal = true - - -
-
-
-
-
- print("first 1.") - print("second.") - print("third.") - print("first 2.") - print("no output.") - """ - ) - - # Check that page has desired parent/child structure, and that - # Output divs are correctly located - assert (container := self.page.locator("#container")).count() > 0 - assert (first_div := container.locator("#first")).count() > 0 - assert (second_div := container.locator("#second")).count() > 0 - assert (third_div := container.locator("#third")).count() > 0 - - # Check that output ends up in proper div - assert first_div.text_content() == "first 1.first 2." - assert second_div.text_content() == "second." - assert third_div.text_content() == "third." - - # Check that tag with no otuput attribute doesn't end up in container at all - assert container.get_by_text("no output.").count() == 0 - - # Check that all output ends up in py-terminal - assert ( - self.page.locator("py-terminal").text_content() - == "first 1.second.third.first 2.no output." - ) - - # Check that all output ends up in the dev console, in order - last_index = -1 - for line in ["first 1.", "second.", "third.", "first 2.", "no output."]: - assert (line_index := self.console.log.lines.index(line)) > -1 - assert line_index > last_index - last_index = line_index - - self.assert_no_banners() - - def test_stdio_escape(self): - # Test that text that looks like HTML tags is properly escaped in stdio - self.pyscript_run( - """ -
- - print("

Hello

") - print('') -
- """ - ) - - text = self.page.locator("#first").text_content() - - assert "

Hello

" in text - assert '' in text - - self.assert_no_banners() - - def test_targeted_stdio_linebreaks(self): - self.pyscript_run( - """ -
- - print("one.") - print("two.") - print("three.") - - -
- - print("one.\\ntwo.\\nthree.") - - """ - ) - - # check line breaks at end of each input - assert self.page.locator("#first").inner_html() == "one.
two.
three.
" - - # new lines are converted to line breaks - assert self.page.locator("#second").inner_html() == "one.
two.
three.
" - - self.assert_no_banners() - - @pytest.mark.xfail(reason="fails after introducing synclink, fix me soon!") - def test_targeted_stdio_async(self): - # Test the behavior of stdio capture in async contexts - self.pyscript_run( - """ - - import asyncio - import js - - async def coro(value, delay): - print(value) - await asyncio.sleep(delay) - js.console.log(f"DONE {value}") - - -
- - asyncio.ensure_future(coro("first", 1)) - - -
- - asyncio.ensure_future(coro("second", 1)) - - -
- - asyncio.ensure_future(coro("third", 0)) - - - - asyncio.ensure_future(coro("DONE", 3)) - - """ - ) - - self.wait_for_console("DONE DONE") - - # py-script tags without output parameter should not send - # stdout to element - assert self.page.locator("#first").text_content() == "" - - # py-script tags with output parameter not expected to send - # std to element in coroutine - assert self.page.locator("#second").text_content() == "" - assert self.page.locator("#third").text_content() == "" - - self.assert_no_banners() - - @pytest.mark.xfail(reason="fails after introducing synclink, fix me soon!") - def test_targeted_stdio_interleaved(self): - # Test that synchronous writes to stdout are placed correctly, even - # While interleaved with scheduling coroutines in the same tag - self.pyscript_run( - """ -
-
- - import asyncio - import js - - async def coro_bad(value, delay): - print(value) - await asyncio.sleep(delay) - - print("one.") - asyncio.ensure_future(coro_bad("badone.", 0.1)) - print("two.") - asyncio.ensure_future(coro_bad("badtwo.", 0.2)) - print("three.") - asyncio.ensure_future(coro_bad("badthree.", 0)) - asyncio.ensure_future(coro_bad("DONE", 1)) - - """ - ) - - # Three prints should appear from synchronous writes - assert self.page.locator("#good").text_content() == "one.two.three." - - # Check that all output ends up in the dev console, in order - last_index = -1 - for line in ["one.", "two.", "three.", "badthree.", "badone.", "badtwo."]: - assert (line_index := self.console.log.lines.index(line)) > -1 - assert line_index > last_index - - self.assert_no_banners() - - def test_targeted_stdio_dynamic_tags(self): - # Test that creating py-script tags via Python still leaves - # stdio targets working - - self.pyscript_run( - """ -
-
- - print("first.") - - import js - tag = js.document.createElement("py-script") - tag.innerText = "print('second.')" - tag.setAttribute("output", "second") - js.document.body.appendChild(tag) - - print("first.") - - """ - ) - - # Ensure second tag was added to page - assert (second_div := self.page.locator("#second")).count() > 0 - - # Ensure output when to correct locations - assert self.page.locator("#first").text_content() == "first.first." - assert second_div.text_content() == "second." - - self.assert_no_banners() - - def test_stdio_stdout_id_errors(self): - # Test that using an ID not present on the page as the Output - # Attribute creates exactly 1 warning banner per missing id - self.pyscript_run( - """ - - print("bad.") - - -
- - print("good.") - - - - print("bad.") - - """ - ) - - banner = self.page.query_selector_all(".py-warning") - assert len(banner) == 1 - banner_content = banner[0].inner_text() - expected = ( - 'output = "not-on-page" does not match the id of any element on the page.' - ) - - assert banner_content == expected - - def test_stdio_stderr_id_errors(self): - # Test that using an ID not present on the page as the stderr - # attribute creates exactly 1 warning banner per missing id - self.pyscript_run( - """ - - import sys - print("bad.", file=sys.stderr) - - -
- - print("good.", file=sys.stderr) - - - - print("bad.", file=sys.stderr) - - """ - ) - - banner = self.page.query_selector_all(".py-warning") - assert len(banner) == 1 - banner_content = banner[0].inner_text() - expected = ( - 'stderr = "not-on-page" does not match the id of any element on the page.' - ) - - assert banner_content == expected - - def test_stdio_stderr(self): - # Test that stderr works, and routes to the same location as stdout - # Also, script tags with the stderr attribute route to an additional location - self.pyscript_run( - """ -
-
- - import sys - print("one.", file=sys.stderr) - print("two.") - - """ - ) - - assert self.page.locator("#stdout-div").text_content() == "one.two." - assert self.page.locator("#stderr-div").text_content() == "one." - self.assert_no_banners() - - def test_stdio_output_attribute_change(self): - # If the user changes the 'output' attribute of a tag mid-execution, - # Output should no longer go to the selected div and a warning should appear - self.pyscript_run( - """ -
-
- - - print("one.") - - # Change the 'output' attribute of this tag - import js - this_tag = js.document.getElementById("pyscript-tag") - - this_tag.setAttribute("output", "second") - print("two.") - - this_tag.setAttribute("output", "third") - print("three.") - - """ - ) - - assert self.page.locator("#first").text_content() == "one." - assert self.page.locator("#second").text_content() == "two." - expected_alert_banner_msg = ( - 'output = "third" does not match the id of any element on the page.' - ) - - alert_banner = self.page.locator(".alert-banner") - assert expected_alert_banner_msg in alert_banner.inner_text() - - def test_stdio_target_element_id_change(self): - # If the user changes the ID of the targeted DOM element mid-execution, - # Output should no longer go to the selected element and a warning should appear - self.pyscript_run( - """ -
-
- - - print("one.") - - # Change the ID of the targeted DIV to something else - import js - target_tag = js.document.getElementById("first") - - # should fail and show banner - target_tag.setAttribute("id", "second") - print("two.") - - # But changing both the 'output' attribute and the id of the target - # should work - target_tag.setAttribute("id", "third") - js.document.getElementById("pyscript-tag").setAttribute("output", "third") - print("three.") - - """ - ) - - # Note the ID of the div has changed by the time of this assert - assert self.page.locator("#third").text_content() == "one.three." - - expected_alert_banner_msg = ( - 'output = "first" does not match the id of any element on the page.' - ) - alert_banner = self.page.locator(".alert-banner") - assert expected_alert_banner_msg in alert_banner.inner_text() diff --git a/pyscriptjs/tests/integration/test_style.py b/pyscriptjs/tests/integration/test_style.py deleted file mode 100644 index 89f2bd82c51..00000000000 --- a/pyscriptjs/tests/integration/test_style.py +++ /dev/null @@ -1,40 +0,0 @@ -from playwright.sync_api import expect - -from .support import PyScriptTest - - -class TestStyle(PyScriptTest): - def test_pyscript_not_defined(self): - """Test raw elements that are not defined for display:none""" - doc = """ - - - - - - hello - hello - hello - - - """ - self.writefile("test-not-defined-css.html", doc) - self.goto("test-not-defined-css.html") - expect(self.page.locator("py-config")).to_be_hidden() - expect(self.page.locator("py-script")).to_be_hidden() - expect(self.page.locator("py-repl")).to_be_hidden() - - def test_pyscript_defined(self): - """Test elements have visibility that should""" - self.pyscript_run( - """ - - name = "foo" - - display("hello") - display("hello") - """ - ) - expect(self.page.locator("py-config")).to_be_hidden() - expect(self.page.locator("py-script")).to_be_visible() - expect(self.page.locator("py-repl")).to_be_visible() diff --git a/pyscriptjs/tests/integration/test_warnings_and_banners.py b/pyscriptjs/tests/integration/test_warnings_and_banners.py deleted file mode 100644 index 3e0013769e0..00000000000 --- a/pyscriptjs/tests/integration/test_warnings_and_banners.py +++ /dev/null @@ -1,28 +0,0 @@ -from .support import PyScriptTest - - -class TestWarningsAndBanners(PyScriptTest): - # Test the behavior of generated warning banners - - def test_create_singular_warning(self): - # Use a script tag with an invalid output attribute to generate a warning, but only one - self.pyscript_run( - """ - - print("one.") - print("two.") - - - print("three.") - - """ - ) - - loc = self.page.locator(".alert-banner") - - # Only one banner should appear - assert loc.count() == 1 - assert ( - loc.text_content() - == 'output = "foo" does not match the id of any element on the page.' - ) diff --git a/pyscriptjs/tests/integration/test_zz_examples.py b/pyscriptjs/tests/integration/test_zz_examples.py deleted file mode 100644 index 41499e4267b..00000000000 --- a/pyscriptjs/tests/integration/test_zz_examples.py +++ /dev/null @@ -1,397 +0,0 @@ -import base64 -import io -import os -import re -import time - -import numpy as np -import pytest -from PIL import Image - -from .support import ROOT, PyScriptTest, wait_for_render - - -@pytest.mark.usefixtures("chdir") -class TestExamples(PyScriptTest): - """ - Each example requires the same three tests: - - - Test that the initial markup loads properly (currently done by - testing the tag's content) - - Testing that pyscript is loading properly - - Testing that the page contains appropriate content after rendering - """ - - @pytest.fixture() - def chdir(self): - # make sure that the http server serves from the right directory - ROOT.join("pyscriptjs").chdir() - - def test_hello_world(self): - self.goto("examples/hello_world.html") - self.wait_for_pyscript() - assert self.page.title() == "PyScript Hello World" - content = self.page.content() - pattern = "\\d+/\\d+/\\d+, \\d+:\\d+:\\d+" # e.g. 08/09/2022 15:57:32 - assert re.search(pattern, content) - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_simple_clock(self): - self.goto("examples/simple_clock.html") - self.wait_for_pyscript() - assert self.page.title() == "Simple Clock Demo" - pattern = r"\d{2}/\d{2}/\d{4}, \d{2}:\d{2}:\d{2}" - # run for 5 seconds to be sure that we see the page with "It's - # espresso time!" - for _ in range(5): - content = self.page.inner_html("#outputDiv2") - if re.match(pattern, content) and int(content[-1]) in (0, 4, 8): - assert self.page.inner_html("#outputDiv3") == "It's espresso time!" - break - else: - time.sleep(1) - else: - raise AssertionError("Espresso time not found :(") - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_altair(self): - self.goto("examples/altair.html") - self.wait_for_pyscript() - assert self.page.title() == "Altair" - wait_for_render(self.page, "*", '<canvas.*?class=\\"marks\\".*?>') - save_as_png_link = self.page.locator("text=Save as PNG") - see_source_link = self.page.locator("text=View Source") - # These shouldn't be visible since we didn't click the menu - assert not save_as_png_link.is_visible() - assert not see_source_link.is_visible() - - self.page.locator("summary").click() - - # Let's confirm that the links are visible now after clicking the menu - assert save_as_png_link.is_visible() - assert see_source_link.is_visible() - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_antigravity(self): - self.goto("examples/antigravity.html") - self.wait_for_pyscript() - assert self.page.title() == "Antigravity" - - # confirm that svg added to page - wait_for_render(self.page, "*", '<svg.*id="svg8".*>') - - # Get svg layer of flying character - char = self.page.wait_for_selector("#python") - assert char is not None - - # check that character moves in negative-y direction over time - ycoord_pattern = r"translate\(-?\d*\.\d*,\s(?P<ycoord>-?[\d.]+)\)" - starting_y_coord = float( - re.match(ycoord_pattern, char.get_attribute("transform")).group("ycoord") - ) - time.sleep(2) - later_y_coord = float( - re.match(ycoord_pattern, char.get_attribute("transform")).group("ycoord") - ) - assert later_y_coord < starting_y_coord - self.check_tutor_generated_code(modules_to_check=["antigravity.py"]) - - def test_bokeh(self): - # XXX improve this test - self.goto("examples/bokeh.html") - self.wait_for_pyscript() - assert self.page.title() == "Bokeh Example" - wait_for_render(self.page, "*", '<div.*?class="bk.*".*?>') - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_bokeh_interactive(self): - # XXX improve this test - self.goto("examples/bokeh_interactive.html") - self.wait_for_pyscript() - assert self.page.title() == "Bokeh Example" - wait_for_render(self.page, "*", '<div.*?class=\\"bk\\".*?>') - self.assert_no_banners() - self.check_tutor_generated_code() - - @pytest.mark.skip("flaky, see issue 759") - def test_d3(self): - self.goto("examples/d3.html") - self.wait_for_pyscript() - assert ( - self.page.title() == "d3: JavaScript & PyScript visualizations side-by-side" - ) - wait_for_render(self.page, "*", "<svg.*?>") - assert "PyScript version" in self.page.content() - pyscript_chart = self.page.wait_for_selector("#py") - - # Let's simply assert that the text of the chart is as expected which - # means that the chart rendered successfully and with the right text - assert "🍊21\n🍇13\n🍏8\n🍌5\n🍐3\n🍋2\n🍎1\n🍉1" in pyscript_chart.inner_text() - self.assert_no_banners() - self.check_tutor_generated_code(modules_to_check=["d3.py"]) - - def test_folium(self): - self.goto("examples/folium.html") - self.wait_for_pyscript() - assert self.page.title() == "Folium" - wait_for_render(self.page, "*", "<iframe srcdoc=") - - # We need to look into the iframe first - iframe = self.page.frame_locator("iframe") - - # Just checking that legend was rendered correctly - legend = iframe.locator("#legend") - assert "Unemployment Rate (%)" in legend.inner_html() - - # Let's check that the zoom buttons are rendered and clickable - # Note: if element is not clickable it will timeout - zoom_in = iframe.locator("[aria-label='Zoom in']") - assert "+" in zoom_in.inner_text() - zoom_in.click() - zoom_out = iframe.locator("[aria-label='Zoom out']") - assert "−" in zoom_out.inner_text() - zoom_out.click() - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_markdown_plugin(self): - # Given the example page with: - # * <title>PyMarkdown - # * #Hello world! - self.goto("examples/markdown-plugin.html") - self.wait_for_pyscript() - # ASSERT title is rendered correctly - assert self.page.title() == "PyMarkdown" - # ASSERT markdown is rendered to the corresponding HTML tag - wait_for_render(self.page, "*", "

Hello world!

") - self.check_tutor_generated_code() - - def test_matplotlib(self): - self.goto("examples/matplotlib.html") - self.wait_for_pyscript() - assert self.page.title() == "Matplotlib" - wait_for_render(self.page, "*", "> img") - img_src = test.get_attribute("src").replace( - "data:image/png;charset=utf-8;base64,", "" - ) - # Finally, let's get the np array from the previous data - img_data = np.asarray(Image.open(io.BytesIO(base64.b64decode(img_src)))) - with Image.open( - os.path.join(os.path.dirname(__file__), "test_assets", "tripcolor.png"), - ) as image: - ref_data = np.asarray(image) - # Now that we have both images data as a numpy array - # let's confirm that they are the same - deviation = np.mean(np.abs(img_data - ref_data)) - assert deviation == 0.0 - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_numpy_canvas_fractals(self): - self.goto("examples/numpy_canvas_fractals.html") - self.wait_for_pyscript() - assert ( - self.page.title() - == "Visualization of Mandelbrot, Julia and Newton sets with NumPy and HTML5 canvas" - ) - wait_for_render( - self.page, "*", "" - ) - - # Assert that we get the title and canvas for each element - mandelbrot = self.page.wait_for_selector("#mandelbrot") - assert "Mandelbrot set" in mandelbrot.inner_text() - assert "") - slider_title = self.page.wait_for_selector(".bk-slider-title") - assert slider_title.inner_text() == "Amplitude: 0" - - slider_result = self.page.wait_for_selector(".bk-clearfix") - assert slider_result.inner_text() == "Amplitude is: 0" - - amplitude_bar = self.page.wait_for_selector(".noUi-connects") - amplitude_bar.click() - - # Let's confirm that slider title changed - assert slider_title.inner_text() == "Amplitude: 5" - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_panel_deckgl(self): - # XXX improve this test - self.goto("examples/panel_deckgl.html") - self.wait_for_pyscript() - assert self.page.title() == "PyScript/Panel DeckGL Demo" - wait_for_render(self.page, "*", "") - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_panel_kmeans(self): - # XXX improve this test - self.goto("examples/panel_kmeans.html") - self.wait_for_pyscript() - assert self.page.title() == "Pyscript/Panel KMeans Demo" - wait_for_render(self.page, "*", "") - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_panel_stream(self): - # XXX improve this test - self.goto("examples/panel_stream.html") - self.wait_for_pyscript() - assert self.page.title() == "PyScript/Panel Streaming Demo" - wait_for_render(self.page, "*", "") - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_repl(self): - self.goto("examples/repl.html") - self.wait_for_pyscript() - assert self.page.title() == "REPL" - self.page.wait_for_selector("py-repl") - - self.page.locator("py-repl").type("display('Hello, World!')") - self.page.wait_for_selector(".py-repl-run-button").click() - self.page.wait_for_selector("#my-repl-repl-output") - assert ( - self.page.locator("#my-repl-repl-output").text_content() == "Hello, World!" - ) - - # Confirm that using the second repl still works properly - self.page.locator("#my-repl-1").type("display(2*2)") - self.page.keyboard.press("Shift+Enter") - my_repl_1 = self.page.wait_for_selector("#my-repl-1-repl-output") - assert my_repl_1.inner_text() == "4" - self.assert_no_banners() - self.check_tutor_generated_code(modules_to_check=["antigravity.py"]) - - def test_repl2(self): - self.goto("examples/repl2.html") - self.wait_for_pyscript() - assert self.page.title() == "Custom REPL Example" - wait_for_render(self.page, "*", "") - # confirm we can import utils and run one command - self.page.locator("py-repl").type("import utils\ndisplay(utils.now())") - self.page.wait_for_selector("py-repl .py-repl-run-button").click() - # Make sure the output is in the page - self.page.wait_for_selector("#my-repl-1") - # utils.now returns current date time - content = self.page.content() - pattern = "\\d+/\\d+/\\d+, \\d+:\\d+:\\d+" # e.g. 08/09/2022 15:57:32 - assert re.search(pattern, content) - self.assert_no_banners() - self.check_tutor_generated_code(modules_to_check=["antigravity.py"]) - - def test_todo(self): - self.goto("examples/todo.html") - self.wait_for_pyscript() - assert self.page.title() == "Todo App" - wait_for_render(self.page, "*", "") - todo_input = self.page.locator("input") - submit_task_button = self.page.locator("button") - - todo_input.type("Fold laundry") - submit_task_button.click() - - first_task = self.page.locator("#task-0") - assert "Fold laundry" in first_task.inner_text() - - task_checkbox = first_task.locator("input") - # Confirm that the new task isn't checked - assert not task_checkbox.is_checked() - - # Let's mark it as done now - task_checkbox.check() - - # Basic check that the task has the line-through class - assert ( - '

Fold laundry

' - in first_task.inner_html() - ) - self.assert_no_banners() - self.check_tutor_generated_code(modules_to_check=["./utils.py", "./todo.py"]) - - @pytest.mark.xfail(reason="fails after introducing synclink, fix me soon!") - def test_todo_pylist(self): - # XXX improve this test - self.goto("examples/todo-pylist.html") - self.wait_for_pyscript() - assert self.page.title() == "Todo App" - wait_for_render(self.page, "*", "") - self.assert_no_banners() - self.check_tutor_generated_code(modules_to_check=["utils.py", "pylist.py"]) - - @pytest.mark.xfail(reason="To be moved to collective and updated, see issue #686") - def test_toga_freedom(self): - self.goto("examples/toga/freedom.html") - self.wait_for_pyscript() - assert self.page.title() in ["Loading...", "Freedom Units"] - wait_for_render(self.page, "*", "<(main|div).*?id=['\"]toga_\\d+['\"].*?>") - - page_content = self.page.content() - - assert "Fahrenheit" in page_content - assert "Celsius" in page_content - - self.page.locator("#toga_f_input").fill("105") - self.page.locator("button#toga_calculate").click() - result = self.page.locator("#toga_c_input") - assert "40.555" in result.input_value() - self.assert_no_banners() - self.check_tutor_generated_code() - - def test_webgl_raycaster_index(self): - # XXX improve this test - self.goto("examples/webgl/raycaster/index.html") - self.wait_for_pyscript() - assert self.page.title() == "Raycaster" - wait_for_render(self.page, "*", "") - self.assert_no_banners() diff --git a/pyscriptjs/tests/integration/test_zzz_docs_snippets.py b/pyscriptjs/tests/integration/test_zzz_docs_snippets.py deleted file mode 100644 index 6d5876588a5..00000000000 --- a/pyscriptjs/tests/integration/test_zzz_docs_snippets.py +++ /dev/null @@ -1,214 +0,0 @@ -import re - -from .support import PyScriptTest - - -class TestDocsSnippets(PyScriptTest): - def test_tutorials_py_click(self): - self.pyscript_run( - """ - -

- - - from pyscript import Element - import datetime - - def current_time(): - now = datetime.datetime.now() - - # Get paragraph element by id - paragraph = Element("current-time") - - # Add current time to the paragraph element - paragraph.write(now.strftime("%Y-%m-%d %H:%M:%S")) - - """ - ) - - assert self.console.log.lines[0] == self.PY_COMPLETE - btn = self.page.wait_for_selector("#get-time") - btn.click() - - current_time = self.page.wait_for_selector("#current-time") - - pattern = "\\d+-\\d+-\\d+\\s\\d+:\\d+:\\d+" # e.g. 08-09-2022 15:57:32 - assert re.search(pattern, current_time.inner_text()) - self.assert_no_banners() - - def test_tutorials_requests(self): - self.pyscript_run( - """ - - packages = ["requests", "pyodide-http"] - - - - import requests - import pyodide_http - - # Patch the Requests library so it works with Pyscript - pyodide_http.patch_all() - - # Make a request to the JSON Placeholder API - response = requests.get("https://jsonplaceholder.typicode.com/todos") - print(response.json()) - - """ - ) - - assert self.console.log.lines[0] == self.PY_COMPLETE - py_terminal = self.page.wait_for_selector("py-terminal") - # Just a small check to confirm that the response was received - assert "userId" in py_terminal.inner_text() - self.assert_no_banners() - - def test_tutorials_py_config_fetch(self): - # flake8: noqa - self.pyscript_run( - """ - - [[fetch]] - from = "https://pyscript.net/examples/" - files = ["utils.py"] - [[fetch]] - from = "https://gist.githubusercontent.com/FabioRosado/faba0b7f6ad4438b07c9ac567c73b864/raw/37603b76dc7ef7997bf36781ea0116150f727f44/" - files = ["todo.py"] - - - from todo import add_task, add_task_event - -
-
-

- To Do List -

-
-
- - -
-
- Fold laundry

' - in first_task.inner_html() - ) - self.assert_no_banners() - - def test_tutorials_py_config_interpreter(self): - self.pyscript_run( - """ - - [[interpreters]] - src = "https://cdn.jsdelivr.net/pyodide/v0.22.0a3/full/pyodide.js" - name = "pyodide-0.22.0a3" - lang = "python" - - - import pyodide - print(pyodide.__version__) - - """ - ) - - assert self.console.log.lines[0] == self.PY_COMPLETE - py_terminal = self.page.wait_for_selector("py-terminal") - assert "0.22.0a3" in py_terminal.inner_text() - self.assert_no_banners() - - def test_tutorials_writing_to_page(self): - self.pyscript_run( - """ -
- -
- -
- -
- - - - def write_to_page(): - manual_div = Element("manual-write") - manual_div.element.innerHTML = "

Hello World

" - - def display_to_div(): - display("I display things!", target="display-write") - - def print_to_page(): - print("I print things!") -
- """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - btn_manual = self.page.wait_for_selector("#manual") - btn_display = self.page.wait_for_selector("#display") - btn_print = self.page.wait_for_selector("#print") - - btn_manual.click() - manual_write_div = self.page.wait_for_selector("#manual-write") - assert "

Hello World

" in manual_write_div.inner_html() - - btn_display.click() - display_write_div = self.page.wait_for_selector("#display-write") - assert "I display things!" in display_write_div.inner_text() - - btn_print.click() - py_terminal = self.page.wait_for_selector("py-terminal") - assert "I print things!" in py_terminal.inner_text() - self.assert_no_banners() - - def test_guides_asyncio(self): - self.pyscript_run( - """ - - import asyncio - - async def main(): - for i in range(3): - print(i) - - asyncio.ensure_future(main()) - - """ - ) - assert self.console.log.lines[0] == self.PY_COMPLETE - py_terminal = self.page.wait_for_selector("py-terminal") - - assert "0\n1\n2\n" in py_terminal.inner_text() diff --git a/pyscriptjs/tests/py-unit/__init__.py b/pyscriptjs/tests/py-unit/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/pyscriptjs/tests/py-unit/conftest.py b/pyscriptjs/tests/py-unit/conftest.py deleted file mode 100644 index 5338b82dc7d..00000000000 --- a/pyscriptjs/tests/py-unit/conftest.py +++ /dev/null @@ -1,29 +0,0 @@ -"""All data required for testing examples""" -import sys -from pathlib import Path - -import pytest - -pyscriptjs = Path(__file__).parents[2] - -# add pyscript folder to path -python_source = pyscriptjs / "src" / "python" -sys.path.append(str(python_source)) - -# add Python plugins folder to path -python_plugins_source = pyscriptjs / "src" / "plugins" / "python" -sys.path.append(str(python_plugins_source)) - - -# patch pyscript module where needed -import pyscript # noqa: E402 -import pyscript_plugins_tester as ppt # noqa: E402 - -pyscript.define_custom_element = ppt.define_custom_element - - -@pytest.fixture() -def plugins_manager(): - """return a new instance of a Test version the PyScript application plugins manager""" - yield ppt.plugins_manager # PluginsManager() - ppt.plugins_manager.reset() diff --git a/pyscriptjs/tests/py-unit/js.py b/pyscriptjs/tests/py-unit/js.py deleted file mode 100644 index d42a250edfe..00000000000 --- a/pyscriptjs/tests/py-unit/js.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Mock module that emulates some of the pyodide js module features for the sake of tests""" -from unittest.mock import Mock - -document = Mock() -console = Mock() diff --git a/pyscriptjs/tests/py-unit/pyscript_plugins_tester.py b/pyscriptjs/tests/py-unit/pyscript_plugins_tester.py deleted file mode 100644 index 4a828464adf..00000000000 --- a/pyscriptjs/tests/py-unit/pyscript_plugins_tester.py +++ /dev/null @@ -1,119 +0,0 @@ -import xml.dom -from xml.dom.minidom import Node # nosec - -import pyscript - - -class classList: - """Class that (lightly) emulates the behaviour of HTML Nodes ClassList""" - - def __init__(self): - self._classes = [] - - def add(self, classname: str): - """Add classname to the classList""" - self._classes.append(classname) - - def remove(self, classname: str): - """Remove classname from the classList""" - self._classes.remove(classname) - - -class PluginsManager: - """ - Emulator of PyScript PluginsManager that can be used to simulate plugins lifecycle events - - TODO: Currently missing most of the lifecycle events in PluginsManager implementation. Need - to add more than just addPythonPlugin - """ - - def __init__(self): - self.plugins = [] - - # mapping containing all the custom elements createed by plugins - self._custom_elements = {} - - def addPythonPlugin(self, pluginInstance: pyscript.Plugin): - """ - Add a pluginInstance to the plugins managed by the PluginManager and calls - pluginInstance.init(self) to initialized the plugin with the manager - """ - pluginInstance.init(self) - self.plugins.append(pluginInstance) - - def reset(self): - """ - Unregister all plugins and related custom elements. - """ - for plugin in self.plugins: - plugin.app = None - - self.plugins = [] - self._custom_elements = {} - - -class CustomElement: - def __init__(self, plugin_class: pyscript.Plugin): - self.pyPluginInstance = plugin_class(self) - self.attributes = {} - self.innerHTML = "" - - def connectedCallback(self): - return self.pyPluginInstance.connect() - - def getAttribute(self, attr: str): - return self.attributes.get(attr) - - -def define_custom_element(tag, plugin_class: pyscript.Plugin): - """ - Mock method to emulate the behaviour of the PyScript `define_custom_element` - that basically creates a new CustomElement passing plugin_class as Python - proxy object. For more info check out the logic of the original implementation at: - - src/plugin.ts:define_custom_element - """ - ce = CustomElement(plugin_class) - plugins_manager._custom_elements[tag] = ce - - -plugins_manager = PluginsManager() - -# Init pyscript testing mocks -impl = xml.dom.getDOMImplementation() - - -class Node: - """ - Represent an HTML Node. - - This classes us an abstraction on top of xml.dom.minidom.Node - """ - - def __init__(self, el: Node): - self._el = el - self.classList = classList() - - # Automatic delegation is a simple and short boilerplate: - def __getattr__(self, attr: str): - return getattr(self._el, attr) - - def createElement(self, *args, **kws): - newEl = self._el.createElement(*args, **kws) - return Node(newEl) - - -class Document(Node): - """ - Represent an HTML Document. - - This classes us an abstraction on top of xml.dom.minidom.Document - """ - - def __init__(self): - self._el = impl.createDocument(None, "document", None) - - -pyscript.js.document = doc = Document() -pyscript.js.document.head = doc.createElement("head") -pyscript.js.document.body = doc.createElement("body") diff --git a/pyscriptjs/tests/py-unit/test_pyscript.py b/pyscriptjs/tests/py-unit/test_pyscript.py deleted file mode 100644 index 8654ee9a084..00000000000 --- a/pyscriptjs/tests/py-unit/test_pyscript.py +++ /dev/null @@ -1,207 +0,0 @@ -import sys -import textwrap -from unittest.mock import Mock - -import pyscript - - -class TestElement: - def test_id_is_correct(self): - el = pyscript.Element("something") - assert el.id == "something" - - def test_element(self, monkeypatch): - el = pyscript.Element("something") - js_mock = Mock() - js_mock.document = Mock() - call_result = "some_result" - js_mock.document.querySelector = Mock(return_value=call_result) - monkeypatch.setattr(pyscript, "js", js_mock) - assert not el._element - real_element = el.element - assert real_element - assert js_mock.document.querySelector.call_count == 1 - js_mock.document.querySelector.assert_called_with("#something") - assert real_element == call_result - - -def test_format_mime_str(): - obj = "just a string" - out, mime = pyscript.format_mime(obj) - assert out == obj - assert mime == "text/plain" - - -def test_format_mime_str_escaping(): - obj = "

hello

" - out, mime = pyscript.format_mime(obj) - assert out == "<p>hello</p>" - assert mime == "text/plain" - - -def test_format_mime_repr_escaping(): - out, mime = pyscript.format_mime(sys) - assert out == "<module 'sys' (built-in)>" - assert mime == "text/plain" - - -def test_format_mime_HTML(): - obj = pyscript.HTML("

hello

") - out, mime = pyscript.format_mime(obj) - assert out == "

hello

" - assert mime == "text/html" - - -def test_uses_top_level_await(): - # Basic Case - src = "x = 1" - assert pyscript.uses_top_level_await(src) is False - - # Comments are not top-level await - src = textwrap.dedent( - """ - #await async for async with asyncio - """ - ) - - assert pyscript.uses_top_level_await(src) is False - - # Top-level-await cases - src = textwrap.dedent( - """ - async def foo(): - pass - await foo - """ - ) - assert pyscript.uses_top_level_await(src) is True - - src = textwrap.dedent( - """ - async with object(): - pass - """ - ) - assert pyscript.uses_top_level_await(src) is True - - src = textwrap.dedent( - """ - async for _ in range(10): - pass - """ - ) - assert pyscript.uses_top_level_await(src) is True - - # Acceptable await/async for/async with cases - src = textwrap.dedent( - """ - async def foo(): - await foo() - """ - ) - assert pyscript.uses_top_level_await(src) is False - - src = textwrap.dedent( - """ - async def foo(): - async with object(): - pass - """ - ) - assert pyscript.uses_top_level_await(src) is False - - src = textwrap.dedent( - """ - async def foo(): - async for _ in range(10): - pass - """ - ) - assert pyscript.uses_top_level_await(src) is False - - -def test_set_version_info(): - version_string = "1234.56.78.ABCD" - pyscript._set_version_info(version_string) - assert pyscript.__version__ == version_string - assert pyscript.version_info == (1234, 56, 78, "ABCD") - # - # for backwards compatibility, should be killed eventually - assert pyscript.PyScript.__version__ == pyscript.__version__ - assert pyscript.PyScript.version_info == pyscript.version_info - - -class MyDeprecatedGlobal(pyscript.DeprecatedGlobal): - """ - A subclass of DeprecatedGlobal, for tests. - - Instead of showing warnings into the DOM (which we don't have inside unit - tests), we record the warnings into a field. - """ - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.warnings = [] - - def _show_warning(self, message): - self.warnings.append(message) - - -class TestDeprecatedGlobal: - def test_repr(self): - glob = MyDeprecatedGlobal("foo", None, "my message") - assert repr(glob) == "" - - def test_show_warning_override(self): - """ - Test that our overriding of _show_warning actually works. - """ - glob = MyDeprecatedGlobal("foo", None, "my message") - glob._show_warning("foo") - glob._show_warning("bar") - assert glob.warnings == ["foo", "bar"] - - def test_getattr(self): - class MyFakeObject: - name = "FooBar" - - glob = MyDeprecatedGlobal("MyFakeObject", MyFakeObject, "this is my warning") - assert glob.name == "FooBar" - assert glob.warnings == ["this is my warning"] - - def test_dont_show_warning_twice(self): - class MyFakeObject: - name = "foo" - surname = "bar" - - glob = MyDeprecatedGlobal("MyFakeObject", MyFakeObject, "this is my warning") - assert glob.name == "foo" - assert glob.surname == "bar" - assert len(glob.warnings) == 1 - - def test_call(self): - def foo(x, y): - return x + y - - glob = MyDeprecatedGlobal("foo", foo, "this is my warning") - assert glob(1, y=2) == 3 - assert glob.warnings == ["this is my warning"] - - def test_iter(self): - d = {"a": 1, "b": 2, "c": 3} - glob = MyDeprecatedGlobal("d", d, "this is my warning") - assert list(glob) == ["a", "b", "c"] - assert glob.warnings == ["this is my warning"] - - def test_getitem(self): - d = {"a": 1, "b": 2, "c": 3} - glob = MyDeprecatedGlobal("d", d, "this is my warning") - assert glob["a"] == 1 - assert glob.warnings == ["this is my warning"] - - def test_setitem(self): - d = {"a": 1, "b": 2, "c": 3} - glob = MyDeprecatedGlobal("d", d, "this is my warning") - glob["a"] = 100 - assert glob.warnings == ["this is my warning"] - assert glob["a"] == 100 diff --git a/pyscriptjs/tests/py-unit/test_python_plugins.py b/pyscriptjs/tests/py-unit/test_python_plugins.py deleted file mode 100644 index cd4db7af64b..00000000000 --- a/pyscriptjs/tests/py-unit/test_python_plugins.py +++ /dev/null @@ -1,171 +0,0 @@ -import html -from unittest.mock import Mock - -import py_markdown -import py_tutor -import pyscript -import pyscript_plugins_tester as ppt - -TUTOR_SOURCE = """ - - packages = [ - "folium", - "pandas" - ] - plugins = [ - "../build/plugins/python/py_tutor.py" - ] - - - -import folium -import json -import pandas as pd - -from pyodide.http import open_url - -# the rest of the code goes one - -""" - - -class TestPyMarkdown: - def test_plugin_hooks(self, monkeypatch): - console_mock = Mock() - monkeypatch.setattr(py_markdown, "console", console_mock) - config = "just a config" - interpreter = "just an interpreter" - - py_markdown.plugin.configure(config) - console_mock.log.assert_called_with("configuration received: just a config") - - py_markdown.plugin.afterStartup(interpreter) - console_mock.log.assert_called_with( - "interpreter received:", "just an interpreter" - ) - - -class TestPyTutor: - def check_prism_added(self): - """ - Assert that the add_prism method has been correctly executed and the - related prism assets have been added to the page head - """ - # GIVEN a previous call to py_tutor.plugin.append_script_to_page - head = pyscript.js.document.head - - # EXPECT the head to contain a link element pointing to the prism.min.css - links = head.getElementsByTagName("link") - assert len(links) == 1 - link = links[0] - assert link.type == "text/css" - assert link.rel == "stylesheet" - assert link.href == "./assets/prism/prism.min.css" - - # EXPECT the head to contain a script src == prism.min.js - scripts = head.getElementsByTagName("script") - assert len(scripts) == 1 - script = scripts[0] - assert script.type == "text/javascript" - assert script.src == "./assets/prism/prism.min.js" - - def check_append_script_to_page(self): - """ - Assert that the append_script_to_page has been correctly executed and the - py_tutor.PAGE_SCRIPT code needed for the plugin JS animation has been added - to the page body - """ - # GIVEN a previous call to py_tutor.plugin.append_script_to_page - body = pyscript.js.document.body - - # EXPECT the body of the page to contain a script of type text/javascript - # and that contains the py_tutor.PAGE_SCRIPT script - scripts = body.getElementsByTagName("script") - assert len(scripts) == 1 - script = scripts[0] - assert script.type == "text/javascript" - - # Check the actual JS script code - # To do so we have 2 methods (it depends on browser support so we check either...) - if script.childNodes: - # in this case it means the content has been added as a child element - node = script.childNodes[0] - assert node.data == py_tutor.PAGE_SCRIPT - else: - assert script.text == py_tutor.PAGE_SCRIPT - - def check_create_code_section(self): - """ - Assert that the create_code_section has been correctly executed and the - related code section has been created and added to the page. - """ - # GIVEN a previous call to py_tutor.plugin.check_create_code_section - console = py_tutor.js.console - - # EXPECT the console to have the messages printed by the plugin while - # executing the plugin operations - console.info.assert_any_call("Creating code introspection section.") - console.info.assert_any_call("Creating new code section element.") - - # EXPECT the page body to contain a section with the input source code - body = pyscript.js.document.body - sections = body.getElementsByTagName("section") - section = sections[0] - assert "code" in section.classList._classes - section_innerHTML = py_tutor.TEMPLATE_CODE_SECTION.format( - source=html.escape(TUTOR_SOURCE), modules_section="" - ) - assert html.escape(TUTOR_SOURCE) in section.innerHTML - assert section.innerHTML == section_innerHTML - - def test_connected_calls(self, plugins_manager: ppt.PluginsManager): - """ - Test that all parts of the plugin have been added to the page body and head - properly. This test effectively calls `self.check_prism_added`, - `self.check_append_script_to_page` and `check_create_code_section` assert - the new nodes have been added properly. - """ - # GIVEN THAT we add the plugin to the app plugin manager - # this will: - # - init the plugin instance passing the plugins_manager as parent app - # - add the plugin instance to plugins_manager.plugins - assert not py_tutor.plugin.app - plugins_manager.addPythonPlugin(py_tutor.plugin) - - # EXPECT: the plugin app to now be the plugin manager - assert py_tutor.plugin.app == plugins_manager - tutor_ce = plugins_manager._custom_elements["py-tutor"] - # tutor_ce_python_instance = tutor_ce.pyPluginInstance - # GIVEN: The following innerHTML on the ce elements - tutor_ce.innerHTML = TUTOR_SOURCE - - # GIVEN: the CustomElement connectedCallback gets called - tutor_ce.connectedCallback() - - # EXPECT: the - self.check_prism_added() - - self.check_append_script_to_page() - - self.check_create_code_section() - - def test_plugin_registered(self, plugins_manager: ppt.PluginsManager): - """ - Test that, when registered, plugin actually has an app attribute set - and that it's present in plugins manager plugins list. - """ - # EXPECT py_tutor.plugin to not have any app associate - assert not py_tutor.plugin.app - - # EXPECT: the plugin manager to not have any plugin registered - assert not plugins_manager.plugins - - # GIVEN THAT we add the plugin to the app plugin manager - plugins_manager.addPythonPlugin(py_tutor.plugin) - - # EXPECT: the plugin app to now be the plugin manager - assert py_tutor.plugin.app == plugins_manager - assert "py-tutor" in py_tutor.plugin._custom_elements - - # EXPECT: the pytutor.plugin manager to be part of - assert py_tutor.plugin in plugins_manager.plugins diff --git a/pyscriptjs/tests/unit/calculateFetchPaths.test.ts b/pyscriptjs/tests/unit/calculateFetchPaths.test.ts deleted file mode 100644 index 31a4d8d7280..00000000000 --- a/pyscriptjs/tests/unit/calculateFetchPaths.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { calculateFetchPaths } from '../../src/plugins/calculateFetchPaths'; -import { FetchConfig } from '../../src/pyconfig'; - -describe('CalculateFetchPaths', () => { - it('should calculate paths when only from is provided', () => { - const fetch_cfg: FetchConfig[] = [{ from: 'http://a.com/data.csv' }]; - const res = calculateFetchPaths(fetch_cfg); - expect(res).toStrictEqual([{ url: 'http://a.com/data.csv', path: 'data.csv' }]); - }); - - it('should calculate paths when only files is provided', () => { - const fetch_cfg: FetchConfig[] = [{ files: ['foo/__init__.py', 'foo/mod.py', 'foo2/mod.py'] }]; - const res = calculateFetchPaths(fetch_cfg); - expect(res).toStrictEqual([ - { url: 'foo/__init__.py', path: 'foo/__init__.py' }, - { url: 'foo/mod.py', path: 'foo/mod.py' }, - { url: 'foo2/mod.py', path: 'foo2/mod.py' }, - ]); - }); - - it('should calculate paths when files and to_folder is provided', () => { - const fetch_cfg: FetchConfig[] = [{ files: ['foo/__init__.py', 'foo/mod.py'], to_folder: '/my/lib/' }]; - const res = calculateFetchPaths(fetch_cfg); - expect(res).toStrictEqual([ - { url: 'foo/__init__.py', path: '/my/lib/foo/__init__.py' }, - { url: 'foo/mod.py', path: '/my/lib/foo/mod.py' }, - ]); - }); - - it('should calculate paths when from and files and to_folder is provided', () => { - const fetch_cfg: FetchConfig[] = [ - { from: 'http://a.com/download/', files: ['foo/__init__.py', 'foo/mod.py'], to_folder: '/my/lib/' }, - ]; - const res = calculateFetchPaths(fetch_cfg); - expect(res).toStrictEqual([ - { url: 'http://a.com/download/foo/__init__.py', path: '/my/lib/foo/__init__.py' }, - { url: 'http://a.com/download/foo/mod.py', path: '/my/lib/foo/mod.py' }, - ]); - }); - - it("should error out while calculating paths when filename cannot be determined from 'from'", () => { - const fetch_cfg: FetchConfig[] = [{ from: 'http://google.com/', to_folder: '/tmp' }]; - expect(() => calculateFetchPaths(fetch_cfg)).toThrowError( - "Couldn't determine the filename from the path http://google.com/", - ); - }); - - it('should calculate paths when to_file is explicitly supplied', () => { - const fetch_cfg: FetchConfig[] = [{ from: 'http://a.com/data.csv?version=1', to_file: 'pkg/tmp/data.csv' }]; - const res = calculateFetchPaths(fetch_cfg); - expect(res).toStrictEqual([{ path: 'pkg/tmp/data.csv', url: 'http://a.com/data.csv?version=1' }]); - }); - - it('should error out when both to_file and files parameters are provided', () => { - const fetch_cfg: FetchConfig[] = [ - { from: 'http://a.com/data.csv?version=1', to_file: 'pkg/tmp/data.csv', files: ['a.py', 'b.py'] }, - ]; - expect(() => calculateFetchPaths(fetch_cfg)).toThrowError( - "Cannot use 'to_file' and 'files' parameters together!", - ); - }); -}); diff --git a/pyscriptjs/tests/unit/exceptions.test.ts b/pyscriptjs/tests/unit/exceptions.test.ts deleted file mode 100644 index fc276e4fd50..00000000000 --- a/pyscriptjs/tests/unit/exceptions.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { expect, it, jest, describe, afterEach } from '@jest/globals'; -import { _createAlertBanner, UserError, FetchError, ErrorCode } from '../../src/exceptions'; - -describe('Test _createAlertBanner', () => { - afterEach(() => { - // Ensure we always have a clean body - document.body.innerHTML = `
Hello World
`; - }); - - it("error level shouldn't contain close button", async () => { - _createAlertBanner('Something went wrong!', 'error'); - - const banner = document.getElementsByClassName('alert-banner'); - const closeButton = document.getElementById('alert-close-button'); - expect(banner.length).toBe(1); - expect(banner[0].innerHTML).toBe('Something went wrong!'); - expect(closeButton).toBeNull(); - }); - - it('warning level should contain close button', async () => { - _createAlertBanner('This is a warning', 'warning'); - - const banner = document.getElementsByClassName('alert-banner'); - const closeButton = document.getElementById('alert-close-button'); - expect(banner.length).toBe(1); - expect(banner[0].innerHTML).toContain('This is a warning'); - expect(closeButton).not.toBeNull(); - }); - - it('error level banner should log to console', async () => { - const logSpy = jest.spyOn(console, 'error'); - - _createAlertBanner('Something went wrong!'); - - expect(logSpy).toHaveBeenCalledWith('Something went wrong!'); - }); - - it('warning level banner should log to console', async () => { - const logSpy = jest.spyOn(console, 'warn'); - - _createAlertBanner('This warning', 'warning'); - - expect(logSpy).toHaveBeenCalledWith('This warning'); - }); - - it('close button should remove element from page', async () => { - let banner = document.getElementsByClassName('alert-banner'); - expect(banner.length).toBe(0); - - _createAlertBanner('Warning!', 'warning'); - - // Just a sanity check - banner = document.getElementsByClassName('alert-banner'); - expect(banner.length).toBe(1); - - const closeButton = document.getElementById('alert-close-button'); - if (closeButton) { - closeButton.click(); - // Confirm that clicking the close button, removes the element - banner = document.getElementsByClassName('alert-banner'); - expect(banner.length).toBe(0); - } else { - fail('Unable to find close button on the page, but should exist'); - } - }); - - it("toggling logging off on error alert shouldn't log to console", async () => { - const errorLogSpy = jest.spyOn(console, 'error'); - - _createAlertBanner('Test error', 'error', 'text', false); - expect(errorLogSpy).not.toHaveBeenCalledWith('Test error'); - }); - - it("toggling logging off on warning alert shouldn't log to console", async () => { - const warnLogSpy = jest.spyOn(console, 'warn'); - _createAlertBanner('Test warning', 'warning', 'text', false); - expect(warnLogSpy).not.toHaveBeenCalledWith('Test warning'); - }); - - it('_createAlertbanner messageType text writes message to content', async () => { - let banner = document.getElementsByClassName('alert-banner'); - expect(banner.length).toBe(0); - - const message = '

Test message

'; - _createAlertBanner(message, 'error', 'text'); - banner = document.getElementsByClassName('alert-banner'); - - expect(banner.length).toBe(1); - expect(banner[0].innerHTML).toBe('<p>Test message</p>'); - expect(banner[0].textContent).toBe(message); - }); - - it('_createAlertbanner messageType html writes message to innerHTML', async () => { - let banner = document.getElementsByClassName('alert-banner'); - expect(banner.length).toBe(0); - - const message = '

Test message

'; - _createAlertBanner(message, 'error', 'html'); - banner = document.getElementsByClassName('alert-banner'); - - expect(banner.length).toBe(1); - expect(banner[0].innerHTML).toBe(message); - expect(banner[0].textContent).toBe('Test message'); - }); -}); - -describe('Test Exceptions', () => { - it('UserError contains errorCode and shows in message', async () => { - const errorCode = ErrorCode.BAD_CONFIG; - const message = 'Test error'; - const userError = new UserError(ErrorCode.BAD_CONFIG, message); - expect(userError.errorCode).toBe(errorCode); - expect(userError.message).toBe(`(${errorCode}): ${message}`); - }); - - it('FetchError contains errorCode and shows in message', async () => { - const errorCode = ErrorCode.FETCH_NOT_FOUND_ERROR; - const message = 'Test error'; - const fetchError = new FetchError(errorCode, message); - expect(fetchError.errorCode).toBe(errorCode); - expect(fetchError.message).toBe(`(${errorCode}): ${message}`); - }); -}); diff --git a/pyscriptjs/tests/unit/fetch.test.ts b/pyscriptjs/tests/unit/fetch.test.ts deleted file mode 100644 index c204a04101b..00000000000 --- a/pyscriptjs/tests/unit/fetch.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, it, expect, jest } from '@jest/globals'; -import { FetchError, ErrorCode } from '../../src/exceptions'; -import { robustFetch } from '../../src/fetch'; -import { Response } from 'node-fetch'; - -describe('robustFetch', () => { - it('should return a response object', async () => { - global.fetch = jest.fn(() => Promise.resolve(new Response((status = '200'), 'Hello World'))); - - const response = await robustFetch('https://pyscript.net'); - expect(response).toBeInstanceOf(Response); - expect(response.status).toBe(200); - }); - - it('receiving a 404 when fetching should throw FetchError with the right errorCode', async () => { - global.fetch = jest.fn(() => Promise.resolve(new Response('Not Found', { status: 404 }))); - - const url = 'https://pyscript.net/non-existent-page'; - const expectedError = new FetchError( - ErrorCode.FETCH_NOT_FOUND_ERROR, - `Fetching from URL ${url} failed with error 404 (Not Found). ` + `Are your filename and path correct?`, - ); - - expect(() => robustFetch(url)).rejects.toThrow(expectedError); - }); - - it('receiving a 401 when fetching should throw FetchError with the right errorCode', async () => { - global.fetch = jest.fn(() => Promise.resolve(new Response('', { status: 401 }))); - - const url = 'https://pyscript.net/protected-page'; - const expectedError = new FetchError( - ErrorCode.FETCH_UNAUTHORIZED_ERROR, - `Fetching from URL ${url} failed with error 401 (Unauthorized). ` + `Are your filename and path correct?`, - ); - - expect(() => robustFetch(url)).rejects.toThrow(expectedError); - }); - - it('receiving a 403 when fetching should throw FetchError with the right errorCode', async () => { - global.fetch = jest.fn(() => Promise.resolve(new Response('', { status: 403 }))); - - const url = 'https://pyscript.net/secret-page'; - const expectedError = new FetchError( - ErrorCode.FETCH_FORBIDDEN_ERROR, - `Fetching from URL ${url} failed with error 403 (Forbidden). ` + `Are your filename and path correct?`, - ); - - expect(() => robustFetch(url)).rejects.toThrow(expectedError); - }); - - it('receiving a 500 when fetching should throw FetchError with the right errorCode', async () => { - global.fetch = jest.fn(() => Promise.resolve(new Response('Not Found', { status: 500 }))); - - const url = 'https://pyscript.net/protected-page'; - const expectedError = new FetchError( - ErrorCode.FETCH_SERVER_ERROR, - `Fetching from URL ${url} failed with error 500 (Internal Server Error). ` + - `Are your filename and path correct?`, - ); - - expect(() => robustFetch(url)).rejects.toThrow(expectedError); - }); - - it('receiving a 503 when fetching should throw FetchError with the right errorCode', async () => { - global.fetch = jest.fn(() => Promise.resolve(new Response('Not Found', { status: 503 }))); - - const url = 'https://pyscript.net/protected-page'; - const expectedError = new FetchError( - ErrorCode.FETCH_UNAVAILABLE_ERROR, - `Fetching from URL ${url} failed with error 503 (Service Unavailable). ` + - `Are your filename and path correct?`, - ); - - expect(() => robustFetch(url)).rejects.toThrow(expectedError); - }); - - it('handle TypeError when using a bad url', async () => { - global.fetch = jest.fn(() => Promise.reject(new TypeError('Failed to fetch'))); - - const url = 'https://pyscript.net/protected-page'; - const expectedError = new FetchError( - ErrorCode.FETCH_ERROR, - `Fetching from URL ${url} failed with error 'Failed to fetch'. Are your filename and path correct?`, - ); - - expect(() => robustFetch(url)).rejects.toThrow(expectedError); - }); - - it('handle failed to fetch when using local file', async () => { - global.fetch = jest.fn(() => Promise.reject(new TypeError('Failed to fetch'))); - - const url = './my-awesome-pyscript.py'; - - const expectedError = new FetchError( - ErrorCode.FETCH_ERROR, - `PyScript: Access to local files - (using "Paths:" in <py-config>) - 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. - `, - ); - - expect(() => robustFetch(url)).rejects.toThrow(expectedError); - }); -}); diff --git a/pyscriptjs/tests/unit/logger.test.ts b/pyscriptjs/tests/unit/logger.test.ts deleted file mode 100644 index 641327406be..00000000000 --- a/pyscriptjs/tests/unit/logger.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { jest } from '@jest/globals'; -import { getLogger } from '../../src/logger'; - -describe('getLogger', () => { - it('getLogger caches results', () => { - let a1 = getLogger('a'); - let b = getLogger('b'); - let a2 = getLogger('a'); - - expect(a1).not.toBe(b); - expect(a1).toBe(a2); - }); - - it('logger.info prints to console.info', () => { - console.info = jest.fn(); - - const logger = getLogger('prefix1'); - logger.info('hello world'); - expect(console.info).toHaveBeenCalledWith('[prefix1] hello world'); - }); - - it('logger.info handles multiple args', () => { - console.info = jest.fn(); - - const logger = getLogger('prefix2'); - logger.info('hello', 'world', 1, 2, 3); - expect(console.info).toHaveBeenCalledWith('[prefix2] hello', 'world', 1, 2, 3); - }); - - it('logger.{debug,warn,error} also works', () => { - console.info = jest.fn(); - console.debug = jest.fn(); - console.warn = jest.fn(); - console.error = jest.fn(); - - const logger = getLogger('prefix3'); - logger.debug('this is a debug'); - logger.warn('this is a warning'); - logger.error('this is an error'); - - expect(console.info).not.toHaveBeenCalled(); - expect(console.debug).toHaveBeenCalledWith('[prefix3] this is a debug'); - expect(console.warn).toHaveBeenCalledWith('[prefix3] this is a warning'); - expect(console.error).toHaveBeenCalledWith('[prefix3] this is an error'); - }); -}); diff --git a/pyscriptjs/tests/unit/main.test.ts b/pyscriptjs/tests/unit/main.test.ts deleted file mode 100644 index d8afaa4e3e8..00000000000 --- a/pyscriptjs/tests/unit/main.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, it, expect } from '@jest/globals'; - -describe('Placeholder', () => { - it('this is a placeholder, we need to fix and re-enable the commented out tests', () => { - expect(true).toBe(true); - }); -}); - -/* -describe('Test withUserErrorHandler', () => { - class MyApp extends PyScriptApp { - myRealMain: any; - - constructor(myRealMain) { - super(); - this.myRealMain = myRealMain; - } - - async _realMain() { - await this.myRealMain(); - } - } - - beforeEach(() => { - // Ensure we always have a clean body - document.body.innerHTML = `
Hello World
`; - }); - - it("userError doesn't stop execution", async () => { - function myRealMain() { - throw new UserError(ErrorCode.GENERIC, 'Computer says no'); - } - - const app = new MyApp(myRealMain); - await app.main(); - const banners = document.getElementsByClassName('alert-banner'); - expect(banners.length).toBe(1); - expect(banners[0].innerHTML).toBe('(PY0000): Computer says no'); - }); - - it('userError escapes by default', async () => { - function myRealMain() { - throw new UserError(ErrorCode.GENERIC, 'hello
'); - } - - const app = new MyApp(myRealMain); - await app.main(); - const banners = document.getElementsByClassName('alert-banner'); - expect(banners.length).toBe(1); - expect(banners[0].innerHTML).toBe('(PY0000): hello <br>'); - }); - - it("userError messageType=html don't escape", async () => { - function myRealMain() { - throw new UserError(ErrorCode.GENERIC, 'hello
', 'html'); - } - - const app = new MyApp(myRealMain); - await app.main(); - const banners = document.getElementsByClassName('alert-banner'); - expect(banners.length).toBe(1); - expect(banners[0].innerHTML).toBe('(PY0000): hello
'); - }); - - it('any other exception should stop execution and raise', async () => { - function myRealMain() { - throw new Error('Explosions!'); - } - - const app = new MyApp(myRealMain); - expect.assertions(1); - await expect(async () => await app.main()).resolves.toThrow(new Error('Explosions!')); - }); -}); -*/ diff --git a/pyscriptjs/tests/unit/pyconfig.test.ts b/pyscriptjs/tests/unit/pyconfig.test.ts deleted file mode 100644 index 78e296605ec..00000000000 --- a/pyscriptjs/tests/unit/pyconfig.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { jest, describe, it, expect } from '@jest/globals'; -import { loadConfigFromElement, defaultConfig } from '../../src/pyconfig'; -import { version } from '../../src/version'; -import { UserError } from '../../src/exceptions'; - -// inspired by trump typos -const covfefeConfig = { - name: 'covfefe', - interpreters: [ - { - src: '/demo/covfefe.js', - name: 'covfefe', - lang: 'covfefe', - }, - ], - wonderful: 'disgrace', -}; - -const covfefeConfigToml = ` -name = "covfefe" - -wonderful = "hijacked" - -[[interpreters]] -src = "/demo/covfefe.js" -name = "covfefe" -lang = "covfefe" -`; - -// ideally, I would like to be able to just do "new HTMLElement" in the tests -// below, but it is not permitted. The easiest work around is to create a fake -// custom element: not that we are not using any specific feature of custom -// elements: the sole purpose to FakeElement is to be able to instantiate them -// in the tests. -class FakeElement extends HTMLElement { - constructor() { - super(); - } -} -customElements.define('fake-element', FakeElement); - -function make_config_element(attrs) { - const el = new FakeElement(); - for (const [key, value] of Object.entries(attrs)) { - el.setAttribute(key, value as string); - } - return el; -} - -describe('loadConfigFromElement', () => { - const xhrMockClass = () => ({ - open: jest.fn(), - send: jest.fn(), - responseText: JSON.stringify(covfefeConfig), - }); - // @ts-ignore - window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass); - - it('should load the default config', () => { - const config = loadConfigFromElement(null); - expect(config).toBe(defaultConfig); - expect(config.pyscript.version).toBe(version); - }); - - it('an empty should load the default config', () => { - const el = make_config_element({}); - let config = loadConfigFromElement(el); - expect(config).toBe(defaultConfig); - expect(config.pyscript.version).toBe(version); - }); - - it('should load the JSON config from inline', () => { - const el = make_config_element({ type: 'json' }); - el.innerHTML = JSON.stringify(covfefeConfig); - const config = loadConfigFromElement(el); - expect(config.interpreters[0].lang).toBe('covfefe'); - expect(config.pyscript?.time).not.toBeNull(); - // schema_version wasn't present in `inline config` but is still set due to merging with default - expect(config.schema_version).toBe(1); - }); - - it('should load the JSON config from src attribute', () => { - const el = make_config_element({ type: 'json', src: '/covfefe.json' }); - const config = loadConfigFromElement(el); - expect(config.interpreters[0].lang).toBe('covfefe'); - expect(config.pyscript?.time).not.toBeNull(); - // wonderful is an extra key supplied by the user and is unaffected by merging process - expect(config.wonderful).toBe('disgrace'); - // schema_version wasn't present in `config from src` but is still set due to merging with default - expect(config.schema_version).toBe(1); - }); - - it('should load the JSON config from both inline and src', () => { - const el = make_config_element({ type: 'json', src: '/covfefe.json' }); - el.innerHTML = JSON.stringify({ version: '0.2a', wonderful: 'hijacked' }); - const config = loadConfigFromElement(el); - expect(config.interpreters[0].lang).toBe('covfefe'); - expect(config.pyscript?.time).not.toBeNull(); - // config from src had an extra key "wonderful" with value "disgrace" - // inline config had the same extra key "wonderful" with value "hijacked" - // the merge process works for extra keys that clash as well - // so the final value is "hijacked" since inline takes precedence over src - expect(config.wonderful).toBe('hijacked'); - // version wasn't present in `config from src` but is still set due to merging with default and inline - expect(config.version).toBe('0.2a'); - }); - - it('should be able to load an inline TOML config', () => { - // TOML is the default type - const el = make_config_element({}); - el.innerHTML = covfefeConfigToml; - const config = loadConfigFromElement(el); - expect(config.interpreters[0].lang).toBe('covfefe'); - expect(config.pyscript?.time).not.toBeNull(); - // schema_version wasn't present in `inline config` but is still set due to merging with default - expect(config.schema_version).toBe(1); - expect(config.wonderful).toBe('hijacked'); - }); - - it('should NOT be able to load an inline config in JSON format with type as TOML', () => { - const el = make_config_element({}); - el.innerHTML = JSON.stringify(covfefeConfig); - expect(() => loadConfigFromElement(el)).toThrow( - /config supplied: {.*} is an invalid TOML and cannot be parsed/, - ); - }); - - it('should NOT be able to load an inline config in TOML format with type as JSON', () => { - const el = make_config_element({ type: 'json' }); - el.innerHTML = covfefeConfigToml; - expect(() => loadConfigFromElement(el)).toThrow(UserError); - }); - - it('should NOT be able to load an inline TOML config with a JSON config from src with type as toml', () => { - const el = make_config_element({ src: '/covfefe.json' }); - el.innerHTML = covfefeConfigToml; - expect(() => loadConfigFromElement(el)).toThrow( - /config supplied: {.*} is an invalid TOML and cannot be parsed/, - ); - }); - - it('should NOT be able to load an inline TOML config with a JSON config from src with type as json', () => { - const el = make_config_element({ type: 'json', src: '/covfefe.json' }); - el.innerHTML = covfefeConfigToml; - expect(() => loadConfigFromElement(el)).toThrow(UserError); - }); - - it('should error out when passing an invalid JSON', () => { - const el = make_config_element({ type: 'json' }); - el.innerHTML = '[['; - expect(() => loadConfigFromElement(el)).toThrow(UserError); - }); - - it('should error out when passing an invalid TOML', () => { - const el = make_config_element({}); - el.innerHTML = '[['; - expect(() => loadConfigFromElement(el)).toThrow(UserError); - }); - - it('should not escape characters like &', () => { - const el = make_config_element({ type: 'json' }); - el.innerHTML = JSON.stringify({ - fetch: [{ from: 'https://datausa.io/api/data?drilldowns=Nation&measures=Population' }], - }); - const config = loadConfigFromElement(el); - expect(config.fetch[0].from).toBe('https://datausa.io/api/data?drilldowns=Nation&measures=Population'); - }); -}); diff --git a/pyscriptjs/tests/unit/pyodide.test.ts b/pyscriptjs/tests/unit/pyodide.test.ts deleted file mode 100644 index 49539cb3e2b..00000000000 --- a/pyscriptjs/tests/unit/pyodide.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type { AppConfig } from '../../src/pyconfig'; -import { InterpreterClient } from '../../src/interpreter_client'; -import { CaptureStdio } from '../../src/stdio'; -import * as Synclink from 'synclink'; -import { describe, beforeAll, afterAll, it, expect } from '@jest/globals'; -// We can't import RemoteInterpreter at top level because we need to mock the -// Python package in setup.ts -// But we can import the types at top level. -// TODO: is there a better way to handle this? -import type { RemoteInterpreter } from '../../src/remote_interpreter'; - -describe('RemoteInterpreter', () => { - let interpreter: InterpreterClient; - let stdio: CaptureStdio = new CaptureStdio(); - let RemoteInterpreter; - const { port1, port2 } = new MessageChannel(); - beforeAll(async () => { - const SRC = '../pyscriptjs/node_modules/pyodide/pyodide.js'; - const config: AppConfig = { interpreters: [{ src: SRC }] }; - // Dynamic import of RemoteInterpreter sees our mocked Python package. - ({ RemoteInterpreter } = await import('../../src/remote_interpreter')); - const remote_interpreter = new RemoteInterpreter(SRC); - - port1.start(); - port2.start(); - Synclink.expose(remote_interpreter, port2); - const wrapped_remote_interpreter = Synclink.wrap(port1); - interpreter = new InterpreterClient( - config, - stdio, - wrapped_remote_interpreter as Synclink.Remote, - remote_interpreter, - ); - - /** - * Since import { loadPyodide } from 'pyodide'; - * is not used inside `src/pyodide.ts`, the function - * `interpreter.loadInterpreter();` below which calls - * `loadPyodide()` results in an expected issue of: - * ReferenceError: loadPyodide is not defined - * - * To make jest happy, while also not importing - * explicitly inside `src/pyodide.ts`, the - * following lines - so as to dynamically import - * and make it available in the global namespace - * - are used. - * - * Pyodide uses a "really hacky" method to get the - * URL/Path where packages/package data are stored; - * it throws an error, catches it, and parses it. In - * Jest, this calculated path is different than in - * the browser/Node, so files cannot be found and the - * test fails. We set indexURL below the correct location - * to fix this. - * See https://github.com/pyodide/pyodide/blob/7dfee03a82c19069f714a09da386547aeefef242/src/js/pyodide.ts#L161-L179 - */ - const pyodideSpec = await import('pyodide'); - global.loadPyodide = async options => - pyodideSpec.loadPyodide(Object.assign({ indexURL: '../pyscriptjs/node_modules/pyodide/' }, options)); - await interpreter.initializeRemote(); - }); - - afterAll(async () => { - port1.close(); - port2.close(); - }); - - it('should check if interpreter is an instance of abstract Interpreter', async () => { - expect(interpreter).toBeInstanceOf(InterpreterClient); - }); - - it('should check if interpreter is an instance of RemoteInterpreter', async () => { - expect(interpreter._unwrapped_remote).toBeInstanceOf(RemoteInterpreter); - }); - - it('should check if interpreter can run python code asynchronously', async () => { - expect((await interpreter.run('2+3')).result).toBe(5); - }); - - it('should capture stdout', async () => { - stdio.reset(); - await interpreter.run("print('hello')"); - expect(stdio.captured_stdout).toBe('hello\n'); - }); - - it('should check if interpreter is able to load a package', async () => { - stdio.reset(); - await interpreter._unwrapped_remote.loadPackage('numpy'); - await interpreter.run('import numpy as np'); - await interpreter.run('x = np.ones((10,))'); - await interpreter.run('print(x)'); - expect(stdio.captured_stdout).toBe('[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]\n'); - }); -}); diff --git a/pyscriptjs/tests/unit/setup.ts b/pyscriptjs/tests/unit/setup.ts deleted file mode 100644 index 2b33bfb79a4..00000000000 --- a/pyscriptjs/tests/unit/setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { jest } from '@jest/globals'; -import { directoryManifest } from '../../directoryManifest.mjs'; - -jest.unstable_mockModule('../../src/python_package', async () => ({ - python_package: await directoryManifest('./src/python/'), -})); diff --git a/pyscriptjs/tests/unit/stdio.test.ts b/pyscriptjs/tests/unit/stdio.test.ts deleted file mode 100644 index 562977765ff..00000000000 --- a/pyscriptjs/tests/unit/stdio.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { expect } from '@jest/globals'; -import { type Stdio, CaptureStdio, StdioMultiplexer, TargetedStdio } from '../../src/stdio'; - -describe('CaptureStdio', () => { - it('captured streams are initialized to empty string', () => { - let stdio = new CaptureStdio(); - expect(stdio.captured_stdout).toBe(''); - expect(stdio.captured_stderr).toBe(''); - }); - - it('stdout() and stderr() captures', () => { - let stdio = new CaptureStdio(); - stdio.stdout_writeline('hello'); - stdio.stdout_writeline('world'); - stdio.stderr_writeline('this is an error'); - expect(stdio.captured_stdout).toBe('hello\nworld\n'); - expect(stdio.captured_stderr).toBe('this is an error\n'); - }); - - it('reset() works', () => { - let stdio = new CaptureStdio(); - stdio.stdout_writeline('aaa'); - stdio.stderr_writeline('bbb'); - stdio.reset(); - expect(stdio.captured_stdout).toBe(''); - expect(stdio.captured_stderr).toBe(''); - }); -}); - -describe('StdioMultiplexer', () => { - let a: CaptureStdio; - let b: CaptureStdio; - let multi: StdioMultiplexer; - - beforeEach(() => { - a = new CaptureStdio(); - b = new CaptureStdio(); - multi = new StdioMultiplexer(); - }); - - it('works without listeners', () => { - // no listeners, messages are ignored - multi.stdout_writeline('out 1'); - multi.stderr_writeline('err 1'); - expect(a.captured_stdout).toBe(''); - expect(a.captured_stderr).toBe(''); - expect(b.captured_stdout).toBe(''); - expect(b.captured_stderr).toBe(''); - }); - - it('redirects to multiple listeners', () => { - multi.addListener(a); - multi.stdout_writeline('out 1'); - multi.stderr_writeline('err 1'); - - multi.addListener(b); - multi.stdout_writeline('out 2'); - multi.stderr_writeline('err 2'); - - expect(a.captured_stdout).toBe('out 1\nout 2\n'); - expect(a.captured_stderr).toBe('err 1\nerr 2\n'); - - expect(b.captured_stdout).toBe('out 2\n'); - expect(b.captured_stderr).toBe('err 2\n'); - }); -}); - -describe('TargetedStdio', () => { - let capture: CaptureStdio; - let targeted: TargetedStdio; - let error_targeted: TargetedStdio; - let multi: StdioMultiplexer; - - beforeEach(() => { - //DOM element to capture stdout and stderr - let target_div = document.getElementById('output-id'); - - if (target_div === null) { - target_div = document.createElement('div'); - target_div.id = 'output-id'; - document.body.appendChild(target_div); - } else { - target_div.innerHTML = ''; - } - - //DOM element to capture stderr - let error_div = document.getElementById('error-id'); - - if (error_div === null) { - error_div = document.createElement('div'); - error_div.id = 'error-id'; - document.body.appendChild(error_div); - } else { - error_div.innerHTML = ''; - } - - const tag = document.createElement('div'); - tag.setAttribute('output', 'output-id'); - tag.setAttribute('stderr', 'error-id'); - - capture = new CaptureStdio(); - targeted = new TargetedStdio(tag, 'output', true, true); - error_targeted = new TargetedStdio(tag, 'stderr', false, true); - - multi = new StdioMultiplexer(); - multi.addListener(capture); - multi.addListener(targeted); - multi.addListener(error_targeted); - }); - - it('targeted id is set by constructor', () => { - expect(targeted.source_attribute).toBe('output'); - }); - - it('targeted stdio/stderr also goes to multiplexer', () => { - multi.stdout_writeline('out 1'); - multi.stderr_writeline('out 2'); - expect(capture.captured_stdout).toBe('out 1\n'); - expect(capture.captured_stderr).toBe('out 2\n'); - expect(document.getElementById('output-id')?.innerHTML).toBe('out 1
out 2
'); - expect(document.getElementById('error-id')?.innerHTML).toBe('out 2
'); - }); - - it('Add and remove targeted listener', () => { - multi.stdout_writeline('out 1'); - multi.removeListener(targeted); - multi.stdout_writeline('out 2'); - multi.addListener(targeted); - multi.stdout_writeline('out 3'); - - //all three should be captured by multiplexer - expect(capture.captured_stdout).toBe('out 1\nout 2\nout 3\n'); - //out 2 should not be present in the DOM element - expect(document.getElementById('output-id')?.innerHTML).toBe('out 1
out 3
'); - }); -}); diff --git a/pyscriptjs/tests/unit/utils.test.ts b/pyscriptjs/tests/unit/utils.test.ts deleted file mode 100644 index 848cd8f8d57..00000000000 --- a/pyscriptjs/tests/unit/utils.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { beforeEach, expect, describe, it } from '@jest/globals'; -import { ensureUniqueId, joinPaths, createSingularWarning } from '../../src/utils'; - -describe('Utils', () => { - let element: HTMLElement; - - beforeEach(() => { - element = document.createElement('div'); - }); - - it('ensureUniqueId sets unique id on element', async () => { - expect(element.id).toBe(''); - - ensureUniqueId(element); - - expect(element.id).toBe('py-internal-0'); - }); - - it('ensureUniqueId sets unique id with increasing counter', async () => { - const secondElement = document.createElement('div'); - - expect(element.id).toBe(''); - expect(secondElement.id).toBe(''); - - ensureUniqueId(element); - ensureUniqueId(secondElement); - - // The counter will have been incremented on - // the previous test, make sure it keeps increasing - expect(element.id).toBe('py-internal-1'); - expect(secondElement.id).toBe('py-internal-2'); - }); -}); - -describe('JoinPaths', () => { - it('should remove trailing slashes from the beginning and the end', () => { - const paths: string[] = ['///abc/d/e///']; - const joinedPath = joinPaths(paths); - expect(joinedPath).toStrictEqual('/abc/d/e'); - }); - - it('should not remove slashes from the middle to preserve protocols such as http', () => { - const paths: string[] = ['http://google.com', '///data.txt']; - const joinedPath = joinPaths(paths); - expect(joinedPath).toStrictEqual('http://google.com/data.txt'); - }); - - it('should not join paths when they are empty strings', () => { - const paths: string[] = ['', '///hhh/ll/pp///', '', 'kkk']; - const joinedPath = joinPaths(paths); - expect(joinedPath).toStrictEqual('hhh/ll/pp/kkk'); - }); - - describe('createSingularBanner', () => { - it('should create one and new banner containing the sentinel text, and not duplicate it', () => { - //One warning banner with the desired text should be created - createSingularWarning('A unique error message', 'unique'); - expect(document.getElementsByClassName('alert-banner')?.length).toEqual(1); - expect(document.getElementsByClassName('alert-banner')[0].textContent).toEqual( - expect.stringContaining('A unique error message'), - ); - - //Should still only be one banner, since the second uses the existing sentinel value "unique" - createSingularWarning('This banner should not appear', 'unique'); - expect(document.getElementsByClassName('alert-banner')?.length).toEqual(1); - expect(document.getElementsByClassName('alert-banner')[0].textContent).toEqual( - expect.stringContaining('A unique error message'), - ); - - //If the sentinel value is not provided, the entire msg is used as the sentinel - createSingularWarning('A unique error message', null); - expect(document.getElementsByClassName('alert-banner')?.length).toEqual(1); - expect(document.getElementsByClassName('alert-banner')[0].textContent).toEqual( - expect.stringContaining('A unique error message'), - ); - }); - }); -}); diff --git a/pyscriptjs/tsconfig.json b/pyscriptjs/tsconfig.json deleted file mode 100644 index 59372ea7e4c..00000000000 --- a/pyscriptjs/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "_version": "3.0.0", - - "include": ["src/**/*"], - "exclude": ["node_modules/*", "__sapper__/*", "public/*"], - "compilerOptions": { - "moduleResolution": "node", - "target": "ES2020", - "module": "ES2020", - "types": ["jest", "node"], - "strict": false, - "esModuleInterop": true, - "skipLibCheck": true, - "isolatedModules": true, - "forceConsistentCasingInFileNames": true, - "lib": ["es2017", "dom", "DOM.Iterable"] - } -} 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