Full Code of dessant/buster for AI

main 8278e87666fa cached
69 files
216.8 KB
60.2k tokens
127 symbols
1 requests
Download .txt
Showing preview only (234K chars total). Download the full file or copy to clipboard to get everything.
Repository: dessant/buster
Branch: main
Commit: 8278e87666fa
Files: 69
Total size: 216.8 KB

Directory structure:
gitextract_irjtamld/

├── .browserslistrc
├── .github/
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── config.yml
│   │   └── feature_request.md
│   ├── label-actions.yml
│   ├── pull_request_template.md
│   └── workflows/
│       ├── ci.yml
│       ├── label-actions.yml
│       └── lockdown.yml
├── .gitignore
├── .nvmrc
├── .prettierignore
├── .prettierrc.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── babel.config.js
├── gulpfile.js
├── package.json
├── postcss.config.js
├── secrets.json.example
├── src/
│   ├── assets/
│   │   ├── fonts/
│   │   │   └── roboto.css
│   │   ├── locales/
│   │   │   └── en/
│   │   │       ├── messages-firefox.json
│   │   │       └── messages.json
│   │   └── manifest/
│   │       ├── chrome.json
│   │       ├── edge.json
│   │       ├── firefox.json
│   │       └── opera.json
│   ├── background/
│   │   ├── index.html
│   │   └── main.js
│   ├── base/
│   │   ├── main.js
│   │   ├── solver-button.css
│   │   └── style.css
│   ├── contribute/
│   │   ├── App.vue
│   │   ├── index.html
│   │   └── main.js
│   ├── offscreen/
│   │   ├── index.html
│   │   └── main.js
│   ├── options/
│   │   ├── App.vue
│   │   ├── index.html
│   │   └── main.js
│   ├── scripts/
│   │   ├── init-setup.js
│   │   └── reset.js
│   ├── setup/
│   │   ├── App.vue
│   │   ├── index.html
│   │   └── main.js
│   ├── storage/
│   │   ├── config.json
│   │   ├── init.js
│   │   ├── revisions/
│   │   │   ├── local/
│   │   │   │   ├── 20221211221603_add_theme_support.js
│   │   │   │   ├── 20221214080901_update_services.js
│   │   │   │   ├── 20240514170322_add_appversion.js
│   │   │   │   ├── DlgF14Chrh.js
│   │   │   │   ├── Lj3MYlSr4L.js
│   │   │   │   ├── ONiJBs00o.js
│   │   │   │   ├── UidMDYaYA.js
│   │   │   │   ├── UoT3kGyBH.js
│   │   │   │   ├── X3djS8vZC.js
│   │   │   │   ├── ZtLMLoh1ag.js
│   │   │   │   ├── nOedd0Txqd.js
│   │   │   │   └── t335iRDhZ8.js
│   │   │   └── session/
│   │   │       └── 20240514122825_initial_version.js
│   │   └── storage.js
│   └── utils/
│       ├── app.js
│       ├── common.js
│       ├── config.js
│       ├── data.js
│       └── vuetify.js
└── webpack.config.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .browserslistrc
================================================
[chrome]
Chrome >= 123
Edge >= 123
Opera >= 109

[edge]
Edge >= 123

[firefox]
Firefox >= 115

[opera]
Opera >= 109


================================================
FILE: .github/FUNDING.yml
================================================
github: dessant
patreon: dessant
custom:
  - https://armin.dev/go/paypal
  - https://armin.dev/go/bitcoin


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report if something isn't working as expected

---

<!--
You may experience a temporary block when trying to solve a reCAPTCHA audio challenge.
This error is outside the control of the extension, and should not be reported as a bug.
Visit the wiki to learn more about the issue.

https://github.com/dessant/buster/wiki/Inaccessible-reCAPTCHA-audio-challenge

Full automation and scripting are not within the scope of this project due to the potential for misuse.
The solver must always be manually started from the extension button.
 -->

**System**
<!-- Fill out the template below with the requested information. -->

* OS name: [e.g. Windows, Ubuntu]
* OS version: [e.g. 10]
* Browser name: [e.g. Chrome, Firefox]
* Browser version: [e.g. 60]

**Extension**
<!-- Fill out the template below with the requested information. -->

* Extension version: [e.g. 1.0.0]
<!-- Check if the feature is enabled on the options page. -->
* User input simulation: [e.g. yes, no]
<!-- Fill out only if you have downloaded the client app. -->
* Client app version: [e.g. 1.0.0]
* Client app installed successfully: [e.g. yes, no]

**Bug description**
<!--
Describe what the bug is and how to reproduce it. List each step
that is required to reproduce the issue. Mention any browser features
or installed extensions that may trigger the bug. If applicable,
attach screenshots.
-->

**Logs**

<!--
If there was an error, open the browser console (Ctrl+Shift+J)
and share its recent output.
-->
Browser:
```
// REPLACE WITH LOGS
```

<!--
If you are using the client app, find the `buster-client-log.txt` file
in the temp folder (e.g. `C:\Users\<user>\AppData\Local\Temp`)
and share its contents.
-->
Client app:
```
// REPLACE WITH LOGS
```


================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false


================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project

---

<!--
Full automation and scripting are not within the scope of this project due to the potential for misuse.
The solver must always be manually started from the extension button.
 -->

**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. -->

**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->

**Describe alternatives you've considered**
<!-- Description of any alternative solutions or features you've considered. -->

**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->


================================================
FILE: .github/label-actions.yml
================================================
# Configuration for Label Actions - https://github.com/dessant/label-actions

incomplete:
  issues:
    comment: >
      @{issue-author}, the issue does not contain enough information
      to reproduce the bug. Please open a new bug report and fill out
      the issue template with the requested data.
    close: true
wontfix-automation:
  issues:
    comment: >
      @{issue-author}, full automation and scripting are not within the scope
      of this project due to the potential for misuse.
      The solver must always be manually started from the extension button.
    close: true
recaptcha-error:
  issues:
    comment: |
      You may experience a temporary block when trying to solve a reCAPTCHA audio challenge. Visit the wiki to learn more about the issue and the steps you can take to minimize the risk of a temporary block.

      https://github.com/dessant/buster/wiki/Inaccessible-reCAPTCHA-audio-challenge
    close: true


================================================
FILE: .github/pull_request_template.md
================================================
This project does not accept pull requests. Please use issues to report bugs or suggest new features.


================================================
FILE: .github/workflows/ci.yml
================================================
name: CI

on: push

jobs:
  build:
    name: Build
    runs-on: ubuntu-22.04
    permissions:
      contents: read
    steps:
      - name: Clone repository
        uses: actions/checkout@v4
        with:
          persist-credentials: 'false'
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version-file: '.nvmrc'
          cache: 'npm'
      - name: Install dependencies
        run: npm install --legacy-peer-deps
      - name: Build artifacts
        run: |
          npm run build:prod:zip:chrome
          npm run build:prod:zip:edge
          npm run build:prod:zip:firefox
          npm run build:prod:zip:opera
        env:
          BUSTER_SECRETS: ${{ secrets.BUSTER_SECRETS }}
      - name: Hash artifacts
        run: sha256sum artifacts/*/*
        if: startsWith(github.ref, 'refs/tags/v')
      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        if: startsWith(github.ref, 'refs/tags/v')
        with:
          name: artifacts
          path: artifacts/
          retention-days: 1
  release:
    name: Release on GitHub
    runs-on: ubuntu-22.04
    needs: [build]
    if: startsWith(github.ref, 'refs/tags/v')
    permissions:
      contents: write
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: artifacts
          path: artifacts/
      - name: Hash artifacts
        run: sha256sum artifacts/*/*
      - name: Create GitHub release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.ref_name }}
          name: ${{ github.ref_name }}
          body: |
            Download and install the extension from the [extension store](https://github.com/dessant/buster#readme) of your browser.

            Learn more about this release from the [changelog](https://github.com/dessant/buster/blob/main/CHANGELOG.md#changelog).
          files: artifacts/*/*
          fail_on_unmatched_files: true
          draft: true


================================================
FILE: .github/workflows/label-actions.yml
================================================
name: 'Label Actions'

on:
  issues:
    types: [labeled, unlabeled]
  pull_request:
    types: [labeled, unlabeled]

permissions:
  contents: read
  issues: write
  pull-requests: write

jobs:
  action:
    runs-on: ubuntu-latest
    steps:
      - uses: dessant/label-actions@v4


================================================
FILE: .github/workflows/lockdown.yml
================================================
name: 'Repo Lockdown'

on:
  pull_request_target:
    types: opened

permissions:
  pull-requests: write

jobs:
  action:
    runs-on: ubuntu-latest
    steps:
      - uses: dessant/repo-lockdown@v4
        with:
          exclude-pr-created-before: '2021-11-02T00:00:00Z'
          pr-comment: 'This project does not accept pull requests. Please use issues to report bugs or suggest new features.'
          process-only: 'prs'


================================================
FILE: .gitignore
================================================
/.assets/
/app/
/artifacts/
/dist/

/secrets.json

/report.json
/report.html

/web-ext-config.js

node_modules/
/npm-debug.log

/.vscode

xcuserdata/

.DS_Store


================================================
FILE: .nvmrc
================================================
20.14.0


================================================
FILE: .prettierignore
================================================
package.json
*.md


================================================
FILE: .prettierrc.yml
================================================
singleQuote: true
bracketSpacing: false
arrowParens: 'avoid'
trailingComma: 'none'


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.

## [3.1.0](https://github.com/dessant/buster/compare/v3.0.0...v3.1.0) (2024-06-04)


### Features

* reload options page when client app is installed ([290dfba](https://github.com/dessant/buster/commit/290dfbac14c973e8efe007012419d7c583510d14))
* upgrade to Manifest V3 in Edge and Opera ([f3e09bf](https://github.com/dessant/buster/commit/f3e09bfb82404bc90afeea4c79d09f976156da76))


### Bug Fixes

* omit cookies from API requests ([cb4811e](https://github.com/dessant/buster/commit/cb4811e84121b306a640ccdcb96a2dff1448d24b))
* workaround for IBM Watson error ([cd1312e](https://github.com/dessant/buster/commit/cd1312ecb31fe89e493550fcdbd3fe78df104bef)), closes [#405](https://github.com/dessant/buster/issues/405)

## [3.0.0](https://github.com/dessant/buster/compare/v2.0.1...v3.0.0) (2024-05-28)


### ⚠ BREAKING CHANGES

* browser versions older than Chrome 123, Edge 123,
Firefox 115 and Opera 109 are no longer supported

### Features

* upgrade to Manifest V3 in Chrome ([42149b3](https://github.com/dessant/buster/commit/42149b35b70b93483165b210a2fdc7c6f643bde0))

### [2.0.1](https://github.com/dessant/buster/compare/v2.0.0...v2.0.1) (2022-12-16)


### Bug Fixes

* set color scheme ([57c941a](https://github.com/dessant/buster/commit/57c941ae685b367504da03f94bf5d74ddd645ddf))

## [2.0.0](https://github.com/dessant/buster/compare/v1.3.2...v2.0.0) (2022-12-15)


### ⚠ BREAKING CHANGES

* the options for speech recognition services have changed,
the configuration of certain services may be needed
* browser versions older than Chrome 92, Edge 92,
Firefox 91, and Opera 78 are no longer supported

### Features

* migrate to Vuetify ([c921f65](https://github.com/dessant/buster/commit/c921f6509e515158491b4878ab5a4bb075b1a048))


### Bug Fixes

* update speech recognition services ([cd84690](https://github.com/dessant/buster/commit/cd84690f362773d4123e838299e07825a67812b4))

### [1.3.2](https://github.com/dessant/buster/compare/v1.3.1...v1.3.2) (2022-09-01)


### Bug Fixes

* set correct tabindex for extension button ([d68ce72](https://github.com/dessant/buster/commit/d68ce72e8d3664939cac5ce677c2dfd988ea732a))
* update client app navigation ([3fae62e](https://github.com/dessant/buster/commit/3fae62ee4adde746ab46299732df7535c81592bd)), closes [#360](https://github.com/dessant/buster/issues/360)

### [1.3.1](https://github.com/dessant/buster/compare/v1.3.0...v1.3.1) (2021-11-02)


### Bug Fixes

* update challenge reset ([3d0fb37](https://github.com/dessant/buster/commit/3d0fb3768b05138fc0b6766b5ed107bffac4a380))

## [1.3.0](https://github.com/dessant/buster/compare/v1.2.2...v1.3.0) (2021-09-25)


### Features

* link to guide for configuring Google Cloud Speech to Text ([8930b1c](https://github.com/dessant/buster/commit/8930b1cf51447bc656d528f83a209075fa07e121))
* link to guide for configuring IBM Watson Speech to Text ([ead4292](https://github.com/dessant/buster/commit/ead4292c7c208f9730e6a54e85dec6701fa9b7ed))
* link to guide for configuring Microsoft Azure Speech to Text ([36afd65](https://github.com/dessant/buster/commit/36afd655feed3f62760c257adf9a4a72f711bec5))


### Bug Fixes

* add new API location for IBM Watson ([da8266b](https://github.com/dessant/buster/commit/da8266bf739905de9d2522625cca625852e8952c))
* add new API locations for Microsoft Azure ([bce1cbb](https://github.com/dessant/buster/commit/bce1cbb36c25763b1c01e263a67f5079c510b654))
* update speech service names ([10cf778](https://github.com/dessant/buster/commit/10cf778ce69bff0a184d8a28d0d06aff752d0354))

### [1.2.2](https://github.com/dessant/buster/compare/v1.2.1...v1.2.2) (2021-07-23)

### [1.2.1](https://github.com/dessant/buster/compare/v1.2.0...v1.2.1) (2021-05-14)


### Bug Fixes

* do not bundle source maps with Opera package ([187622b](https://github.com/dessant/buster/commit/187622b83a0edaeb1318feb68249bd342fd0951d))

## [1.2.0](https://github.com/dessant/buster/compare/v1.1.1...v1.2.0) (2021-04-29)


### Features

* automatically clear non-critical error notifications ([ab03085](https://github.com/dessant/buster/commit/ab03085b0e156aa0bfccf6448222a003f2690386)), closes [#253](https://github.com/dessant/buster/issues/253)


### Bug Fixes

* handle new reCAPTCHA host ([9d092c2](https://github.com/dessant/buster/commit/9d092c2c39f2d018455a4333fad417f6d500c360)), closes [#290](https://github.com/dessant/buster/issues/290)
* serve AMD64 client app installer for ARM macOS devices ([17c0a38](https://github.com/dessant/buster/commit/17c0a383afbb0e54ef9434abc6bd3e9f2d7efd68)), closes [#261](https://github.com/dessant/buster/issues/261)

### [1.1.1](https://github.com/dessant/buster/compare/v1.1.0...v1.1.1) (2020-10-12)


### Bug Fixes

* Opera add-ons does not accept the .enc file extension ([317eb95](https://github.com/dessant/buster/commit/317eb95f6c248013e1f296f49f71ca940b0b63e8))

## [1.1.0](https://github.com/dessant/buster/compare/v1.0.1...v1.1.0) (2020-10-12)


### Features

* add support for reCAPTCHA Enterprise ([092f3b9](https://github.com/dessant/buster/commit/092f3b9492abf48b92539b4bb5670273bfced88e)), closes [#236](https://github.com/dessant/buster/issues/236)
* create new section for client app options ([15ae99e](https://github.com/dessant/buster/commit/15ae99ea1395855c8d2db3707661328f1452a0eb))
* link to guide for configuring Wit.ai ([31f915f](https://github.com/dessant/buster/commit/31f915f517be8e8c70541b059fed2ee5c32af279))
* navigate with client app using keyboard ([d34f5fa](https://github.com/dessant/buster/commit/d34f5fa8b715e95ae921e0490223817f9accb111)), closes [#168](https://github.com/dessant/buster/issues/168)
* support Chrome Incognito ([39cf3c0](https://github.com/dessant/buster/commit/39cf3c02efb40bec69e2de4124563120c0b1074d))


### Bug Fixes

* increase favicon size ([2df4816](https://github.com/dessant/buster/commit/2df48169e1fca5241595eaa513d27fe68561b5ed))
* inject assets in challenge frames loaded from alternative URLs ([ce2d942](https://github.com/dessant/buster/commit/ce2d9424f55210c1fe000ef48490317816f27532))
* move mouse to the correct position when only text is zoomed in Firefox ([692340c](https://github.com/dessant/buster/commit/692340c5aa16425e0d6f762a2f33119257c33ea9)), closes [#133](https://github.com/dessant/buster/issues/133)
* show actionable error message when API quota is exceeded ([d01968d](https://github.com/dessant/buster/commit/d01968d5b46694ea84ba643a95ba29ce46e52c31))

### [1.0.1](https://github.com/dessant/buster/compare/v1.0.0...v1.0.1) (2020-06-14)


### Bug Fixes

* set challenge locale when widget is loaded from recaptcha.net ([edb7402](https://github.com/dessant/buster/commit/edb74021ef14cefc5d407cabedb0fe8e813b8711))

## [1.0.0](https://github.com/dessant/buster/compare/v0.7.3...v1.0.0) (2020-06-14)


### ⚠ BREAKING CHANGES

* browser versions before Chrome 76, Firefox 68 and Opera 63
are no longer supported

### Bug Fixes

* add extension button when challenge assets are loaded from recaptcha.net ([afbde57](https://github.com/dessant/buster/commit/afbde578cfb21f388f8415adbe99997e8a037c3b)), closes [#194](https://github.com/dessant/buster/issues/194)


*  fix: remove support for outdated browsers ([ef7514e](https://github.com/dessant/buster/commit/ef7514e9ee0ab059a271b3d7be6142f0ccd58ce6))

### [0.7.3](https://github.com/dessant/buster/compare/v0.7.2...v0.7.3) (2020-05-28)


### Bug Fixes

* add button to existing challenge widgets after installation in Chrome ([1b9af9e](https://github.com/dessant/buster/commit/1b9af9e93cfe899a962c3c137ff66be7e020552d))
* remove unused permissions ([dcacc48](https://github.com/dessant/buster/commit/dcacc489e6f2f858949fb4988c74d9d78704f2bd))
* trim Wit Speech API result only when it exists ([8a54f1f](https://github.com/dessant/buster/commit/8a54f1fdcec03b2860a60e4f4bb521e80f441b10))

### [0.7.2](https://github.com/dessant/buster/compare/v0.7.1...v0.7.2) (2020-05-14)


### Bug Fixes

* update Wit Speech API ([d244f62](https://github.com/dessant/buster/commit/d244f625501f377bc7f26112b674f464d45ee399))

### [0.7.1](https://github.com/dessant/buster/compare/v0.7.0...v0.7.1) (2020-02-11)


### Bug Fixes

* include source maps for production builds ([6fb0b04](https://github.com/dessant/buster/commit/6fb0b042be5d853084474ef3f6fd5f6695f451ed))

## [0.7.0](https://github.com/dessant/buster/compare/v0.6.1...v0.7.0) (2020-02-09)


### Features

* enable client app installation on Windows 32-bit ([9995f46](https://github.com/dessant/buster/commit/9995f46ed4cb2ac006b335405209a22fe54a1f23))


### Bug Fixes

* send browser name to client app installer ([aab8384](https://github.com/dessant/buster/commit/aab8384d35c6d6354d3b9ae6fa5a227fc693105f))

### [0.6.1](https://github.com/dessant/buster/compare/v0.6.0...v0.6.1) (2020-02-02)


### Bug Fixes

* discard noise from audio challenge ([a57cdb8](https://github.com/dessant/buster/commit/a57cdb839db59909079a44c42af0488648ba5fa0))
* link client app installation guide from options page ([57611ac](https://github.com/dessant/buster/commit/57611ac664fa436ffbe47525825f5b75591eab5a))
* remove origin header from background requests ([999ccf9](https://github.com/dessant/buster/commit/999ccf94c7acff1e31fbfaee769e3e84968774c4))
* rotate Wit.ai API keys for English challenges ([e985b7d](https://github.com/dessant/buster/commit/e985b7d6662c1f168bf504d799cd773ba5e5d8b3)), closes [#130](https://github.com/dessant/buster/issues/130)
* update available languages and API endpoints ([182a0aa](https://github.com/dessant/buster/commit/182a0aa5cf3d6dab7cbe1cbc9f4220692259ed51))
* update speech service name ([bb2bff9](https://github.com/dessant/buster/commit/bb2bff913cd11056a0315b0ce0bd6acb5733f5c0))
* update UI layout ([72aeceb](https://github.com/dessant/buster/commit/72aeceb8e4db927624267062acc343ec6b0cf4e8))

## [0.6.0](https://github.com/dessant/buster/compare/v0.5.3...v0.6.0) (2019-05-28)


### Features

* build with travis ([43f9ce5](https://github.com/dessant/buster/commit/43f9ce5))
* transcribe audio in background script ([2c89926](https://github.com/dessant/buster/commit/2c89926)), closes [#81](https://github.com/dessant/buster/issues/81)



<a name="0.5.3"></a>
## [0.5.3](https://github.com/dessant/buster/compare/v0.5.2...v0.5.3) (2019-05-14)


### Bug Fixes

* correct the target element width / height for higher density screens ([22edae2](https://github.com/dessant/buster/commit/22edae2)), closes [#71](https://github.com/dessant/buster/issues/71)



<a name="0.5.2"></a>
## [0.5.2](https://github.com/dessant/buster/compare/v0.5.1...v0.5.2) (2019-04-07)


### Bug Fixes

* get audio URL from audio element ([4a823f9](https://github.com/dessant/buster/commit/4a823f9))
* remove demo speech service ([f7b9554](https://github.com/dessant/buster/commit/f7b9554))



<a name="0.5.1"></a>
## [0.5.1](https://github.com/dessant/buster/compare/v0.5.0...v0.5.1) (2019-03-08)


### Bug Fixes

* divide click coordinates by display scale on Windows ([0db060d](https://github.com/dessant/buster/commit/0db060d)), closes [#40](https://github.com/dessant/buster/issues/40)



<a name="0.5.0"></a>
# [0.5.0](https://github.com/dessant/buster/compare/v0.4.1...v0.5.0) (2019-03-04)


### Bug Fixes

* allow installation on windows if manifest location is not set ([aebd114](https://github.com/dessant/buster/commit/aebd114))
* clean up after client app update ([4b4d645](https://github.com/dessant/buster/commit/4b4d645))
* close client app before checking ping response ([715aab7](https://github.com/dessant/buster/commit/715aab7))
* wait for client app to close before launching new version ([d9aef00](https://github.com/dessant/buster/commit/d9aef00))


### Features

* add option for automatically updating client app ([e17107f](https://github.com/dessant/buster/commit/e17107f))
* require new client app version ([0879515](https://github.com/dessant/buster/commit/0879515))



<a name="0.4.1"></a>
## [0.4.1](https://github.com/dessant/buster/compare/v0.4.0...v0.4.1) (2019-02-22)


### Bug Fixes

* account for OS scaling during mouse movement ([e055850](https://github.com/dessant/buster/commit/e055850)), closes [#27](https://github.com/dessant/buster/issues/27)
* break early during challenge reset ([baa6581](https://github.com/dessant/buster/commit/baa6581))



<a name="0.4.0"></a>
# [0.4.0](https://github.com/dessant/buster/compare/v0.3.0...v0.4.0) (2019-02-18)


### Features

* show reset button when the challenge is blocked ([3398166](https://github.com/dessant/buster/commit/3398166))
* simulate user input ([779f466](https://github.com/dessant/buster/commit/779f466))



<a name="0.3.0"></a>
# [0.3.0](https://github.com/dessant/buster/compare/v0.2.0...v0.3.0) (2018-12-18)


### Bug Fixes

* use English as alternative language for Google Cloud Speech API ([f13d1ea](https://github.com/dessant/buster/commit/f13d1ea))


### Features

* add Wit Speech API and tryEnglishSpeechModel option ([c32a654](https://github.com/dessant/buster/commit/c32a654))
* load challenge in English by default ([3f581bd](https://github.com/dessant/buster/commit/3f581bd))



<a name="0.2.0"></a>
# [0.2.0](https://github.com/dessant/buster/compare/v0.1.1...v0.2.0) (2018-12-08)


### Bug Fixes

* set IBM API location instead of URL ([0c9a824](https://github.com/dessant/buster/commit/0c9a824))


### Features

* add IBM Speech to Text ([58f9106](https://github.com/dessant/buster/commit/58f9106))
* add Microsoft Azure Speech to Text API ([f8c1dde](https://github.com/dessant/buster/commit/f8c1dde))
* indicate that work is in progress ([fdb4cca](https://github.com/dessant/buster/commit/fdb4cca))



<a name="0.1.1"></a>
## [0.1.1](https://github.com/dessant/buster/compare/v0.1.0...v0.1.1) (2018-12-06)


### Bug Fixes

* solve compatibility issues with older browser versions ([8be3007](https://github.com/dessant/buster/commit/8be3007)), closes [#3](https://github.com/dessant/buster/issues/3)



<a name="0.1.0"></a>
# 0.1.0 (2018-12-04)


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
<p align="center"><img width="128" height="128" src="https://i.imgur.com/uVpmR8l.png"></p>
<h1 align="center">Buster: Captcha Solver for Humans</h1>

<p align="center">
  </br></br>
  <a href="https://chrome.google.com/webstore/detail/buster-captcha-solver-for/mpbjkejclgfgadiemmefgebjfooflfhl">
    <picture>
      <source srcset="https://i.imgur.com/XBIE9pk.png" media="(prefers-color-scheme: dark)">
      <img height="58" src="https://i.imgur.com/oGxig2F.png" alt="Chrome Web Store"></picture></a>
  <a href="https://addons.mozilla.org/firefox/addon/buster-captcha-solver/">
    <picture>
      <source srcset="https://i.imgur.com/ZluoP7T.png" media="(prefers-color-scheme: dark)">
      <img height="58" src="https://i.imgur.com/4PobQqE.png" alt="Firefox add-ons"></picture></a>
  <a href="https://microsoftedge.microsoft.com/addons/detail/buster-captcha-solver-fo/admkpobhocmdideidcndkfaeffadipkc">
    <picture>
      <source srcset="https://i.imgur.com/Jog9cQP.png" media="(prefers-color-scheme: dark)">
      <img height="58" src="https://i.imgur.com/aiprUt8.png" alt="Microsoft Store"></picture></a>
  <a href="https://addons.opera.com/extensions/details/buster-captcha-solver-for-humans/">
    <picture>
      <source srcset="https://i.imgur.com/ziehy0f.png" media="(prefers-color-scheme: dark)">
      <img height="58" src="https://i.imgur.com/ytVATu0.png" alt="Opera add-ons"></picture></a>
  </br></br>
</p>

## Supporting the Project

The continued development of Buster is made possible
thanks to the support of awesome backers. If you'd like to join them,
please consider contributing with
[Patreon](https://armin.dev/go/patreon?pr=buster&src=repo),
[PayPal](https://armin.dev/go/paypal?pr=buster&src=repo) or
[Bitcoin](https://armin.dev/go/bitcoin?pr=buster&src=repo).

## Description

Buster is a browser extension which helps you to solve difficult CAPTCHAs
by completing reCAPTCHA audio challenges using speech recognition.
Challenges are solved by clicking on the extension button at the bottom
of the reCAPTCHA widget.

> Obviously, this blue part here is the land.
>
> — <cite>Byron "Buster" Bluth, reading a map</cite>

## Motivation

reCAPTCHA challenges remain a considerable burden on the web,
delaying and often blocking our access to services and information
depending on our physical and cognitive abilities, our social
and cultural background, and the devices or networks we connect from.

The difficulty of CAPTCHA challenges can be so out of balance,
that sometimes they seem friendlier to bots than they are to humans.

The goal of this project is to improve our user experience on the web,
by giving us easy access to solutions utilized by automated systems.

## Client App

The client app enables you to simulate user interactions and improves
the success rate of the extension. Follow the instructions
from the extension's options to download and install the client app
on Windows, Linux and macOS, or get the app
from [this](https://github.com/dessant/buster-client#readme) repository.

## Screenshots

<p>
  <img width="380" src="https://i.imgur.com/hTqeN4z.png">
  <img width="380" src="https://i.imgur.com/o0qqDd5.png">
</p>

## License

Copyright (c) 2018-2024 Armin Sebastian

This software is released under the terms of the GNU General Public License v3.0.
See the [LICENSE](LICENSE) file for further information.


================================================
FILE: babel.config.js
================================================
const path = require('node:path');

const corejsVersion = require(
  path.join(path.dirname(require.resolve('core-js')), 'package.json')
).version;

module.exports = function (api) {
  api.cache(true);

  const presets = [
    [
      '@babel/env',
      {
        modules: false,
        bugfixes: true,
        useBuiltIns: 'usage',
        corejs: {version: corejsVersion}
      }
    ]
  ];

  const plugins = [];

  const ignore = [
    new RegExp(`node_modules\\${path.sep}(?!(vueton|wesa)\\${path.sep}).*`)
  ];

  const parserOpts = {plugins: ['importAttributes']};

  return {presets, plugins, ignore, parserOpts};
};


================================================
FILE: gulpfile.js
================================================
const path = require('node:path');
const {exec} = require('node:child_process');
const {
  lstatSync,
  readdirSync,
  readFileSync,
  writeFileSync,
  rmSync
} = require('node:fs');

const {series, parallel, src, dest} = require('gulp');
const postcss = require('gulp-postcss');
const gulpif = require('gulp-if');
const jsonMerge = require('gulp-merge-json');
const jsonmin = require('gulp-jsonmin');
const htmlmin = require('gulp-htmlmin');
const imagemin = require('gulp-imagemin');
const {ensureDirSync, readJsonSync} = require('fs-extra');
const sharp = require('sharp');
const CryptoJS = require('crypto-js');

const appVersion = require('./package.json').version;

const targetEnv = process.env.TARGET_ENV || 'chrome';
const isProduction = process.env.NODE_ENV === 'production';
const enableContributions =
  (process.env.ENABLE_CONTRIBUTIONS || 'true') === 'true';

const mv3 = ['chrome', 'edge', 'opera'].includes(targetEnv);

const distDir = path.join(__dirname, 'dist', targetEnv);

function initEnv() {
  process.env.BROWSERSLIST_ENV = targetEnv;
}

function init(done) {
  initEnv();

  rmSync(distDir, {recursive: true, force: true});
  ensureDirSync(distDir);
  done();
}

function js(done) {
  exec('webpack-cli build --color', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    done(err);
  });
}

function html() {
  const htmlSrc = ['src/**/*.html'];

  if (mv3) {
    htmlSrc.push('!src/background/*.html');
  }

  if (!enableContributions) {
    htmlSrc.push('!src/contribute/*.html');
  }

  if (!(mv3 && !['firefox', 'safari'].includes(targetEnv))) {
    htmlSrc.push('!src/offscreen/*.html');
  }

  return src(htmlSrc, {base: '.'})
    .pipe(gulpif(isProduction, htmlmin({collapseWhitespace: true})))
    .pipe(dest(distDir));
}

function css() {
  return src('src/base/*.css', {base: '.'}).pipe(postcss()).pipe(dest(distDir));
}

async function images(done) {
  ensureDirSync(path.join(distDir, 'src/assets/icons/app'));
  const appIconSvg = readFileSync('src/assets/icons/app/icon.svg');
  const appIconSizes = [16, 19, 24, 32, 38, 48, 64, 96, 128];
  if (targetEnv === 'safari') {
    appIconSizes.push(256, 512, 1024);
  }
  for (const size of appIconSizes) {
    await sharp(appIconSvg, {density: (72 * size) / 24})
      .resize(size)
      .toFile(path.join(distDir, `src/assets/icons/app/icon-${size}.png`));
  }

  // Chrome Web Store does not correctly display optimized icons
  if (isProduction && targetEnv !== 'chrome') {
    await new Promise(resolve => {
      src(path.join(distDir, 'src/assets/icons/app/*.png'), {
        base: '.',
        encoding: false
      })
        .pipe(imagemin())
        .pipe(dest('.'))
        .on('error', done)
        .on('finish', resolve);
    });
  }

  await new Promise(resolve => {
    src('src/assets/icons/@(app|misc)/*.@(png|svg)', {
      base: '.',
      encoding: false
    })
      .pipe(gulpif(isProduction, imagemin()))
      .pipe(dest(distDir))
      .on('error', done)
      .on('finish', resolve);
  });

  if (enableContributions) {
    await new Promise(resolve => {
      src(
        'node_modules/vueton/components/contribute/assets/*.@(png|webp|svg)',
        {encoding: false}
      )
        .pipe(gulpif(isProduction, imagemin()))
        .pipe(dest(path.join(distDir, 'src/contribute/assets')))
        .on('error', done)
        .on('finish', resolve);
    });
  }
}

async function fonts(done) {
  await new Promise(resolve => {
    src('src/assets/fonts/roboto.css', {base: '.'})
      .pipe(postcss())
      .pipe(dest(distDir))
      .on('error', done)
      .on('finish', resolve);
  });

  await new Promise(resolve => {
    src(
      'node_modules/@fontsource/roboto/files/roboto-latin-@(400|500|700)-normal.woff2',
      {encoding: false}
    )
      .pipe(dest(path.join(distDir, 'src/assets/fonts/files')))
      .on('error', done)
      .on('finish', resolve);
  });
}

async function locale(done) {
  const localesRootDir = path.join(__dirname, 'src/assets/locales');
  const localeDirs = readdirSync(localesRootDir).filter(function (file) {
    return lstatSync(path.join(localesRootDir, file)).isDirectory();
  });
  for (const localeDir of localeDirs) {
    const localePath = path.join(localesRootDir, localeDir);
    await new Promise(resolve => {
      src(
        [
          path.join(localePath, 'messages.json'),
          path.join(localePath, `messages-${targetEnv}.json`)
        ],
        {allowEmpty: true}
      )
        .pipe(
          jsonMerge({
            fileName: 'messages.json',
            edit: (parsedJson, file) => {
              if (isProduction) {
                for (let [key, value] of Object.entries(parsedJson)) {
                  if (value.hasOwnProperty('description')) {
                    delete parsedJson[key].description;
                  }
                }
              }
              return parsedJson;
            }
          })
        )
        .pipe(gulpif(isProduction, jsonmin()))
        .pipe(dest(path.join(distDir, '_locales', localeDir)))
        .on('error', done)
        .on('finish', resolve);
    });
  }
}

function manifest() {
  return src(`src/assets/manifest/${targetEnv}.json`)
    .pipe(
      jsonMerge({
        fileName: 'manifest.json',
        edit: (parsedJson, file) => {
          parsedJson.version = appVersion;
          return parsedJson;
        }
      })
    )
    .pipe(gulpif(isProduction, jsonmin()))
    .pipe(dest(distDir));
}

function license(done) {
  let year = '2018';
  const currentYear = new Date().getFullYear().toString();
  if (year !== currentYear) {
    year = `${year}-${currentYear}`;
  }

  let notice = `Buster: Captcha Solver for Humans
Copyright (c) ${year} Armin Sebastian
`;

  if (['safari', 'samsung'].includes(targetEnv)) {
    writeFileSync(path.join(distDir, 'NOTICE'), notice);
    done();
  } else {
    notice = `${notice}
This software is released under the terms of the GNU General Public License v3.0.
See the LICENSE file for further information.
`;
    writeFileSync(path.join(distDir, 'NOTICE'), notice);
    return src('LICENSE').pipe(dest(distDir));
  }
}

function secrets(done) {
  try {
    let data = process.env.BUSTER_SECRETS;
    if (data) {
      data = JSON.parse(data);
    } else {
      data = readJsonSync('secrets.json');
    }
    data = JSON.stringify(data);

    const key = CryptoJS.SHA256(
      readFileSync(path.join(distDir, 'src/background/script.js')).toString() +
        readFileSync(path.join(distDir, 'src/base/script.js')).toString()
    ).toString();

    const ciphertext = CryptoJS.AES.encrypt(data, key).toString();

    writeFileSync(path.join(distDir, 'secrets.txt'), ciphertext);
  } catch (err) {
    console.log(
      'Secrets are missing, secrets.txt will not be included in the extension package.'
    );
  }

  done();
}

function zip(done) {
  exec(
    `web-ext build -s dist/${targetEnv} -a artifacts/${targetEnv} -n "{name}-{version}-${targetEnv}.zip" --overwrite-dest`,
    function (err, stdout, stderr) {
      console.log(stdout);
      console.log(stderr);
      done(err);
    }
  );
}

function inspect(done) {
  initEnv();

  exec(
    `npm run build:prod:chrome && \
    webpack --profile --json > report.json && \
    webpack-bundle-analyzer --mode static report.json dist/chrome/src && \
    sleep 3 && rm report.{json,html}`,
    function (err, stdout, stderr) {
      console.log(stdout);
      console.log(stderr);
      done(err);
    }
  );
}

exports.build = series(
  init,
  parallel(js, html, css, images, fonts, locale, manifest, license),
  secrets
);
exports.zip = zip;
exports.inspect = inspect;
exports.secrets = secrets;


================================================
FILE: package.json
================================================
{
  "name": "buster",
  "version": "3.1.0",
  "author": "Armin Sebastian",
  "license": "GPL-3.0-only",
  "homepage": "https://github.com/dessant/buster",
  "repository": {
    "url": "https://github.com/dessant/buster.git",
    "type": "git"
  },
  "bugs": {
    "url": "https://github.com/dessant/buster/issues"
  },
  "scripts": {
    "_build": "cross-env NODE_ENV=development gulp build",
    "build:chrome": "cross-env TARGET_ENV=chrome npm run _build",
    "build:edge": "cross-env TARGET_ENV=edge npm run _build",
    "build:firefox": "cross-env TARGET_ENV=firefox npm run _build",
    "build:opera": "cross-env TARGET_ENV=opera npm run _build",
    "_build:prod": "cross-env NODE_ENV=production gulp build",
    "build:prod:chrome": "cross-env TARGET_ENV=chrome npm run _build:prod",
    "build:prod:edge": "cross-env TARGET_ENV=edge npm run _build:prod",
    "build:prod:firefox": "cross-env TARGET_ENV=firefox npm run _build:prod",
    "build:prod:opera": "cross-env TARGET_ENV=opera npm run _build:prod",
    "_build:prod:zip": "npm run _build:prod && gulp zip",
    "build:prod:zip:chrome": "cross-env TARGET_ENV=chrome npm run _build:prod:zip",
    "build:prod:zip:edge": "cross-env TARGET_ENV=edge npm run _build:prod:zip",
    "build:prod:zip:firefox": "cross-env TARGET_ENV=firefox npm run _build:prod:zip",
    "build:prod:zip:opera": "cross-env TARGET_ENV=opera npm run _build:prod:zip",
    "start:chrome": "web-ext run -s dist/chrome -t chromium",
    "start:firefox": "web-ext run -s dist/firefox -t firefox-desktop",
    "inspect": "cross-env NODE_ENV=production gulp inspect",
    "update": "ncu --dep prod,dev,peer --filterVersion '^*' --upgrade",
    "release": "commit-and-tag-version",
    "push": "git push --follow-tags origin main"
  },
  "dependencies": {
    "@fontsource/roboto": "^5.0.13",
    "audiobuffer-to-wav": "^1.0.0",
    "bowser": "^2.11.0",
    "core-js": "^3.37.1",
    "crypto-js": "^4.2.0",
    "p-queue": "^8.0.1",
    "uuid": "^9.0.1",
    "vue": "3.4.23",
    "vuetify": "3.3.0",
    "vueton": "^0.4.2",
    "webextension-polyfill": "^0.12.0",
    "wesa": "^0.6.0"
  },
  "devDependencies": {
    "@babel/core": "^7.24.6",
    "@babel/preset-env": "^7.24.6",
    "babel-loader": "^9.1.3",
    "commit-and-tag-version": "^12.4.1",
    "cross-env": "^7.0.3",
    "css-loader": "^7.1.2",
    "cssnano": "^7.0.1",
    "fs-extra": "^11.2.0",
    "gulp": "^5.0.0",
    "gulp-htmlmin": "^5.0.1",
    "gulp-if": "^3.0.0",
    "gulp-imagemin": "7.1.0",
    "gulp-jsonmin": "^1.2.0",
    "gulp-merge-json": "^2.2.1",
    "gulp-postcss": "^10.0.0",
    "mini-css-extract-plugin": "^2.9.0",
    "npm-check-updates": "^16.14.20",
    "postcss": "^8.4.38",
    "postcss-loader": "^8.1.1",
    "postcss-preset-env": "^9.5.14",
    "prettier": "^3.3.0",
    "sass": "^1.77.4",
    "sass-loader": "^14.2.1",
    "sharp": "^0.33.4",
    "vue-loader": "^17.4.2",
    "web-ext": "^8.0.0",
    "webpack": "^5.91.0",
    "webpack-bundle-analyzer": "^4.10.2",
    "webpack-cli": "^5.1.4",
    "webpack-plugin-vuetify": "^3.0.3"
  },
  "private": true
}


================================================
FILE: postcss.config.js
================================================
const postcssPresetEnv = require('postcss-preset-env');
const cssnano = require('cssnano');

module.exports = function (api) {
  const plugins = [postcssPresetEnv()];

  if (api.env === 'production') {
    plugins.push(cssnano({zindex: false, discardUnused: false}));
  }

  return {plugins};
};


================================================
FILE: secrets.json.example
================================================
{
  "witApiKeys": {
    "arabic": "",
    "bengali": "",
    "chinese": "",
    "dutch": "",
    "english": "",
    "finnish": "",
    "french": "",
    "german": "",
    "hindi": "",
    "indonesian": "",
    "italian": "",
    "japanese": "",
    "kannada": "",
    "korean": "",
    "malay": "",
    "malayalam": "",
    "marathi": "",
    "polish": "",
    "portuguese": "",
    "russian": "",
    "sinhala": "",
    "spanish": "",
    "swedish": "",
    "tamil": "",
    "thai": "",
    "turkish": "",
    "urdu": "",
    "vietnamese": ""
  }
}


================================================
FILE: src/assets/fonts/roboto.css
================================================
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  src: url('./files/roboto-latin-400-normal.woff2') format('woff2'),
    local('Roboto'), local('Roboto-Regular');
}

@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 500;
  src: url('./files/roboto-latin-500-normal.woff2') format('woff2'),
    local('Roboto Medium'), local('Roboto-Medium');
}

@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 700;
  src: url('./files/roboto-latin-700-normal.woff2') format('woff2'),
    local('Roboto Bold'), local('Roboto-Bold');
}


================================================
FILE: src/assets/locales/en/messages-firefox.json
================================================
{
  "optionSectionTitle_client": {
    "message": "Client App",
    "description": "Title of the options section."
  }
}


================================================
FILE: src/assets/locales/en/messages.json
================================================
{
  "extensionName": {
    "message": "Buster: Captcha Solver for Humans",
    "description": "Name of the extension."
  },

  "extensionDescription": {
    "message": "Save time by asking Buster to solve CAPTCHAs for you.",
    "description": "Description of the extension."
  },

  "optionSectionTitle_services": {
    "message": "Services",
    "description": "Title of the options section."
  },

  "optionTitle_speechService": {
    "message": "Speech recognition",
    "description": "Title of the option."
  },

  "optionValue_speechService_googleSpeechApi": {
    "message": "Google Cloud Speech-to-Text",
    "description": "Value of the option."
  },

  "optionValue_speechService_ibmSpeechApi": {
    "message": "IBM Watson Speech to Text",
    "description": "Value of the option."
  },

  "optionValue_speechService_microsoftSpeechApi": {
    "message": "Microsoft Azure Speech to Text",
    "description": "Value of the option."
  },

  "optionValue_speechService_witSpeechApiDemo": {
    "message": "Wit.ai (managed)",
    "description": "Value of the option."
  },

  "optionValue_speechService_witSpeechApi": {
    "message": "Wit.ai",
    "description": "Value of the option."
  },

  "optionTitle_microsoftSpeechApiLoc": {
    "message": "API location",
    "description": "Title of the option."
  },

  "optionValue_microsoftSpeechApiLoc_southafricanorth": {
    "message": "South Africa North",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_eastasia": {
    "message": "East Asia",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_southeastasia": {
    "message": "Southeast Asia",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_australiaeast": {
    "message": "Australia East",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_centralindia": {
    "message": "Central India",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_japaneast": {
    "message": "Japan East",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_japanwest": {
    "message": "Japan West",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_koreacentral": {
    "message": "Korea Central",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_canadacentral": {
    "message": "Canada Central",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_northeurope": {
    "message": "North Europe",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_westeurope": {
    "message": "West Europe",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_francecentral": {
    "message": "France Central",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_germanywestcentral": {
    "message": "Germany West Central",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_norwayeast": {
    "message": "Norway East",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_swedencentral": {
    "message": "Sweden Central",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_switzerlandnorth": {
    "message": "Switzerland North",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_switzerlandwest": {
    "message": "Switzerland West",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_uksouth": {
    "message": "UK South",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_uaenorth": {
    "message": "UAE North",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_brazilsouth": {
    "message": "Brazil South",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_qatarcentral": {
    "message": "Qatar Central",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_centralus": {
    "message": "Central US",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_eastus": {
    "message": "East US",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_eastus2": {
    "message": "East US 2",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_northcentralus": {
    "message": "North Central US",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_southcentralus": {
    "message": "South Central US",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_westcentralus": {
    "message": "West Central US",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_westus": {
    "message": "West US",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_westus2": {
    "message": "West US 2",
    "description": "Value of the option."
  },

  "optionValue_microsoftSpeechApiLoc_westus3": {
    "message": "West US 3",
    "description": "Value of the option."
  },

  "optionSectionTitle_client": {
    "message": "Client app",
    "description": "Title of the options section."
  },

  "optionSectionDescription_client": {
    "message": "The client app enables you to simulate user interactions and improves the success rate of the extension.",
    "description": "Description of the options section."
  },

  "optionTitle_simulateUserInput": {
    "message": "Simulate user interactions",
    "description": "Title of the option."
  },

  "optionTitle_navigateWithKeyboard": {
    "message": "Navigate with keyboard",
    "description": "Title of the option."
  },

  "optionTitle_autoUpdateClientApp": {
    "message": "Auto-update client app",
    "description": "Title of the option."
  },

  "optionSectionTitle_misc": {
    "message": "Miscellaneous",
    "description": "Title of the options section."
  },

  "optionTitle_loadEnglishChallenge": {
    "message": "Load challenge in English",
    "description": "Title of the option."
  },

  "optionTitle_tryEnglishSpeechModel": {
    "message": "Retry speech recognition with English model",
    "description": "Title of the option."
  },

  "optionTitle_appTheme": {
    "message": "Theme",
    "description": "Title of the option."
  },

  "optionValue_appTheme_auto": {
    "message": "System default",
    "description": "Value of the option."
  },

  "optionValue_appTheme_light": {
    "message": "Light",
    "description": "Value of the option."
  },

  "optionValue_appTheme_dark": {
    "message": "Dark",
    "description": "Value of the option."
  },

  "optionTitle_showContribPage": {
    "message": "Show contribution page",
    "description": "Title of the option."
  },

  "optionTitle_witSpeechApiLang": {
    "message": "API language",
    "description": "Title of the option."
  },

  "optionValue_witSpeechApiLang_arabic": {
    "message": "Arabic",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_bengali": {
    "message": "Bengali",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_chinese": {
    "message": "Chinese",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_dutch": {
    "message": "Dutch",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_english": {
    "message": "English",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_finnish": {
    "message": "Finnish",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_french": {
    "message": "French",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_german": {
    "message": "German",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_hindi": {
    "message": "Hindi",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_indonesian": {
    "message": "Indonesian",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_italian": {
    "message": "Italian",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_japanese": {
    "message": "Japanese",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_kannada": {
    "message": "Kannada",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_korean": {
    "message": "Korean",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_malay": {
    "message": "Malay",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_malayalam": {
    "message": "Malayalam",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_marathi": {
    "message": "Marathi",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_polish": {
    "message": "Polish",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_portuguese": {
    "message": "Portuguese",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_russian": {
    "message": "Russian",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_sinhala": {
    "message": "Sinhala",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_spanish": {
    "message": "Spanish",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_swedish": {
    "message": "Swedish",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_tamil": {
    "message": "Tamil",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_thai": {
    "message": "Thai",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_turkish": {
    "message": "Turkish",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_urdu": {
    "message": "Urdu",
    "description": "Value of the option."
  },

  "optionValue_witSpeechApiLang_vietnamese": {
    "message": "Vietnamese",
    "description": "Value of the option."
  },

  "inputLabel_apiUrl": {
    "message": "API endpoint",
    "description": "Label of the input."
  },

  "inputLabel_apiKey": {
    "message": "API key",
    "description": "Label of the input."
  },

  "inputLabel_apiKeyType": {
    "message": "API key: $TYPE$",
    "description": "Label of the input.",
    "placeholders": {
      "type": {
        "content": "$1",
        "example": "English"
      }
    }
  },

  "inputLabel_appLocation": {
    "message": "App location",
    "description": "Label of the input."
  },

  "inputLabel_manifestLocation": {
    "message": "Manifest location",
    "description": "Label of the input."
  },

  "buttonLabel_addApi": {
    "message": "Add API",
    "description": "Text of the button."
  },

  "buttonLabel_solve": {
    "message": "Solve the challenge",
    "description": "Text of the button."
  },

  "buttonLabel_reset": {
    "message": "Reset the challenge",
    "description": "Text of the button."
  },

  "buttonLabel_downloadApp": {
    "message": "Download app",
    "description": "Text of the button."
  },

  "buttonLabel_installApp": {
    "message": "Install app",
    "description": "Text of the button."
  },

  "buttonLabel_goBack": {
    "message": "Go back",
    "description": "Text of the button."
  },

  "buttonLabel_contribute": {
    "message": "Contribute",
    "description": "Label of the button."
  },

  "linkText_installGuide": {
    "message": "Installation guide",
    "description": "Text of the link."
  },

  "linkText_apiGuide": {
    "message": "How to get an API key?",
    "description": "Text of the link."
  },

  "pageContent_optionClientAppDownloadDesc": {
    "message": "Download and install the client app to get started. $INSTALLGUIDE$",
    "description": "Page content.",
    "placeholders": {
      "installGuide": {
        "content": "$1",
        "example": "Installation guide"
      }
    }
  },

  "pageContent_optionClientAppOSError": {
    "message": "Your operating system is not supported.",
    "description": "Page content."
  },

  "pageContent_installTitle": {
    "message": "Install Buster Client",
    "description": "Page content."
  },

  "pageContent_installDesc": {
    "message": "The client app enables you to simulate user interactions and improves the success rate of the extension.",
    "description": "Page content."
  },

  "pageContent_installSuccessTitle": {
    "message": "Installation finished",
    "description": "Page content."
  },

  "pageContent_installSuccessDesc": {
    "message": "The client app has been installed for the current browser.",
    "description": "Page content."
  },

  "pageContent_installErrorTitle": {
    "message": "Something went wrong",
    "description": "Page content."
  },

  "pageContent_installErrorDesc": {
    "message": "The installation has failed. Check the browser console for more details, and open an issue on GitHub if this error persists.",
    "description": "Page content."
  },

  "pageContent_manifestLocationDesc": {
    "message": "The manifest location is browser-dependent, edit the path only if the installation does not succeed.",
    "description": "Page content."
  },

  "pageTitle": {
    "message": "$PAGETITLE$ - $EXTENSIONNAME$",
    "description": "Title of the page.",
    "placeholders": {
      "pageTitle": {
        "content": "$1",
        "example": "Options"
      },
      "extensionName": {
        "content": "$2",
        "example": "Extension Name"
      }
    }
  },

  "pageTitle_options": {
    "message": "Options",
    "description": "Title of the page."
  },

  "pageTitle_contribute": {
    "message": "Contribute",
    "description": "Title of the page."
  },

  "info_updatingClientApp": {
    "message": "Updating client app. Solving will continue in a moment, do not switch away from the current tab.",
    "description": "Info message."
  },

  "error_captchaNotSolved": {
    "message": "CAPTCHA could not be solved. Try again after requesting a new challenge.",
    "description": "Error message."
  },

  "error_captchaNotSolvedWitai": {
    "message": "Wit.ai could not detect any speech. Try a new challenge, or switch to a more reliable service from the extension's options, such as IBM Watson.",
    "description": "Error message."
  },

  "error_missingApiUrl": {
    "message": "API endpoint missing. Visit the extension's options to configure the service.",
    "description": "Error message."
  },

  "error_missingApiKey": {
    "message": "API key missing. Visit the extension's options to configure the service.",
    "description": "Error message."
  },

  "error_apiQuotaExceeded": {
    "message": "API quota exceeded. Try again later, or visit the extension's options and switch to a different service.",
    "description": "Error message."
  },

  "error_scriptsNotAllowed": {
    "message": "Content scripts are not allowed on this page.",
    "description": "Error message."
  },

  "error_missingClientApp": {
    "message": "Cannot connect to client app. Finish setting up the app or turn off the simulation of user interactions from the extension's options.",
    "description": "Error message."
  },

  "error_outdatedClientApp": {
    "message": "The client app is outdated. Download and install the latest version from the extension's options.",
    "description": "Error message."
  },

  "error_clientAppUpdateFailed": {
    "message": "The client app cannot be updated. Download and install the latest version from the extension's options.",
    "description": "Error message."
  },

  "error_internalError": {
    "message": "Something went wrong. Open the browser console for more details.",
    "description": "Error message."
  }
}


================================================
FILE: src/assets/manifest/chrome.json
================================================
{
  "manifest_version": 3,
  "name": "__MSG_extensionName__",
  "description": "__MSG_extensionDescription__",
  "version": "0.1.0",
  "author": "Armin Sebastian",
  "homepage_url": "https://github.com/dessant/buster",
  "default_locale": "en",

  "minimum_chrome_version": "123.0",

  "permissions": [
    "storage",
    "notifications",
    "webRequest",
    "declarativeNetRequest",
    "webNavigation",
    "nativeMessaging",
    "offscreen",
    "scripting"
  ],

  "host_permissions": ["<all_urls>"],

  "content_security_policy": {
    "extension_pages": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src * data:; connect-src *; object-src 'none'; frame-ancestors http://127.0.0.1:*;"
  },

  "icons": {
    "16": "src/assets/icons/app/icon-16.png",
    "19": "src/assets/icons/app/icon-19.png",
    "24": "src/assets/icons/app/icon-24.png",
    "32": "src/assets/icons/app/icon-32.png",
    "38": "src/assets/icons/app/icon-38.png",
    "48": "src/assets/icons/app/icon-48.png",
    "64": "src/assets/icons/app/icon-64.png",
    "96": "src/assets/icons/app/icon-96.png",
    "128": "src/assets/icons/app/icon-128.png"
  },

  "action": {
    "default_icon": {
      "16": "src/assets/icons/app/icon-16.png",
      "19": "src/assets/icons/app/icon-19.png",
      "24": "src/assets/icons/app/icon-24.png",
      "32": "src/assets/icons/app/icon-32.png",
      "38": "src/assets/icons/app/icon-38.png",
      "48": "src/assets/icons/app/icon-48.png",
      "64": "src/assets/icons/app/icon-64.png",
      "96": "src/assets/icons/app/icon-96.png",
      "128": "src/assets/icons/app/icon-128.png"
    }
  },

  "options_ui": {
    "page": "src/options/index.html",
    "open_in_tab": true
  },

  "background": {
    "service_worker": "src/background/script.js"
  },

  "content_scripts": [
    {
      "matches": [
        "https://google.com/recaptcha/api2/bframe*",
        "https://www.google.com/recaptcha/api2/bframe*",
        "https://google.com/recaptcha/enterprise/bframe*",
        "https://www.google.com/recaptcha/enterprise/bframe*",
        "https://recaptcha.net/recaptcha/api2/bframe*",
        "https://www.recaptcha.net/recaptcha/api2/bframe*",
        "https://recaptcha.net/recaptcha/enterprise/bframe*",
        "https://www.recaptcha.net/recaptcha/enterprise/bframe*"
      ],
      "all_frames": true,
      "run_at": "document_idle",
      "css": ["src/base/style.css"],
      "js": ["src/base/script.js"]
    },
    {
      "matches": ["http://127.0.0.1/buster/setup?session=*"],
      "run_at": "document_idle",
      "js": ["src/scripts/init-setup.js"]
    }
  ],

  "web_accessible_resources": [
    {
      "resources": [
        "src/setup/index.html",
        "src/scripts/reset.js",
        "src/base/solver-button.css"
      ],
      "matches": ["http://*/*", "https://*/*"],
      "use_dynamic_url": true
    }
  ],

  "incognito": "split"
}


================================================
FILE: src/assets/manifest/edge.json
================================================
{
  "manifest_version": 3,
  "name": "__MSG_extensionName__",
  "description": "__MSG_extensionDescription__",
  "version": "0.1.0",
  "author": "Armin Sebastian",
  "homepage_url": "https://github.com/dessant/buster",
  "default_locale": "en",

  "minimum_chrome_version": "123.0",

  "permissions": [
    "storage",
    "notifications",
    "webRequest",
    "declarativeNetRequest",
    "webNavigation",
    "nativeMessaging",
    "offscreen",
    "scripting"
  ],

  "host_permissions": ["<all_urls>"],

  "content_security_policy": {
    "extension_pages": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src * data:; connect-src *; object-src 'none'; frame-ancestors http://127.0.0.1:*;"
  },

  "icons": {
    "16": "src/assets/icons/app/icon-16.png",
    "19": "src/assets/icons/app/icon-19.png",
    "24": "src/assets/icons/app/icon-24.png",
    "32": "src/assets/icons/app/icon-32.png",
    "38": "src/assets/icons/app/icon-38.png",
    "48": "src/assets/icons/app/icon-48.png",
    "64": "src/assets/icons/app/icon-64.png",
    "96": "src/assets/icons/app/icon-96.png",
    "128": "src/assets/icons/app/icon-128.png"
  },

  "action": {
    "default_icon": {
      "16": "src/assets/icons/app/icon-16.png",
      "19": "src/assets/icons/app/icon-19.png",
      "24": "src/assets/icons/app/icon-24.png",
      "32": "src/assets/icons/app/icon-32.png",
      "38": "src/assets/icons/app/icon-38.png",
      "48": "src/assets/icons/app/icon-48.png",
      "64": "src/assets/icons/app/icon-64.png",
      "96": "src/assets/icons/app/icon-96.png",
      "128": "src/assets/icons/app/icon-128.png"
    }
  },

  "options_ui": {
    "page": "src/options/index.html",
    "open_in_tab": true
  },

  "background": {
    "service_worker": "src/background/script.js"
  },

  "content_scripts": [
    {
      "matches": [
        "https://google.com/recaptcha/api2/bframe*",
        "https://www.google.com/recaptcha/api2/bframe*",
        "https://google.com/recaptcha/enterprise/bframe*",
        "https://www.google.com/recaptcha/enterprise/bframe*",
        "https://recaptcha.net/recaptcha/api2/bframe*",
        "https://www.recaptcha.net/recaptcha/api2/bframe*",
        "https://recaptcha.net/recaptcha/enterprise/bframe*",
        "https://www.recaptcha.net/recaptcha/enterprise/bframe*"
      ],
      "all_frames": true,
      "run_at": "document_idle",
      "css": ["src/base/style.css"],
      "js": ["src/base/script.js"]
    },
    {
      "matches": ["http://127.0.0.1/buster/setup?session=*"],
      "run_at": "document_idle",
      "js": ["src/scripts/init-setup.js"]
    }
  ],

  "web_accessible_resources": [
    {
      "resources": [
        "src/setup/index.html",
        "src/scripts/reset.js",
        "src/base/solver-button.css"
      ],
      "matches": ["http://*/*", "https://*/*"],
      "use_dynamic_url": true
    }
  ],

  "incognito": "split"
}


================================================
FILE: src/assets/manifest/firefox.json
================================================
{
  "manifest_version": 2,
  "name": "__MSG_extensionName__",
  "description": "__MSG_extensionDescription__",
  "version": "0.1.0",
  "author": "Armin Sebastian",
  "homepage_url": "https://github.com/dessant/buster",
  "default_locale": "en",

  "browser_specific_settings": {
    "gecko": {
      "id": "{e58d3966-3d76-4cd9-8552-1582fbc800c1}",
      "strict_min_version": "115.0"
    }
  },

  "permissions": [
    "storage",
    "notifications",
    "webRequest",
    "webRequestBlocking",
    "webNavigation",
    "nativeMessaging",
    "<all_urls>"
  ],

  "content_security_policy": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src * data:; connect-src *; object-src 'none'; frame-ancestors http://127.0.0.1:*;",

  "icons": {
    "16": "src/assets/icons/app/icon-16.png",
    "19": "src/assets/icons/app/icon-19.png",
    "24": "src/assets/icons/app/icon-24.png",
    "32": "src/assets/icons/app/icon-32.png",
    "38": "src/assets/icons/app/icon-38.png",
    "48": "src/assets/icons/app/icon-48.png",
    "64": "src/assets/icons/app/icon-64.png",
    "96": "src/assets/icons/app/icon-96.png",
    "128": "src/assets/icons/app/icon-128.png"
  },

  "browser_action": {
    "default_icon": {
      "16": "src/assets/icons/app/icon-16.png",
      "19": "src/assets/icons/app/icon-19.png",
      "24": "src/assets/icons/app/icon-24.png",
      "32": "src/assets/icons/app/icon-32.png",
      "38": "src/assets/icons/app/icon-38.png",
      "48": "src/assets/icons/app/icon-48.png",
      "64": "src/assets/icons/app/icon-64.png",
      "96": "src/assets/icons/app/icon-96.png",
      "128": "src/assets/icons/app/icon-128.png"
    }
  },

  "content_scripts": [
    {
      "matches": [
        "https://google.com/recaptcha/api2/bframe*",
        "https://www.google.com/recaptcha/api2/bframe*",
        "https://google.com/recaptcha/enterprise/bframe*",
        "https://www.google.com/recaptcha/enterprise/bframe*",
        "https://recaptcha.net/recaptcha/api2/bframe*",
        "https://www.recaptcha.net/recaptcha/api2/bframe*",
        "https://recaptcha.net/recaptcha/enterprise/bframe*",
        "https://www.recaptcha.net/recaptcha/enterprise/bframe*"
      ],
      "all_frames": true,
      "run_at": "document_idle",
      "css": ["src/base/style.css"],
      "js": ["src/base/script.js"]
    },
    {
      "matches": ["http://127.0.0.1/buster/setup?session=*"],
      "run_at": "document_idle",
      "js": ["src/scripts/init-setup.js"]
    }
  ],

  "options_ui": {
    "page": "src/options/index.html",
    "browser_style": false,
    "open_in_tab": true
  },

  "background": {
    "page": "src/background/index.html"
  },

  "web_accessible_resources": [
    "src/setup/index.html",
    "src/scripts/reset.js",
    "src/base/solver-button.css"
  ]
}


================================================
FILE: src/assets/manifest/opera.json
================================================
{
  "manifest_version": 3,
  "name": "__MSG_extensionName__",
  "description": "__MSG_extensionDescription__",
  "version": "0.1.0",
  "author": "Armin Sebastian",
  "homepage_url": "https://github.com/dessant/buster",
  "default_locale": "en",

  "minimum_opera_version": "109.0",

  "permissions": [
    "storage",
    "notifications",
    "webRequest",
    "declarativeNetRequest",
    "webNavigation",
    "nativeMessaging",
    "offscreen",
    "scripting"
  ],

  "host_permissions": ["<all_urls>"],

  "content_security_policy": {
    "extension_pages": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src * data:; connect-src *; object-src 'none'; frame-ancestors http://127.0.0.1:*;"
  },

  "icons": {
    "16": "src/assets/icons/app/icon-16.png",
    "19": "src/assets/icons/app/icon-19.png",
    "24": "src/assets/icons/app/icon-24.png",
    "32": "src/assets/icons/app/icon-32.png",
    "38": "src/assets/icons/app/icon-38.png",
    "48": "src/assets/icons/app/icon-48.png",
    "64": "src/assets/icons/app/icon-64.png",
    "96": "src/assets/icons/app/icon-96.png",
    "128": "src/assets/icons/app/icon-128.png"
  },

  "action": {
    "default_icon": {
      "16": "src/assets/icons/app/icon-16.png",
      "19": "src/assets/icons/app/icon-19.png",
      "24": "src/assets/icons/app/icon-24.png",
      "32": "src/assets/icons/app/icon-32.png",
      "38": "src/assets/icons/app/icon-38.png",
      "48": "src/assets/icons/app/icon-48.png",
      "64": "src/assets/icons/app/icon-64.png",
      "96": "src/assets/icons/app/icon-96.png",
      "128": "src/assets/icons/app/icon-128.png"
    }
  },

  "options_ui": {
    "page": "src/options/index.html",
    "open_in_tab": true
  },

  "background": {
    "service_worker": "src/background/script.js"
  },

  "content_scripts": [
    {
      "matches": [
        "https://google.com/recaptcha/api2/bframe*",
        "https://www.google.com/recaptcha/api2/bframe*",
        "https://google.com/recaptcha/enterprise/bframe*",
        "https://www.google.com/recaptcha/enterprise/bframe*",
        "https://recaptcha.net/recaptcha/api2/bframe*",
        "https://www.recaptcha.net/recaptcha/api2/bframe*",
        "https://recaptcha.net/recaptcha/enterprise/bframe*",
        "https://www.recaptcha.net/recaptcha/enterprise/bframe*"
      ],
      "all_frames": true,
      "run_at": "document_idle",
      "css": ["src/base/style.css"],
      "js": ["src/base/script.js"]
    },
    {
      "matches": ["http://127.0.0.1/buster/setup?session=*"],
      "run_at": "document_idle",
      "js": ["src/scripts/init-setup.js"]
    }
  ],

  "web_accessible_resources": [
    {
      "resources": [
        "src/setup/index.html",
        "src/scripts/reset.js",
        "src/base/solver-button.css"
      ],
      "matches": ["http://*/*", "https://*/*"],
      "use_dynamic_url": true
    }
  ],

  "incognito": "split"
}


================================================
FILE: src/background/index.html
================================================
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="referrer" content="no-referrer" />
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>


================================================
FILE: src/background/main.js
================================================
import aes from 'crypto-js/aes';
import sha256 from 'crypto-js/sha256';
import utf8 from 'crypto-js/enc-utf8';

import {initStorage} from 'storage/init';
import {isStorageReady} from 'storage/storage';
import storage from 'storage/storage';
import {
  showNotification,
  sendNativeMessage,
  processMessageResponse,
  processAppUse,
  showOptionsPage,
  setAppVersion,
  getStartupState,
  insertBaseModule
} from 'utils/app';
import {
  executeScript,
  scriptsAllowed,
  isValidTab,
  getBrowser,
  getPlatform,
  getExtensionDomain,
  getRandomInt,
  arrayBufferToBase64,
  base64ToArrayBuffer,
  prepareAudio,
  setupOffscreenDocument,
  sendOffscreenMessage,
  runOnce
} from 'utils/common';
import {
  recaptchaUrlRxString,
  captchaGoogleSpeechApiLangCodes,
  captchaIbmSpeechApiLangCodes,
  captchaMicrosoftSpeechApiLangCodes,
  captchaWitSpeechApiLangCodes
} from 'utils/data';
import {targetEnv, clientAppVersion, mv3} from 'utils/config';

let nativePort;

function getFrameClientPos(index) {
  let currentIndex = -1;
  if (window !== window.top) {
    const siblingWindows = window.parent.frames;
    for (let i = 0; i < siblingWindows.length; i++) {
      if (siblingWindows[i] === window) {
        currentIndex = i;
        break;
      }
    }
  }

  const targetWindow = window.frames[index];
  for (const frame of document.querySelectorAll('iframe')) {
    if (frame.contentWindow === targetWindow) {
      let {left: x, top: y} = frame.getBoundingClientRect();
      const scale = window.devicePixelRatio;

      return {x: x * scale, y: y * scale, currentIndex};
    }
  }
}

async function getFramePos(tabId, frameId, frameIndex) {
  let x = 0;
  let y = 0;

  while (true) {
    frameId = (
      await browser.webNavigation.getFrame({
        tabId,
        frameId
      })
    ).parentFrameId;
    if (frameId === -1) {
      break;
    }

    const [data] = await executeScript({
      func: getFrameClientPos,
      args: [frameIndex],
      code: `(${getFrameClientPos.toString()})(${frameIndex})`,
      tabId,
      frameIds: [frameId]
    });

    frameIndex = data.currentIndex;
    x += data.x;
    y += data.y;
  }

  return {x, y};
}

function initResetCaptcha() {
  const initReset = function (challengeUrl) {
    const script = document.createElement('script');
    script.onload = function (ev) {
      ev.target.remove();
      document.dispatchEvent(
        new CustomEvent('___resetCaptcha', {detail: challengeUrl})
      );
    };
    script.src = chrome.runtime.getURL('/src/scripts/reset.js');
    document.documentElement.appendChild(script);
  };

  const onMessage = function (request) {
    if (request.id === 'resetCaptcha') {
      removeCallbacks();
      initReset(request.challengeUrl);
    }
  };

  const removeCallbacks = function () {
    window.clearTimeout(timeoutId);
    chrome.runtime.onMessage.removeListener(onMessage);
  };

  const timeoutId = window.setTimeout(removeCallbacks, 10000); // 10 seconds

  chrome.runtime.onMessage.addListener(onMessage);
}

async function resetCaptcha(tabId, frameId, challengeUrl) {
  frameId = (await browser.webNavigation.getFrame({tabId, frameId}))
    .parentFrameId;

  if (!(await scriptsAllowed({tabId, frameId}))) {
    await showNotification({messageId: 'error_scriptsNotAllowed'});
    return;
  }

  await executeScript({
    func: initResetCaptcha,
    code: `(${initResetCaptcha.toString()})()`,
    tabId,
    frameIds: [frameId]
  });

  await browser.tabs.sendMessage(
    tabId,
    {
      id: 'resetCaptcha',
      challengeUrl
    },
    {frameId}
  );
}

function challengeRequestCallback(details) {
  const url = new URL(details.url);
  if (url.searchParams.get('hl') !== 'en') {
    url.searchParams.set('hl', 'en');
    return {redirectUrl: url.toString()};
  }
}

async function setChallengeLocale() {
  const {loadEnglishChallenge, simulateUserInput} = await storage.get([
    'loadEnglishChallenge',
    'simulateUserInput'
  ]);

  if (mv3) {
    if (loadEnglishChallenge || simulateUserInput) {
      await browser.declarativeNetRequest.updateSessionRules({
        removeRuleIds: [1],
        addRules: [
          {
            id: 1,
            action: {
              type: 'redirect',
              redirect: {
                transform: {
                  queryTransform: {
                    addOrReplaceParams: [{key: 'hl', value: 'en'}]
                  }
                }
              }
            },
            condition: {
              regexFilter: recaptchaUrlRxString,
              resourceTypes: ['sub_frame']
            }
          }
        ]
      });
    } else {
      await browser.declarativeNetRequest.updateSessionRules({
        removeRuleIds: [1]
      });
    }
  } else {
    if (loadEnglishChallenge || simulateUserInput) {
      if (
        !browser.webRequest.onBeforeRequest.hasListener(
          challengeRequestCallback
        )
      ) {
        browser.webRequest.onBeforeRequest.addListener(
          challengeRequestCallback,
          {
            urls: [
              'https://google.com/recaptcha/api2/anchor*',
              'https://google.com/recaptcha/api2/bframe*',
              'https://www.google.com/recaptcha/api2/anchor*',
              'https://www.google.com/recaptcha/api2/bframe*',
              'https://google.com/recaptcha/enterprise/anchor*',
              'https://google.com/recaptcha/enterprise/bframe*',
              'https://www.google.com/recaptcha/enterprise/anchor*',
              'https://www.google.com/recaptcha/enterprise/bframe*',
              'https://recaptcha.net/recaptcha/api2/anchor*',
              'https://recaptcha.net/recaptcha/api2/bframe*',
              'https://www.recaptcha.net/recaptcha/api2/anchor*',
              'https://www.recaptcha.net/recaptcha/api2/bframe*',
              'https://recaptcha.net/recaptcha/enterprise/anchor*',
              'https://recaptcha.net/recaptcha/enterprise/bframe*',
              'https://www.recaptcha.net/recaptcha/enterprise/anchor*',
              'https://www.recaptcha.net/recaptcha/enterprise/bframe*'
            ],
            types: ['sub_frame']
          },
          ['blocking']
        );
      }
    } else if (
      browser.webRequest.onBeforeRequest.hasListener(challengeRequestCallback)
    ) {
      browser.webRequest.onBeforeRequest.removeListener(
        challengeRequestCallback
      );
    }
  }
}

function removeRequestHeaders(details) {
  const headers = details.requestHeaders;

  const isBackgroundRequest = headers.some(
    header =>
      header.name.toLowerCase() === 'origin' &&
      header.value === self.location.origin
  );

  if (isBackgroundRequest) {
    for (const header of headers) {
      const name = header.name.toLowerCase();

      if (name === 'origin' || name === 'referer') {
        headers.splice(headers.indexOf(header), 1);
      }
    }
  }

  return {requestHeaders: headers};
}

async function addBackgroundRequestListener() {
  const ruleIds = [2];

  if (mv3) {
    await browser.declarativeNetRequest.updateSessionRules({
      removeRuleIds: ruleIds,
      addRules: [
        {
          id: ruleIds[0],
          action: {
            type: 'modifyHeaders',
            requestHeaders: [
              {operation: 'remove', header: 'Origin'},
              {operation: 'remove', header: 'Referer'}
            ]
          },
          condition: {
            // https://google.com/*
            // https://www.google.com/*
            // https://recaptcha.net/*
            // https://www.recaptcha.net/*
            // https://api.wit.ai/*
            // https://speech.googleapis.com/*
            // https://iam.cloud.ibm.com/*
            // https://*.speech-to-text.watson.cloud.ibm.com/*
            // wss://*.speech-to-text.watson.cloud.ibm.com/*
            // https://*.stt.speech.microsoft.com/*
            requestDomains: [
              'google.com',
              'recaptcha.net',
              'api.wit.ai',
              'speech.googleapis.com',
              'iam.cloud.ibm.com',
              'speech-to-text.watson.cloud.ibm.com',
              'stt.speech.microsoft.com'
            ],
            initiatorDomains: [getExtensionDomain()],
            resourceTypes: ['websocket', 'xmlhttprequest']
          }
        }
      ]
    });

    return ruleIds;
  } else {
    if (
      !browser.webRequest.onBeforeSendHeaders.hasListener(removeRequestHeaders)
    ) {
      const urls = [
        'https://google.com/*',
        'https://www.google.com/*',
        'https://recaptcha.net/*',
        'https://www.recaptcha.net/*',
        'https://api.wit.ai/*',
        'https://speech.googleapis.com/*',
        '*://*.speech-to-text.watson.cloud.ibm.com/*',
        'https://iam.cloud.ibm.com/*',
        'https://*.stt.speech.microsoft.com/*'
      ];

      const extraInfo = ['blocking', 'requestHeaders'];
      if (
        targetEnv !== 'firefox' &&
        Object.values(browser.webRequest.OnBeforeSendHeadersOptions).includes(
          'extraHeaders'
        )
      ) {
        extraInfo.push('extraHeaders');
      }

      browser.webRequest.onBeforeSendHeaders.addListener(
        removeRequestHeaders,
        {
          urls,
          types: ['websocket', 'xmlhttprequest']
        },
        extraInfo
      );
    }
  }
}

async function removeBackgroundRequestListener({ruleIds = null} = {}) {
  if (mv3) {
    await browser.declarativeNetRequest.updateSessionRules({
      removeRuleIds: ruleIds
    });
  } else {
    if (
      browser.webRequest.onBeforeSendHeaders.hasListener(removeRequestHeaders)
    ) {
      browser.webRequest.onBeforeSendHeaders.removeListener(
        removeRequestHeaders
      );
    }
  }
}

let secrets;
async function loadSecrets() {
  if (mv3) {
    const {secrets: data} = await storage.get('secrets', {area: 'session'});
    if (data) {
      return data;
    }
  } else {
    if (secrets) {
      return secrets;
    }
  }

  let data;

  try {
    const ciphertext = await (await fetch('/secrets.txt')).text();

    const key = sha256(
      (await (await fetch('/src/background/script.js')).text()) +
        (await (await fetch('/src/base/script.js')).text())
    ).toString();

    data = JSON.parse(aes.decrypt(ciphertext, key).toString(utf8));
  } catch (err) {
    const {speechService} = await storage.get('speechService');
    if (speechService === 'witSpeechApiDemo') {
      await storage.set({speechService: 'witSpeechApi'});
    }

    data = {};
  } finally {
    if (mv3) {
      await storage.set({secrets: data}, {area: 'session'});
    } else {
      secrets = data;
    }
  }

  return data;
}

async function getWitSpeechApiKey(speechService, language) {
  if (speechService === 'witSpeechApiDemo') {
    const secrets = await loadSecrets();

    const apiKeys = secrets.witApiKeys;
    if (apiKeys) {
      const apiKey = apiKeys[language];
      if (Array.isArray(apiKey)) {
        return apiKey[getRandomInt(1, apiKey.length) - 1];
      }
      return apiKey;
    }
  } else {
    const {witSpeechApiKeys: apiKeys} = await storage.get('witSpeechApiKeys');
    return apiKeys[language];
  }
}

async function getWitSpeechApiResult(apiKey, audioContent) {
  const result = {};

  const rsp = await fetch('https://api.wit.ai/speech?v=20240304', {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + apiKey
    },
    body: new Blob([audioContent], {type: 'audio/wav'}),
    credentials: 'omit'
  });

  if (rsp.status !== 200) {
    if (rsp.status === 429) {
      result.errorId = 'error_apiQuotaExceeded';
      result.errorTimeout = 6000;
    } else {
      throw new Error(`API response: ${rsp.status}, ${await rsp.text()}`);
    }
  } else {
    const data = JSON.parse((await rsp.text()).split('\r\n').at(-1)).text;
    if (data) {
      result.text = data.trim();
    }
  }

  return result;
}

async function getGoogleSpeechApiResult(
  apiKey,
  audioContent,
  language,
  detectAltLanguages
) {
  const data = {
    audio: {
      content: arrayBufferToBase64(audioContent)
    },
    config: {
      encoding: 'LINEAR16',
      languageCode: language,
      model: 'video',
      sampleRateHertz: 16000
    }
  };

  if (!['en-US', 'en-GB'].includes(language) && detectAltLanguages) {
    data.config.model = 'default';
    data.config.alternativeLanguageCodes = ['en-US'];
  }

  const rsp = await fetch(
    `https://speech.googleapis.com/v1p1beta1/speech:recognize?key=${apiKey}`,
    {
      method: 'POST',
      body: JSON.stringify(data),
      credentials: 'omit'
    }
  );

  if (rsp.status !== 200) {
    throw new Error(`API response: ${rsp.status}, ${await rsp.text()}`);
  }

  const results = (await rsp.json()).results;
  if (results) {
    return results[0].alternatives[0].transcript.trim();
  }
}

async function getIbmSpeechApiResult(apiUrl, apiKey, audioContent, model) {
  // Issue:

  // IBM HTTP API: response status 400 when Priority header is sent
  // Error: could not convert string to float: 'u=4'

  // Chrome 124 and Firefox 126 sets the Priority header for HTTP/2 requests,
  // but it cannot be removed by the extension, declarativeNetRequest
  // and webRequest do not see the header because it is set by the browser
  // after request filtering occurs.

  // Chrome accepts a custom Priority header value, but Firefox ignores it.

  // IBM has a WebSocket API, but in Chrome declarativeNetRequest rules
  // do not match WebSocket requests from background scripts,
  // so the Origin header we remove for API calls would be exposed.

  // Solution:

  // The HTTP API is used in Chrome with an invalid Priority header value
  // that can be converted to float, and the WebSocket API is used in Firefox.

  if (targetEnv === 'firefox') {
    const rsp = await fetch('https://iam.cloud.ibm.com/identity/token', {
      method: 'POST',
      body: new URLSearchParams({
        grant_type: 'urn:ibm:params:oauth:grant-type:apikey',
        apikey: apiKey
      }),
      credentials: 'omit'
    });

    if (rsp.status !== 200) {
      throw new Error(`API response: ${rsp.status}, ${await rsp.text()}`);
    }

    const {access_token: accessToken} = await rsp.json();
    const wsUrl = apiUrl.replace(/^https(.*)/, 'wss$1');

    const ws = new WebSocket(
      `${wsUrl}/v1/recognize?access_token=${accessToken}&model=${model}&x-watson-learning-opt-out=true`
    );

    return await new Promise((resolve, reject) => {
      const timeoutId = self.setTimeout(function () {
        ws.close();
        reject(new Error('API timeout'));
      }, 30000); // 30 seconds

      function response({result, error} = {}) {
        self.clearTimeout(timeoutId);

        if (error) {
          reject(error);
        } else {
          resolve(result);
        }
      }

      ws.onopen = function (ev) {
        ws.send(
          JSON.stringify({
            action: 'start',
            'content-type': 'audio/wav',
            profanity_filter: false
          })
        );

        ws.send(new Blob([audioContent]));

        ws.send(JSON.stringify({action: 'stop'}));
      };

      ws.onmessage = function (ev) {
        const results = JSON.parse(ev.data).results;

        if (results) {
          ws.close();

          response({result: results[0]?.alternatives[0].transcript.trim()});
        }
      };

      ws.onclose = function (ev) {
        if (ev.code !== 1000) {
          response({error: new Error(`API response: ${ev.code}`)});
        }
      };

      ws.onerror = function (ev) {
        response({error: new Error(`API response: ${ev.code}`)});
      };
    });
  } else {
    const rsp = await fetch(
      `${apiUrl}/v1/recognize?model=${model}&profanity_filter=false`,
      {
        method: 'POST',
        headers: {
          Authorization: 'Basic ' + self.btoa('apikey:' + apiKey),
          'X-Watson-Learning-Opt-Out': 'true',
          // Invalid value, see description above
          Priority: '1'
        },
        body: new Blob([audioContent], {type: 'audio/wav'}),
        credentials: 'omit'
      }
    );

    if (rsp.status !== 200) {
      throw new Error(`API response: ${rsp.status}, ${await rsp.text()}`);
    }

    const results = (await rsp.json()).results;
    if (results && results.length) {
      return results[0].alternatives[0].transcript.trim();
    }
  }
}

async function getMicrosoftSpeechApiResult(
  apiLocation,
  apiKey,
  audioContent,
  language
) {
  const rsp = await fetch(
    `https://${apiLocation}.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=${language}&format=detailed&profanity=raw`,
    {
      method: 'POST',
      headers: {
        'Ocp-Apim-Subscription-Key': apiKey,
        'Content-type': 'audio/wav; codec=audio/pcm; samplerate=16000'
      },
      body: new Blob([audioContent], {type: 'audio/wav'}),
      credentials: 'omit'
    }
  );

  if (rsp.status !== 200) {
    throw new Error(`API response: ${rsp.status}, ${await rsp.text()}`);
  }

  const results = (await rsp.json()).NBest;
  if (results) {
    return results[0].Lexical.trim();
  }
}

async function transcribeAudio(audioUrl, lang) {
  const audioBuffer = await (
    await fetch(audioUrl, {credentials: 'omit'})
  ).arrayBuffer();

  const audioOptions = {trimStart: 1.5, trimEnd: 1.5};

  let audioContent;
  if (mv3 && !['firefox', 'safari'].includes(targetEnv)) {
    await setupOffscreenDocument({
      url: '/src/offscreen/index.html',
      reasons: ['USER_MEDIA'],
      justification: 'process audio'
    });

    const {audioString} = await sendOffscreenMessage({
      id: 'processAudio',
      audioString: arrayBufferToBase64(audioBuffer),
      audioOptions
    });

    await browser.offscreen.closeDocument();

    audioContent = base64ToArrayBuffer(audioString);
  } else {
    audioContent = await prepareAudio(audioBuffer, audioOptions);
  }

  let solution;

  const {speechService, tryEnglishSpeechModel} = await storage.get([
    'speechService',
    'tryEnglishSpeechModel'
  ]);

  if (['witSpeechApiDemo', 'witSpeechApi'].includes(speechService)) {
    const language = captchaWitSpeechApiLangCodes[lang] || 'english';

    const apiKey = await getWitSpeechApiKey(speechService, language);

    if (!apiKey) {
      showNotification({messageId: 'error_missingApiKey'});
      return;
    }

    const result = await getWitSpeechApiResult(apiKey, audioContent);
    if (result.errorId) {
      showNotification({
        messageId: result.errorId,
        timeout: result.errorTimeout
      });
      return;
    }
    solution = result.text;

    if (!solution && language !== 'english' && tryEnglishSpeechModel) {
      const apiKey = await getWitSpeechApiKey(speechService, 'english');

      if (!apiKey) {
        showNotification({messageId: 'error_missingApiKey'});
        return;
      }

      const result = await getWitSpeechApiResult(apiKey, audioContent);
      if (result.errorId) {
        showNotification({
          messageId: result.errorId,
          timeout: result.errorTimeout
        });
        return;
      }
      solution = result.text;
    }
  } else if (speechService === 'googleSpeechApi') {
    const {googleSpeechApiKey: apiKey} =
      await storage.get('googleSpeechApiKey');

    if (!apiKey) {
      showNotification({messageId: 'error_missingApiKey'});
      return;
    }

    const language = captchaGoogleSpeechApiLangCodes[lang] || 'en-US';

    solution = await getGoogleSpeechApiResult(
      apiKey,
      audioContent,
      language,
      tryEnglishSpeechModel
    );
  } else if (speechService === 'ibmSpeechApi') {
    const {ibmSpeechApiUrl: apiUrl, ibmSpeechApiKey: apiKey} =
      await storage.get(['ibmSpeechApiUrl', 'ibmSpeechApiKey']);

    if (!apiUrl) {
      showNotification({messageId: 'error_missingApiUrl'});
      return;
    }
    if (!apiKey) {
      showNotification({messageId: 'error_missingApiKey'});
      return;
    }

    const model = captchaIbmSpeechApiLangCodes[lang] || 'en-US_Multimedia';

    solution = await getIbmSpeechApiResult(apiUrl, apiKey, audioContent, model);

    if (
      !solution &&
      !['en-US_Multimedia', 'en-GB_Multimedia'].includes(model) &&
      tryEnglishSpeechModel
    ) {
      solution = await getIbmSpeechApiResult(
        apiUrl,
        apiKey,
        audioContent,
        'en-US_Multimedia'
      );
    }
  } else if (speechService === 'microsoftSpeechApi') {
    const {microsoftSpeechApiLoc: apiLocaction, microsoftSpeechApiKey: apiKey} =
      await storage.get(['microsoftSpeechApiLoc', 'microsoftSpeechApiKey']);

    if (!apiKey) {
      showNotification({messageId: 'error_missingApiKey'});
      return;
    }

    const language = captchaMicrosoftSpeechApiLangCodes[lang] || 'en-US';

    solution = await getMicrosoftSpeechApiResult(
      apiLocaction,
      apiKey,
      audioContent,
      language
    );
    if (
      !solution &&
      !['en-US', 'en-GB'].includes(language) &&
      tryEnglishSpeechModel
    ) {
      solution = await getMicrosoftSpeechApiResult(
        apiLocaction,
        apiKey,
        audioContent,
        'en-US'
      );
    }
  }

  if (!solution) {
    if (['witSpeechApiDemo', 'witSpeechApi'].includes(speechService)) {
      showNotification({
        messageId: 'error_captchaNotSolvedWitai',
        timeout: 20000
      });
    } else {
      showNotification({messageId: 'error_captchaNotSolved', timeout: 6000});
    }
  } else {
    return solution;
  }
}

async function processMessage(request, sender) {
  // Samsung Internet 13: extension messages are sometimes also dispatched
  // to the sender frame.
  if (sender.url === self.location.href) {
    return;
  }

  if (targetEnv === 'samsung') {
    if (await isValidTab({tab: sender.tab})) {
      // Samsung Internet 13: runtime.onMessage provides wrong tab index.
      sender.tab = await browser.tabs.get(sender.tab.id);
    }
  }

  if (request.id === 'notification') {
    showNotification({
      message: request.message,
      messageId: request.messageId,
      title: request.title,
      type: request.type,
      timeout: request.timeout
    });
  } else if (request.id === 'captchaSolved') {
    await processAppUse();
  } else if (request.id === 'transcribeAudio') {
    const ruleIds = await addBackgroundRequestListener();
    try {
      return await transcribeAudio(request.audioUrl, request.lang);
    } finally {
      await removeBackgroundRequestListener({ruleIds});
    }
  } else if (request.id === 'resetCaptcha') {
    await resetCaptcha(sender.tab.id, sender.frameId, request.challengeUrl);
  } else if (request.id === 'getFramePos') {
    return getFramePos(sender.tab.id, sender.frameId, request.frameIndex);
  } else if (request.id === 'getOsScale') {
    let zoom = await browser.tabs.getZoom(sender.tab.id);

    const [[scale, windowWidth]] = await executeScript({
      func: () => [window.devicePixelRatio, window.innerWidth],
      code: `[window.devicePixelRatio, window.innerWidth];`,
      tabId: sender.tab.id
    });

    if (targetEnv === 'firefox') {
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1787649

      function getImageElement(url) {
        return new Promise(resolve => {
          const img = new Image();
          img.onload = () => {
            resolve(img);
          };
          img.onerror = () => {
            resolve();
          };
          img.onabort = () => {
            resolve();
          };
          img.src = url;
        });
      }

      const screenshotWidth = (
        await getImageElement(
          await browser.tabs.captureVisibleTab({
            format: 'jpeg',
            quality: 10
          })
        )
      ).naturalWidth;

      if (Math.abs(screenshotWidth / windowWidth - scale * zoom) < 0.005) {
        zoom = 1;
      }
    }

    return scale / zoom;
  } else if (request.id === 'startClientApp') {
    nativePort = browser.runtime.connectNative('org.buster.client');
  } else if (request.id === 'stopClientApp') {
    if (nativePort) {
      nativePort.disconnect();
    }
  } else if (request.id === 'messageClientApp') {
    const message = {
      apiVersion: clientAppVersion,
      ...request.message
    };
    return sendNativeMessage(nativePort, message);
  } else if (request.id === 'openOptions') {
    await showOptionsPage();
  } else if (request.id === 'getPlatform') {
    return getPlatform();
  } else if (request.id === 'getBrowser') {
    return getBrowser();
  } else if (request.id === 'optionChange') {
    await onOptionChange();
  } else if (request.id === 'clientAppInstall') {
    await onClientAppInstall();
  }
}

function onMessage(request, sender, sendResponse) {
  const response = processMessage(request, sender);

  return processMessageResponse(response, sendResponse);
}

async function onClientAppInstall() {
  await storage.set({simulateUserInput: true});

  await browser.runtime
    .sendMessage({id: 'reloadOptionsPage'})
    .catch(() => null);
}

async function onOptionChange() {
  await setChallengeLocale();
}

async function onActionButtonClick(tab) {
  await showOptionsPage();
}

async function onInstall(details) {
  if (['install', 'update'].includes(details.reason)) {
    await setup({event: 'install'});
  }
}

async function onStartup() {
  await setup({event: 'startup'});
}

function addActionListener() {
  if (mv3) {
    browser.action.onClicked.addListener(onActionButtonClick);
  } else {
    browser.browserAction.onClicked.addListener(onActionButtonClick);
  }
}

function addMessageListener() {
  browser.runtime.onMessage.addListener(onMessage);
}

function addInstallListener() {
  browser.runtime.onInstalled.addListener(onInstall);
}

function addStartupListener() {
  browser.runtime.onStartup.addListener(onStartup);
}

async function setup({event = ''} = {}) {
  const startup = await getStartupState({event});

  if (startup.setupInstance) {
    await runOnce('setupInstance', async () => {
      if (!(await isStorageReady())) {
        await initStorage();
      }

      if (['chrome', 'edge', 'opera', 'samsung'].includes(targetEnv)) {
        await insertBaseModule();
      }

      if (startup.install) {
        const setupTabs = await browser.tabs.query({
          url: 'http://127.0.0.1/buster/setup?session=*',
          windowType: 'normal'
        });

        for (const tab of setupTabs) {
          await browser.tabs.reload(tab.id);
        }
      }

      if (startup.update) {
        await setAppVersion();
      }
    });
  }

  if (startup.setupSession) {
    await runOnce('setupSession', async () => {
      if (mv3 && !(await isStorageReady({area: 'session'}))) {
        await initStorage({area: 'session', silent: true});
      }

      await setChallengeLocale();
    });
  }
}

function init() {
  addActionListener();
  addMessageListener();
  addInstallListener();
  addStartupListener();

  setup();
}

init();


================================================
FILE: src/base/main.js
================================================
import storage from 'storage/storage';
import {meanSleep, pingClientApp} from 'utils/app';
import {
  getText,
  findNode,
  getRandomFloat,
  sleep,
  getBrowser
} from 'utils/common';
import {targetEnv, clientAppVersion} from 'utils/config';

function main() {
  // Script may be injected multiple times.
  if (self.baseModule) {
    return;
  } else {
    self.baseModule = true;
  }

  let solverWorking = false;
  let solverButton = null;

  function setSolverState({working = true} = {}) {
    solverWorking = working;
    if (solverButton) {
      if (working) {
        solverButton.classList.add('working');
      } else {
        solverButton.classList.remove('working');
      }
    }
  }

  function resetCaptcha() {
    return browser.runtime.sendMessage({
      id: 'resetCaptcha',
      challengeUrl: window.location.href
    });
  }

  function syncUI() {
    if (isBlocked()) {
      if (!document.querySelector('.solver-controls')) {
        const div = document.createElement('div');
        div.classList.add('solver-controls');

        const button = document.createElement('button');
        button.classList.add('rc-button');
        button.setAttribute('tabindex', '0');
        button.setAttribute('title', getText('buttonLabel_reset'));
        button.id = 'reset-button';

        button.addEventListener('click', resetCaptcha);

        div.appendChild(button);
        document.querySelector('.rc-footer').appendChild(div);
      }
      return;
    }

    const helpButton = document.querySelector('#recaptcha-help-button');
    if (helpButton) {
      helpButton.remove();

      const helpButtonHolder = document.querySelector('.help-button-holder');
      helpButtonHolder.tabIndex = document.querySelector('audio#audio-source')
        ? 0
        : 2;

      const shadow = helpButtonHolder.attachShadow({
        mode: 'closed',
        delegatesFocus: true
      });

      const link = document.createElement('link');
      link.setAttribute('rel', 'stylesheet');
      link.setAttribute(
        'href',
        browser.runtime.getURL('/src/base/solver-button.css')
      );
      shadow.appendChild(link);

      solverButton = document.createElement('button');
      solverButton.setAttribute('tabindex', '0');
      solverButton.setAttribute('title', getText('buttonLabel_solve'));
      solverButton.id = 'solver-button';
      if (solverWorking) {
        solverButton.classList.add('working');
      }

      solverButton.addEventListener('click', solveChallenge);

      shadow.appendChild(solverButton);
    }
  }

  function isBlocked({timeout = 0} = {}) {
    const selector = '.rc-doscaptcha-body';
    if (timeout) {
      return new Promise(resolve => {
        findNode(selector, {timeout, throwError: false}).then(result =>
          resolve(Boolean(result))
        );
      });
    }

    return Boolean(document.querySelector(selector));
  }

  function dispatchEnter(node) {
    const keyEvent = {
      code: 'Enter',
      key: 'Enter',
      keyCode: 13,
      which: 13,
      view: window,
      bubbles: true,
      composed: true,
      cancelable: true
    };

    node.focus();
    node.dispatchEvent(new KeyboardEvent('keydown', keyEvent));
    node.dispatchEvent(new KeyboardEvent('keypress', keyEvent));
    node.click();
  }

  async function navigateToElement(node, {forward = true} = {}) {
    if (document.activeElement === node) {
      return;
    }

    if (!forward) {
      await messageClientApp({command: 'pressKey', data: 'shift'});
      await meanSleep(300);
    }

    while (document.activeElement !== node) {
      await messageClientApp({command: 'tapKey', data: 'tab'});
      await meanSleep(300);
    }

    if (!forward) {
      await messageClientApp({command: 'releaseKey', data: 'shift'});
      await meanSleep(300);
    }
  }

  async function tapEnter(node, {navigateForward = true} = {}) {
    await navigateToElement(node, {forward: navigateForward});
    await meanSleep(200);
    await messageClientApp({command: 'tapKey', data: 'enter'});
  }

  async function clickElement(node, browserBorder, osScale) {
    const targetPos = await getClickPos(node, browserBorder, osScale);
    await messageClientApp({command: 'moveMouse', ...targetPos});
    await meanSleep(100);
    await messageClientApp({command: 'clickMouse'});
  }

  async function messageClientApp(message) {
    const rsp = await browser.runtime.sendMessage({
      id: 'messageClientApp',
      message
    });

    if (!rsp.success) {
      throw new Error(`Client app response: ${rsp.text}`);
    }

    return rsp;
  }

  async function getOsScale() {
    return browser.runtime.sendMessage({id: 'getOsScale'});
  }

  async function getBrowserBorder(clickEvent, osScale) {
    const framePos = await getFrameClientPos();
    const scale = window.devicePixelRatio;

    let evScreenPropScale = osScale;
    if (
      targetEnv === 'firefox' &&
      parseInt((await getBrowser()).version.split('.')[0], 10) >= 99
    ) {
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1753836

      evScreenPropScale = scale;
    }

    return {
      left:
        clickEvent.screenX * evScreenPropScale -
        clickEvent.clientX * scale -
        framePos.x -
        window.screenX * scale,
      top:
        clickEvent.screenY * evScreenPropScale -
        clickEvent.clientY * scale -
        framePos.y -
        window.screenY * scale
    };
  }

  async function getFrameClientPos() {
    if (window !== window.top) {
      let frameIndex;
      const siblingWindows = window.parent.frames;
      for (let i = 0; i < siblingWindows.length; i++) {
        if (siblingWindows[i] === window) {
          frameIndex = i;
          break;
        }
      }

      return await browser.runtime.sendMessage({id: 'getFramePos', frameIndex});
    }

    return {x: 0, y: 0};
  }

  async function getElementScreenRect(node, browserBorder, osScale) {
    let {left: x, top: y, width, height} = node.getBoundingClientRect();

    const data = await getFrameClientPos();
    const scale = window.devicePixelRatio;

    x *= scale;
    y *= scale;
    width *= scale;
    height *= scale;

    x += data.x + browserBorder.left + window.screenX * scale;
    y += data.y + browserBorder.top + window.screenY * scale;

    const {os} = await browser.runtime.sendMessage({id: 'getPlatform'});
    if (['windows', 'macos'].includes(os)) {
      x /= osScale;
      y /= osScale;
      width /= osScale;
      height /= osScale;
    }

    return {x, y, width, height};
  }

  async function getClickPos(node, browserBorder, osScale) {
    let {x, y, width, height} = await getElementScreenRect(
      node,
      browserBorder,
      osScale
    );

    return {
      x: Math.round(x + width * getRandomFloat(0.4, 0.6)),
      y: Math.round(y + height * getRandomFloat(0.4, 0.6))
    };
  }

  async function solve(simulateUserInput, clickEvent) {
    if (isBlocked()) {
      return;
    }

    const {navigateWithKeyboard} = await storage.get('navigateWithKeyboard');

    let browserBorder;
    let osScale;
    let useMouse = true;
    if (simulateUserInput) {
      if (!navigateWithKeyboard && (clickEvent.clientX || clickEvent.clientY)) {
        osScale = await getOsScale();
        browserBorder = await getBrowserBorder(clickEvent, osScale);
      } else {
        useMouse = false;
      }
    }

    const audioElSelector = 'audio#audio-source';
    let audioEl = document.querySelector(audioElSelector);
    if (!audioEl) {
      const audioButton = document.querySelector('#recaptcha-audio-button');
      if (simulateUserInput) {
        if (useMouse) {
          await clickElement(audioButton, browserBorder, osScale);
        } else {
          audioButton.focus();
          await tapEnter(audioButton);
        }
      } else {
        dispatchEnter(audioButton);
      }

      const result = await Promise.race([
        new Promise(resolve => {
          findNode(audioElSelector, {timeout: 10000, throwError: false}).then(
            el => {
              meanSleep(500).then(() => resolve({audioEl: el}));
            }
          );
        }),
        new Promise(resolve => {
          isBlocked({timeout: 10000}).then(blocked => resolve({blocked}));
        })
      ]);

      if (result.blocked) {
        return;
      }

      audioEl = result.audioEl;
    }

    if (simulateUserInput) {
      const muteAudio = function () {
        audioEl.muted = true;
      };
      const unmuteAudio = function () {
        removeCallbacks();
        audioEl.muted = false;
      };

      audioEl.addEventListener('playing', muteAudio, {
        capture: true,
        once: true
      });
      audioEl.addEventListener('ended', unmuteAudio, {
        capture: true,
        once: true
      });

      const removeCallbacks = function () {
        window.clearTimeout(timeoutId);
        audioEl.removeEventListener('playing', muteAudio, {
          capture: true,
          once: true
        });
        audioEl.removeEventListener('ended', unmuteAudio, {
          capture: true,
          once: true
        });
      };

      const timeoutId = window.setTimeout(unmuteAudio, 10000); // 10 seconds

      const playButton = document.querySelector(
        '.rc-audiochallenge-play-button > button'
      );
      if (useMouse) {
        await clickElement(playButton, browserBorder, osScale);
      } else {
        await tapEnter(playButton);
      }
    }

    const audioUrl = audioEl.src;
    const lang = document.documentElement.lang;

    const solution = await browser.runtime.sendMessage({
      id: 'transcribeAudio',
      audioUrl,
      lang
    });

    if (!solution) {
      return;
    }

    const input = document.querySelector('#audio-response');
    if (simulateUserInput) {
      if (useMouse) {
        await clickElement(input, browserBorder, osScale);
      } else {
        await navigateToElement(input);
      }
      await meanSleep(200);

      await messageClientApp({command: 'typeText', data: solution});
    } else {
      input.value = solution;
    }

    const submitButton = document.querySelector('#recaptcha-verify-button');
    if (simulateUserInput) {
      if (useMouse) {
        await clickElement(submitButton, browserBorder, osScale);
      } else {
        await tapEnter(submitButton);
      }
    } else {
      dispatchEnter(submitButton);
    }

    browser.runtime.sendMessage({id: 'captchaSolved'});
  }

  function solveChallenge(ev) {
    ev.preventDefault();
    ev.stopImmediatePropagation();

    if (!ev.isTrusted || solverWorking) {
      return;
    }
    setSolverState({working: true});

    runSolver(ev)
      .catch(err => {
        browser.runtime.sendMessage({
          id: 'notification',
          messageId: 'error_internalError'
        });
        console.log(err.toString());
        throw err;
      })
      .finally(() => {
        setSolverState({working: false});
      });
  }

  async function runSolver(ev) {
    const {simulateUserInput, autoUpdateClientApp} = await storage.get([
      'simulateUserInput',
      'autoUpdateClientApp'
    ]);

    if (simulateUserInput) {
      try {
        let pingRsp;

        try {
          pingRsp = await pingClientApp({stop: false, checkResponse: false});
        } catch (err) {
          browser.runtime.sendMessage({
            id: 'notification',
            messageId: 'error_missingClientApp'
          });
          browser.runtime.sendMessage({id: 'openOptions'});
          throw err;
        }

        if (!pingRsp.success) {
          if (!pingRsp.apiVersion !== clientAppVersion) {
            if (!autoUpdateClientApp || pingRsp.apiVersion === '1') {
              browser.runtime.sendMessage({
                id: 'notification',
                messageId: 'error_outdatedClientApp'
              });
              browser.runtime.sendMessage({id: 'openOptions'});
              throw new Error('Client app outdated');
            } else {
              try {
                browser.runtime.sendMessage({
                  id: 'notification',
                  messageId: 'info_updatingClientApp'
                });
                const rsp = await browser.runtime.sendMessage({
                  id: 'messageClientApp',
                  message: {command: 'installClient', data: clientAppVersion}
                });

                if (rsp.success) {
                  await browser.runtime.sendMessage({id: 'stopClientApp'});
                  await sleep(10000);

                  await pingClientApp({stop: false});

                  await browser.runtime.sendMessage({
                    id: 'messageClientApp',
                    message: {command: 'installCleanup'}
                  });
                } else {
                  throw new Error(`Client app update failed: ${rsp.data}`);
                }
              } catch (err) {
                browser.runtime.sendMessage({
                  id: 'notification',
                  messageId: 'error_clientAppUpdateFailed'
                });
                browser.runtime.sendMessage({id: 'openOptions'});
                throw err;
              }
            }
          }
        }
      } catch (err) {
        console.log(err.toString());
        await browser.runtime.sendMessage({id: 'stopClientApp'});
        return;
      }
    }

    try {
      await solve(simulateUserInput, ev);
    } finally {
      if (simulateUserInput) {
        await browser.runtime.sendMessage({id: 'stopClientApp'});
      }
    }
  }

  function init() {
    const observer = new MutationObserver(syncUI);
    observer.observe(document, {
      childList: true,
      subtree: true
    });

    syncUI();
  }

  init();
}

main();


================================================
FILE: src/base/solver-button.css
================================================
#solver-button {
  background-image: url('data:image/svg+xml,%3Csvg%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%20192%20192%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M71.182%20138.872l27.077%2027.077H8.002v-18.051c0-19.947%2032.312-36.103%2072.205-36.103l17.058.993-26.083%2026.084m9.025-117.333c19.939%200%2036.103%2016.164%2036.103%2036.103s-16.164%2036.103-36.103%2036.103S44.105%2077.58%2044.105%2057.641s16.163-36.102%2036.102-36.102z%22%20fill%3D%22%23ff9f43%22%2F%3E%3Cpath%20fill%3D%22%2327ae60%22%20d%3D%22M171.362%2098.256l12.636%2012.726-58.938%2059.479-31.319-31.589%2012.636-12.727%2018.683%2018.774%2046.302-46.663%22%2F%3E%3C%2Fsvg%3E');
  background-color: transparent;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 32px 32px;
  width: 48px;
  height: 48px;
  padding: 0;
  border: 0;
  opacity: 0.8;
  cursor: pointer;
}

#solver-button:focus,
#solver-button:hover {
  opacity: 1;
}

#solver-button:focus {
  outline: none;
}

#solver-button:focus-visible {
  background-color: rgba(216, 216, 216, 0.8);
}

#solver-button.working {
  background-image: url('data:image/svg+xml,%3Csvg%20width%3D%2244%22%20height%3D%2244%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20stroke%3D%22%23727272%22%3E%3Cg%20fill%3D%22none%22%20fill-rule%3D%22evenodd%22%20stroke-width%3D%225%22%3E%3Ccircle%20cx%3D%2222%22%20cy%3D%2222%22%20r%3D%221%22%3E%3Canimate%20attributeName%3D%22r%22%20begin%3D%220s%22%20dur%3D%221.8s%22%20values%3D%221%3B%2020%22%20calcMode%3D%22spline%22%20keyTimes%3D%220%3B%201%22%20keySplines%3D%220.165%2C%200.84%2C%200.44%2C%201%22%20repeatCount%3D%22indefinite%22%2F%3E%3Canimate%20attributeName%3D%22stroke-opacity%22%20begin%3D%220s%22%20dur%3D%221.8s%22%20values%3D%221%3B%200%22%20calcMode%3D%22spline%22%20keyTimes%3D%220%3B%201%22%20keySplines%3D%220.3%2C%200.61%2C%200.355%2C%201%22%20repeatCount%3D%22indefinite%22%2F%3E%3C%2Fcircle%3E%3Ccircle%20cx%3D%2222%22%20cy%3D%2222%22%20r%3D%221%22%3E%3Canimate%20attributeName%3D%22r%22%20begin%3D%22-0.9s%22%20dur%3D%221.8s%22%20values%3D%221%3B%2020%22%20calcMode%3D%22spline%22%20keyTimes%3D%220%3B%201%22%20keySplines%3D%220.165%2C%200.84%2C%200.44%2C%201%22%20repeatCount%3D%22indefinite%22%2F%3E%3Canimate%20attributeName%3D%22stroke-opacity%22%20begin%3D%22-0.9s%22%20dur%3D%221.8s%22%20values%3D%221%3B%200%22%20calcMode%3D%22spline%22%20keyTimes%3D%220%3B%201%22%20keySplines%3D%220.3%2C%200.61%2C%200.355%2C%201%22%20repeatCount%3D%22indefinite%22%2F%3E%3C%2Fcircle%3E%3C%2Fg%3E%3C%2Fsvg%3E') !important;
  opacity: 1;
}


================================================
FILE: src/base/style.css
================================================
#reset-button {
  background-image: url('data:image/svg+xml,%3Csvg%20width%3D%2224%22%20height%3D%2224%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M17.65%206.35C16.2%204.9%2014.21%204%2012%204c-4.42%200-7.99%203.58-7.99%208s3.57%208%207.99%208c3.73%200%206.84-2.55%207.73-6h-2.08c-.82%202.33-3.04%204-5.65%204-3.31%200-6-2.69-6-6s2.69-6%206-6c1.66%200%203.14.69%204.22%201.78L13%2011h7V4l-2.35%202.35z%22%2F%3E%3C%2Fsvg%3E') !important;
  background-color: transparent !important;
}

.solver-controls {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  height: 58px !important;
}

.rc-doscaptcha-header {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  height: 30px !important;
}

.rc-doscaptcha-body {
  height: 120px !important;
}

.rc-doscaptcha-footer {
  height: 60px !important;
  pointer-events: auto !important;
}

.rc-doscaptcha-footer .rc-controls {
  display: none !important;
}


================================================
FILE: src/contribute/App.vue
================================================
<template>
  <vn-app>
    <vn-contribute
      :extName="extName"
      :extSlug="extSlug"
      :notice="notice"
      @open="contribute"
    >
    </vn-contribute>
  </vn-app>
</template>

<script>
import {App} from 'vueton';
import {Contribute} from 'vueton/components/contribute';

import {showPage} from 'utils/app';
import {getText} from 'utils/common';

export default {
  components: {
    [App.name]: App,
    [Contribute.name]: Contribute
  },

  data: function () {
    return {
      extName: getText('extensionName'),
      extSlug: 'buster',
      notice: ''
    };
  },

  methods: {
    setup: function () {
      const query = new URL(window.location.href).searchParams;
      if (query.get('action') === 'auto') {
        this.notice = `This page is shown once a year while using the extension.`;
      }
    },

    contribute: async function ({url} = {}) {
      await showPage({url});
    }
  },

  created: function () {
    document.title = getText('pageTitle', [
      getText('pageTitle_contribute'),
      this.extName
    ]);

    this.setup();
  }
};
</script>

<style lang="scss">
@use 'vueton/styles' as vueton;

@include vueton.theme-base;

.v-application__wrap {
  display: flex;
  align-items: center;
}
</style>


================================================
FILE: src/contribute/index.html
================================================
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="color-scheme" content="light dark" />
    <meta name="referrer" content="no-referrer" />
    <link
      rel="icon"
      href="/src/assets/icons/app/icon-64.png"
      type="image/png"
    />

    <link href="/src/assets/fonts/roboto.css" rel="stylesheet" />
    <link href="/src/commons-ui/style.css" rel="stylesheet" />
    <link href="style.css" rel="stylesheet" />

    <script src="/src/commons-ui/script.js"></script>
    <script src="script.js" defer></script>
  </head>
  <body></body>
</html>


================================================
FILE: src/contribute/main.js
================================================
import {createApp} from 'vue';

import {configApp, loadFonts} from 'utils/app';
import {configVuetify} from 'utils/vuetify';
import App from './App';

async function init() {
  await loadFonts(['400 14px Roboto', '500 14px Roboto', '700 14px Roboto']);

  const app = createApp(App);

  await configApp(app);
  await configVuetify(app);

  app.mount('body');
}

init();


================================================
FILE: src/offscreen/index.html
================================================
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="referrer" content="no-referrer" />
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>


================================================
FILE: src/offscreen/main.js
================================================
import {
  arrayBufferToBase64,
  base64ToArrayBuffer,
  prepareAudio
} from 'utils/common';

async function processAudio(audioString, audioOptions) {
  const audioBuffer = base64ToArrayBuffer(audioString);
  const audioContent = await prepareAudio(audioBuffer, audioOptions);

  messagePort.postMessage({
    audioString: arrayBufferToBase64(audioContent)
  });
}

function onMessage(request) {
  if (request.id === 'processAudio') {
    processAudio(request.audioString, request.audioOptions);
  }
}

let messagePort;
function onConnect(port) {
  if (port.name === 'offscreen') {
    messagePort = port;
    messagePort.onMessage.addListener(onMessage);
  }
}

browser.runtime.onConnect.addListener(onConnect);


================================================
FILE: src/options/App.vue
================================================
<template>
  <vn-app v-if="dataLoaded">
    <div class="section">
      <div class="section-title" v-once>
        {{ getText('optionSectionTitle_services') }}
      </div>
      <div class="option-wrap">
        <div class="option select">
          <vn-select
            :label="getText('optionTitle_speechService')"
            :items="listItems.speechService"
            v-model="options.speechService"
            transition="scale-transition"
          >
          </vn-select>
        </div>

        <div
          class="option text-field"
          v-if="options.speechService === 'googleSpeechApi'"
        >
          <vn-text-field
            :label="getText('inputLabel_apiKey')"
            v-model.trim="options.googleSpeechApiKey"
          >
          </vn-text-field>
        </div>

        <a
          class="service-guide"
          v-if="options.speechService === 'googleSpeechApi'"
          target="_blank"
          rel="noreferrer"
          href="https://github.com/dessant/buster/wiki/Configuring-Google-Cloud-Speech-to-Text"
        >
          {{ getText('linkText_apiGuide') }}
        </a>

        <div
          class="option text-field"
          v-if="options.speechService === 'ibmSpeechApi'"
        >
          <vn-text-field
            v-model.trim="options.ibmSpeechApiUrl"
            :label="getText('inputLabel_apiUrl')"
          >
          </vn-text-field>
        </div>
        <div
          class="option text-field"
          v-if="options.speechService === 'ibmSpeechApi'"
        >
          <vn-text-field
            v-model.trim="options.ibmSpeechApiKey"
            :label="getText('inputLabel_apiKey')"
          >
          </vn-text-field>
        </div>

        <a
          class="service-guide"
          v-if="options.speechService === 'ibmSpeechApi'"
          target="_blank"
          rel="noreferrer"
          href="https://github.com/dessant/buster/wiki/Configuring-IBM-Watson-Speech-to-Text"
        >
          {{ getText('linkText_apiGuide') }}
        </a>

        <div
          class="option select"
          v-if="options.speechService === 'microsoftSpeechApi'"
        >
          <vn-select
            :label="getText('optionTitle_microsoftSpeechApiLoc')"
            :items="listItems.microsoftSpeechApiLoc"
            v-model="options.microsoftSpeechApiLoc"
            transition="scale-transition"
          >
          </vn-select>
        </div>
        <div
          class="option text-field"
          v-if="options.speechService === 'microsoftSpeechApi'"
        >
          <vn-text-field
            v-model.trim="options.microsoftSpeechApiKey"
            :label="getText('inputLabel_apiKey')"
          >
          </vn-text-field>
        </div>

        <a
          class="service-guide"
          v-if="options.speechService === 'microsoftSpeechApi'"
          target="_blank"
          rel="noreferrer"
          href="https://github.com/dessant/buster/wiki/Configuring-Microsoft-Azure-Speech-to-Text"
        >
          {{ getText('linkText_apiGuide') }}
        </a>

        <vn-text-field
          class="text-field"
          v-if="options.speechService === 'witSpeechApi'"
          v-for="item in witSpeechApis"
          :key="item.id"
          :model-value="options.witSpeechApiKeys[item] || ''"
          :label="
            getText('inputLabel_apiKeyType', [
              getText(`optionValue_witSpeechApiLang_${item}`)
            ])
          "
          @update:modelValue="saveWitSpeechApiKey($event.trim(), item)"
        >
        </vn-text-field>
        <div
          class="wit-add-api"
          v-if="options.speechService === 'witSpeechApi'"
        >
          <vn-select
            :label="getText('optionTitle_witSpeechApiLang')"
            :items="listItems.witSpeechApiLang"
            v-model="witSpeechApiLang"
            transition="scale-transition"
          >
          </vn-select>

          <vn-button :disabled="!witSpeechApiLang" @click="addWitSpeechApi">
            {{ getText('buttonLabel_addApi') }}
          </vn-button>
        </div>

        <a
          class="service-guide"
          v-if="options.speechService === 'witSpeechApi'"
          target="_blank"
          rel="noreferrer"
          href="https://github.com/dessant/buster/wiki/Configuring-Wit.ai"
        >
          {{ getText('linkText_apiGuide') }}
        </a>
      </div>
    </div>

    <div class="section section-client">
      <div class="section-title" v-once>
        {{ getText('optionSectionTitle_client') }}
      </div>
      <div class="section-desc" v-once>
        {{ getText('optionSectionDescription_client') }}
      </div>
      <div class="option-wrap">
        <div
          class="option"
          v-if="
            clientAppInstalled ||
            (clientAppVerified && options.simulateUserInput)
          "
        >
          <vn-switch
            :label="getText('optionTitle_simulateUserInput')"
            v-model="options.simulateUserInput"
          ></vn-switch>
        </div>

        <div
          class="option"
          v-if="clientAppVerified && options.simulateUserInput"
        >
          <vn-switch
            :label="getText('optionTitle_navigateWithKeyboard')"
            v-model="options.navigateWithKeyboard"
          ></vn-switch>
        </div>

        <div class="option" v-if="clientAppInstalled">
          <vn-switch
            :label="getText('optionTitle_autoUpdateClientApp')"
            v-model="options.autoUpdateClientApp"
          ></vn-switch>
        </div>

        <div
          class="client-download"
          v-if="clientAppVerified && !clientAppInstalled"
        >
          <div
            class="download-desc"
            v-html="
              getText('pageContent_optionClientAppDownloadDesc', [
                `<a target='_blank' rel='noreferrer' href='${installGuideUrl}'>${getText(
                  'linkText_installGuide'
                )}</a>`
              ])
            "
          ></div>
          <div class="download-error" v-if="!clientAppDownloadUrl">
            {{ getText('pageContent_optionClientAppOSError') }}
          </div>

          <vn-button
            class="download-button"
            :disabled="!clientAppDownloadUrl"
            @click="$refs.dlLink.click()"
            variant="elevated"
          >
            {{ getText('buttonLabel_downloadApp') }}
          </vn-button>
          <a
            ref="dlLink"
            class="download-link"
            target="_blank"
            rel="noreferrer"
            :href="clientAppDownloadUrl"
          ></a>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-title" v-once>
        {{ getText('optionSectionTitle_misc') }}
      </div>
      <div class="option-wrap">
        <div class="option select">
          <vn-select
            :label="getText('optionTitle_appTheme')"
            :items="listItems.appTheme"
            v-model="options.appTheme"
            transition="scale-transition"
          >
          </vn-select>
        </div>
        <div class="option">
          <vn-switch
            :label="getText('optionTitle_loadEnglishChallenge')"
            v-model="options.loadEnglishChallenge"
          ></vn-switch>
        </div>
        <div class="option" v-if="!options.loadEnglishChallenge">
          <vn-switch
            :label="getText('optionTitle_tryEnglishSpeechModel')"
            v-model="options.tryEnglishSpeechModel"
          ></vn-switch>
        </div>
        <div class="option" v-if="enableContributions">
          <vn-switch
            :label="getText('optionTitle_showContribPage')"
            v-model="options.showContribPage"
          ></vn-switch>
        </div>
        <div class="option button" v-if="enableContributions">
          <vn-button
            class="contribute-button vn-icon--start"
            @click="showContribute"
            ><vn-icon
              src="/src/assets/icons/misc/favorite-filled.svg"
            ></vn-icon>
            {{ getText('buttonLabel_contribute') }}
          </vn-button>
        </div>
      </div>
    </div>
  </vn-app>
</template>

<script>
import {toRaw} from 'vue';
import {App, Button, Icon, Select, Switch, TextField} from 'vueton';

import storage from 'storage/storage';
import {getListItems, showContributePage, pingClientApp} from 'utils/app';
import {getText} from 'utils/common';
import {enableContributions, clientAppVersion} from 'utils/config';
import {
  optionKeys,
  clientAppPlatforms,
  captchaWitSpeechApiLangCodes,
  microsoftSpeechApiRegions
} from 'utils/data';

export default {
  components: {
    [App.name]: App,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Select.name]: Select,
    [Switch.name]: Switch,
    [TextField.name]: TextField
  },

  data: function () {
    return {
      dataLoaded: false,

      listItems: {
        ...getListItems(
          {
            speechService: [
              'witSpeechApiDemo',
              'googleSpeechApi',
              'witSpeechApi',
              'ibmSpeechApi',
              'microsoftSpeechApi'
            ]
          },
          {scope: 'optionValue_speechService'}
        ),
        ...getListItems(
          {microsoftSpeechApiLoc: microsoftSpeechApiRegions},
          {scope: 'optionValue_microsoftSpeechApiLoc'}
        ),
        ...getListItems(
          {
            witSpeechApiLang: [
              ...new Set(
                Object.values(captchaWitSpeechApiLangCodes).filter(Boolean)
              )
            ].sort()
          },
          {scope: 'optionValue_witSpeechApiLang'}
        ),
        ...getListItems(
          {appTheme: ['auto', 'light', 'dark']},
          {scope: 'optionValue_appTheme'}
        )
      },

      enableContributions,

      witSpeechApiLang: null,
      witSpeechApis: [],

      clientAppVerified: false,
      clientAppInstalled: false,
      clientAppDownloadUrl: '',
      installGuideUrl: '',

      options: {
        speechService: '',
        googleSpeechApiKey: '',
        ibmSpeechApiUrl: '',
        ibmSpeechApiKey: '',
        microsoftSpeechApiLoc: '',
        microsoftSpeechApiKey: '',
        witSpeechApiKeys: {},
        loadEnglishChallenge: false,
        tryEnglishSpeechModel: false,
        simulateUserInput: false,
        autoUpdateClientApp: false,
        navigateWithKeyboard: false,
        appTheme: '',
        showContribPage: false
      }
    };
  },

  methods: {
    getText,

    setup: async function () {
      browser.runtime.onMessage.addListener(this.onMessage);

      const options = await storage.get(optionKeys);

      for (const option of Object.keys(this.options)) {
        this.options[option] = options[option];

        this.$watch(
          `options.${option}`,
          async function (value) {
            await storage.set({[option]: toRaw(value)});
            await browser.runtime.sendMessage({id: 'optionChange'});
          },
          {deep: true}
        );
      }

      this.witSpeechApis = Object.keys(options.witSpeechApiKeys);
      this.setWitSpeechApiLangOptions();

      document.title = getText('pageTitle', [
        getText('pageTitle_options'),
        getText('extensionName')
      ]);

      this.verifyClientApp();

      this.dataLoaded = true;
    },

    onMessage: function (request, sender) {
      if (request.id === 'reloadOptionsPage') {
        self.location.reload();
      }
    },

    verifyClientApp: async function () {
      try {
        await pingClientApp();
        this.clientAppInstalled = true;
      } catch (err) {
        if (!this.installGuideUrl) {
          this.installGuideUrl =
            'https://github.com/dessant/buster/wiki/Installing-the-client-app';
          const {os, arch} = this.$env;
          if (clientAppPlatforms.includes(`${os}/${arch}`)) {
            this.installGuideUrl += `#${os}`;
            this.clientAppDownloadUrl = `https://github.com/dessant/buster-client/releases/download/v${clientAppVersion}/buster-client-setup-v${clientAppVersion}-${os}-${arch}`;
            if (os === 'windows') {
              this.clientAppDownloadUrl += '.exe';
            }
          }
        }

        this.clientAppInstalled = false;
      }

      this.clientAppVerified = true;
    },

    setWitSpeechApiLangOptions: function () {
      this.listItems.witSpeechApiLang = this.listItems.witSpeechApiLang.filter(
        item => !this.witSpeechApis.includes(item.value)
      );
    },

    addWitSpeechApi: function () {
      this.witSpeechApis.push(this.witSpeechApiLang);
      this.witSpeechApiLang = null;
      this.setWitSpeechApiLangOptions();
    },

    saveWitSpeechApiKey: function (value, lang) {
      const apiKeys = this.options.witSpeechApiKeys;
      if (value) {
        this.options.witSpeechApiKeys = Object.assign({}, apiKeys, {
          [lang]: value
        });
      } else if (apiKeys[lang]) {
        delete apiKeys[lang];
        this.options.witSpeechApiKeys = Object.assign({}, apiKeys);
      }
    },

    showContribute: async function () {
      await showContributePage();
    }
  },

  created: function () {
    document.title = getText('pageTitle', [
      getText('pageTitle_options'),
      getText('extensionName')
    ]);

    this.setup();
  }
};
</script>

<style lang="scss">
@use 'vueton/styles' as vueton;

@include vueton.theme-base;
@include vueton.transitions;

.v-application__wrap {
  display: grid;
  grid-row-gap: 32px;
  grid-column-gap: 48px;
  padding: 24px;
  grid-auto-rows: min-content;
  grid-auto-columns: min-content;
}

.section-title {
  font-size: 20px;
  font-weight: 500;
  letter-spacing: 0.25px;
  line-height: 32px;
}

.section-desc {
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 0.25px;
  line-height: 20px;

  padding-top: 8px;
  max-width: 380px;
}

.option-wrap {
  display: grid;
  grid-row-gap: 24px;
  padding-top: 24px;
}

.option {
  display: flex;
  align-items: center;
  height: 20px;

  &.button {
    height: 40px;
  }

  &.select,
  &.text-field {
    height: 56px;
  }

  & .contribute-button {
    @include vueton.theme-prop(color, primary);

    & .vn-icon {
      @include vueton.theme-prop(background-color, cta);
    }
  }
}

.text-field .v-input__control {
  width: 326px;
}

.section-client .section-desc {
  width: 272px;
}

.wit-add-api {
  display: flex;
  align-items: center;

  & .vn-select {
    & .v-input__control,
    & .v-input__details {
      max-width: calc(100vw - 48px - 124px) !important;
    }
  }

  & .vn-button {
    margin-left: 24px;
    @include vueton.theme-prop(color, primary);
  }
}

.service-guide {
  font-size: 16px;
  font-weight: 400;
  letter-spacing: 0.5px;
  line-height: 24px;
}

.client-download {
  width: 272px;
}

.download-desc,
.download-error {
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 0.25px;
  line-height: 20px;
}

.download-desc a {
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 0.25px;
  line-height: 20px;
}

.download-desc {
  max-width: 240px;
}

.download-error {
  margin-top: 12px;
  @include vueton.theme-prop(color, error);
}

.download-link {
  visibility: hidden;
}

.download-button {
  margin-top: 24px;
  @include vueton.theme-prop(background-color, primary);

  & .v-btn__content {
    @include vueton.theme-prop(color, on-primary);
  }
}
</style>


================================================
FILE: src/options/index.html
================================================
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="color-scheme" content="light dark" />
    <meta name="referrer" content="no-referrer" />
    <link
      rel="icon"
      href="/src/assets/icons/app/icon-64.png"
      type="image/png"
    />

    <link href="/src/assets/fonts/roboto.css" rel="stylesheet" />
    <link href="/src/commons-ui/style.css" rel="stylesheet" />
    <link href="style.css" rel="stylesheet" />

    <script src="/src/commons-ui/script.js"></script>
    <script src="script.js" defer></script>
  </head>
  <body></body>
</html>


================================================
FILE: src/options/main.js
================================================
import {createApp} from 'vue';

import {configApp, loadFonts} from 'utils/app';
import {configVuetify} from 'utils/vuetify';
import App from './App';

async function init() {
  await loadFonts(['400 14px Roboto', '500 14px Roboto']);

  const app = createApp(App);

  await configApp(app);
  await configVuetify(app);

  app.mount('body');
}

init();


================================================
FILE: src/scripts/init-setup.js
================================================
function setup() {
  const url = new URL(browser.runtime.getURL('/src/setup/index.html'));
  url.searchParams.set(
    'session',
    new URL(window.location.href).searchParams.get('session')
  );
  url.searchParams.set('port', window.location.port);

  const frame = document.createElement('iframe');
  frame.src = url.href;
  document.body.appendChild(frame);
}

setup();


================================================
FILE: src/scripts/reset.js
================================================
(function () {
  const reset = function (challengeUrl) {
    for (const [id, client] of Object.entries(___grecaptcha_cfg.clients)) {
      for (const [_, items] of Object.entries(client)) {
        if (items instanceof Object) {
          for (const [_, v] of Object.entries(items)) {
            if (v instanceof Element && v.src === challengeUrl) {
              (grecaptcha.reset || grecaptcha.enterprise.reset)(id);
              return;
            }
          }
        }
      }
    }
  };

  const onMessage = function (ev) {
    ev.stopImmediatePropagation();
    removeCallbacks();

    reset(ev.detail);
  };

  const removeCallbacks = function () {
    window.clearTimeout(timeoutId);
    document.removeEventListener('___resetCaptcha', onMessage, {
      capture: true,
      once: true
    });
  };
  const timeoutId = window.setTimeout(removeCallbacks, 10000); // 10 seconds

  document.addEventListener('___resetCaptcha', onMessage, {
    capture: true,
    once: true
  });
})();


================================================
FILE: src/setup/App.vue
================================================
<template>
  <vn-app v-if="dataLoaded">
    <div class="wrap" v-if="!isInstallSuccess && !isInstallError">
      <div class="title">
        {{ getText('pageContent_installTitle') }}
      </div>
      <div class="desc">
        {{ getText('pageContent_installDesc') }}
      </div>

      <vn-text-field
        :label="getText('inputLabel_appLocation')"
        v-model.trim="appDir"
      >
      </vn-text-field>

      <vn-text-field
        class="manifest-location"
        v-if="manifestDirEditable"
        :label="getText('inputLabel_manifestLocation')"
        v-model.trim="manifestDir"
      >
      </vn-text-field>

      <div class="manifest-desc" v-if="manifestDirEditable">
        {{ getText('pageContent_manifestLocationDesc') }}
      </div>

      <vn-button
        class="button install-button"
        :disabled="
          isInstalling || !appDir || (manifestDirEditable && !manifestDir)
        "
        @click="runInstall"
        variant="elevated"
      >
        {{ getText('buttonLabel_installApp') }}
      </vn-button>
    </div>

    <div class="wrap" v-if="isInstallSuccess">
      <div class="title">{{ getText('pageContent_installSuccessTitle') }}</div>
      <div class="desc">{{ getText('pageContent_installSuccessDesc') }}</div>

      <div class="success-icon">🎉</div>
    </div>

    <div class="wrap" v-if="isInstallError">
      <div class="title error-title">
        {{ getText('pageContent_installErrorTitle') }}
      </div>
      <div class="desc">{{ getText('pageContent_installErrorDesc') }}</div>

      <vn-button
        class="button error-button"
        @click="isInstallError = false"
        variant="elevated"
      >
        {{ getText('buttonLabel_goBack') }}
      </vn-button>
    </div>
  </vn-app>
</template>

<script>
import {App, Button, TextField} from 'vueton';

import {pingClientApp} from 'utils/app';
import {getText} from 'utils/common';

export default {
  components: {
    [App.name]: App,
    [Button.name]: Button,
    [TextField.name]: TextField
  },

  data: function () {
    const urlParams = new URL(window.location.href).searchParams;
    const apiURL = new URL('http://127.0.0.1/api/v1');
    apiURL.port = urlParams.get('port');

    return {
      dataLoaded: false,

      apiUrl: apiURL.href,
      session: urlParams.get('session'),
      browser: '',
      appDir: '',
      manifestDir: '',
      manifestDirEditable: false,

      isInstalling: false,
      isInstallSuccess: false,
      isInstallError: false
    };
  },

  methods: {
    getText,

    getExtensionId: function () {
      let id = browser.runtime.id;
      if (!this.$env.isFirefox) {
        const scheme = window.location.protocol;
        id = `${scheme}//${id}/`;
      }

      return id;
    },

    setLocation: async function () {
      try {
        await this.location();
      } catch (err) {
        this.isInstallError = true;
        console.log(err.toString());
      }
    },

    runInstall: async function () {
      this.isInstalling = true;

      try {
        await this.install();
      } catch (err) {
        this.isInstallError = true;
        console.log(err.toString());
      } finally {
        this.isInstalling = false;
      }

      if (this.isInstallSuccess) {
        const data = new FormData();
        data.append('session', this.session);

        await fetch(`${this.apiUrl}/setup/close`, {
          method: 'POST',
          body: data
        });

        await browser.runtime.sendMessage({id: 'clientAppInstall'});
      }
    },

    location: async function () {
      const data = new FormData();
      data.append('session', this.session);
      data.append('browser', this.browser);
      data.append('targetEnv', this.$env.targetEnv);

      const rsp = await fetch(`${this.apiUrl}/setup/location`, {
        method: 'POST',
        body: data
      });

      const results = await rsp.json();

      if (rsp.status === 200) {
        this.appDir = results.appDir;
        this.manifestDir = results.manifestDir;
      } else {
        throw new Error(results.error);
      }
    },

    install: async function () {
      const data = new FormData();
      data.append('session', this.session);
      data.append('appDir', this.appDir);
      data.append('manifestDir', this.manifestDir);
      data.append('browser', this.browser);
      data.append('targetEnv', this.$env.targetEnv);
      data.append('extension', this.getExtensionId());

      const rsp = await fetch(`${this.apiUrl}/setup/install`, {
        method: 'POST',
        body: data
      });

      if (rsp.status === 200) {
        await pingClientApp();

        this.isInstallSuccess = true;
      } else {
        throw new Error((await rsp.json()).error);
      }
    }
  },

  created: async function () {
    this.browser = (await browser.runtime.sendMessage({id: 'getBrowser'})).name;

    await this.setLocation();

    if (!this.$env.isWindows) {
      this.manifestDirEditable = true;
    }

    this.dataLoaded = true;
  }
};
</script>

<style lang="scss">
@use 'vueton/styles' as vueton;

@include vueton.theme-base;

.v-application__wrap {
  display: flex;
  align-items: center;
  padding: 24px;
}

.wrap {
  display: flex;
  flex-direction: column;
  max-width: 400px;
}

.title {
  font-size: 20px;
  font-weight: 500;
  letter-spacing: 0.25px;
  line-height: 32px;

  margin-top: 48px;
  align-self: center;
}

.error-title {
  @include vueton.theme-prop(color, error);
}

.desc {
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 0.25px;
  line-height: 20px;

  margin-top: 32px;
  margin-bottom: 24px;
}

.manifest-location {
  margin-top: 24px;
}

.manifest-desc {
  font-size: 12px;
  font-weight: 400;
  letter-spacing: 0.4px;
  line-height: 20px;

  margin-top: 12px;
}

.button {
  @include vueton.theme-prop(background-color, primary);

  & .v-btn__content {
    @include vueton.theme-prop(color, on-primary);
  }
}

.install-button {
  margin-top: 32px;
  align-self: center;
}

.error-button {
  margin-top: 8px;
  align-self: center;
}

.success-icon {
  font-size: 72px;
  margin-top: 48px;
  align-self: center;
}
</style>


================================================
FILE: src/setup/index.html
================================================
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="referrer" content="no-referrer" />
    <link
      rel="icon"
      href="/src/assets/icons/app/icon-64.png"
      type="image/png"
    />

    <link href="/src/assets/fonts/roboto.css" rel="stylesheet" />
    <link href="/src/commons-ui/style.css" rel="stylesheet" />
    <link href="style.css" rel="stylesheet" />

    <script src="/src/commons-ui/script.js"></script>
    <script src="script.js" defer></script>
  </head>
  <body></body>
</html>


================================================
FILE: src/setup/main.js
================================================
import {createApp} from 'vue';

import {configApp, loadFonts} from 'utils/app';
import {configVuetify} from 'utils/vuetify';
import App from './App';

async function init() {
  await loadFonts(['400 14px Roboto', '500 14px Roboto']);

  const app = createApp(App);

  await configApp(app);
  await configVuetify(app);

  app.mount('body');
}

// only run in a frame
if (window.top !== window) {
  init();
}


================================================
FILE: src/storage/config.json
================================================
{
  "revisions": {
    "local": [
      "UoT3kGyBH",
      "ONiJBs00o",
      "UidMDYaYA",
      "nOedd0Txqd",
      "ZtLMLoh1ag",
      "t335iRDhZ8",
      "X3djS8vZC",
      "DlgF14Chrh",
      "Lj3MYlSr4L",
      "20221211221603_add_theme_support",
      "20221214080901_update_services",
      "20240514170322_add_appversion"
    ],
    "session": ["20240514122825_initial_version"]
  }
}


================================================
FILE: src/storage/init.js
================================================
import {migrate} from 'wesa';

import {isStorageArea} from './storage';

async function initStorage({area = 'local', data = null, silent = false} = {}) {
  const context = {
    getAvailableRevisions: async ({area} = {}) =>
      (
        await import(/* webpackMode: "eager" */ 'storage/config.json', {
          with: {type: 'json'}
        })
      ).revisions[area],
    getCurrentRevision: async ({area} = {}) =>
      (await browser.storage[area].get('storageVersion')).storageVersion,
    getRevision: async ({area, revision} = {}) =>
      import(
        /* webpackMode: "eager" */ `storage/revisions/${area}/${revision}.js`
      )
  };

  if (area === 'local') {
    await migrateLegacyStorage();
  }

  return migrate(context, {area, data, silent});
}

async function migrateLegacyStorage() {
  if (await isStorageArea({area: 'sync'})) {
    const {storageVersion: syncVersion} =
      await browser.storage.sync.get('storageVersion');
    if (syncVersion && syncVersion.length < 14) {
      const {storageVersion: localVersion} =
        await browser.storage.local.get('storageVersion');

      if (!localVersion || localVersion.length < 14) {
        const syncData = await browser.storage.sync.get(null);
        await browser.storage.local.clear();
        await browser.storage.local.set(syncData);
        await browser.storage.sync.clear();
      }
    }
  }
}

export {initStorage};


================================================
FILE: src/storage/revisions/local/20221211221603_add_theme_support.js
================================================
import {getDayPrecisionEpoch} from 'utils/common';

const message = 'Add theme support';

const revision = '20221211221603_add_theme_support';

async function upgrade() {
  const changes = {
    appTheme: 'auto', // auto, light, dark
    showContribPage: true,
    contribPageLastOpen: 0,
    contribPageLastAutoOpen: 0
  };

  const {installTime} = await browser.storage.local.get('installTime');
  changes.installTime = getDayPrecisionEpoch(installTime);

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/20221214080901_update_services.js
================================================
const message = 'Update services';

const revision = '20221214080901_update_services';

async function upgrade() {
  const changes = {};

  const {witSpeechApiKeys} = await browser.storage.local.get(
    'witSpeechApiKeys'
  );
  delete witSpeechApiKeys['catalan'];
  delete witSpeechApiKeys['telugu'];
  changes.witSpeechApiKeys = witSpeechApiKeys;

  await browser.storage.local.remove('ibmSpeechApiLoc');
  changes.ibmSpeechApiUrl = '';

  changes.microsoftSpeechApiLoc = 'eastus';

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/20240514170322_add_appversion.js
================================================
const message = 'Add appVersion';

const revision = '20240514170322_add_appversion';

async function upgrade() {
  const changes = {
    appVersion: ''
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/DlgF14Chrh.js
================================================
const message = 'Revision description';

const revision = 'DlgF14Chrh';

async function upgrade() {
  const changes = {};
  const {speechService} = await browser.storage.local.get('speechService');
  if (speechService === 'googleSpeechApiDemo') {
    changes.speechService = 'witSpeechApiDemo';
  }

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/Lj3MYlSr4L.js
================================================
const message = 'Add navigateWithKeyboard';

const revision = 'Lj3MYlSr4L';

async function upgrade() {
  const changes = {
    navigateWithKeyboard: false
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/ONiJBs00o.js
================================================
const message = 'Add IBM Watson Speech to Text API';

const revision = 'ONiJBs00o';

async function upgrade() {
  const changes = {
    ibmSpeechApiLoc: 'frankfurt', // 'frankfurt', 'dallas', 'washington', 'sydney', 'tokyo'
    ibmSpeechApiKey: ''
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/UidMDYaYA.js
================================================
const message = 'Add Microsoft Azure Speech to Text API';

const revision = 'UidMDYaYA';

async function upgrade() {
  const changes = {
    microsoftSpeechApiLoc: 'eastUs', // 'eastUs', 'eastUs2', 'westUs', 'westUs2', 'eastAsia', 'southeastAsia', 'westEu', 'northEu'
    microsoftSpeechApiKey: ''
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/UoT3kGyBH.js
================================================
const message = 'Initial version';

const revision = 'UoT3kGyBH';

async function upgrade() {
  const changes = {
    speechService: 'googleSpeechApiDemo', // 'googleSpeechApiDemo', 'witSpeechApiDemo', 'googleSpeechApi', 'witSpeechApi', 'ibmSpeechApi', 'microsoftSpeechApi'
    googleSpeechApiKey: '',
    installTime: new Date().getTime(),
    useCount: 0
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/X3djS8vZC.js
================================================
const message = 'Add autoUpdateClientApp option';

const revision = 'X3djS8vZC';

async function upgrade() {
  const changes = {
    autoUpdateClientApp: true
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/ZtLMLoh1ag.js
================================================
const message = 'Add loadEnglishChallenge option';

const revision = 'ZtLMLoh1ag';

async function upgrade() {
  const changes = {
    loadEnglishChallenge: true
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/nOedd0Txqd.js
================================================
const message = 'Add Wit Speech API and tryEnglishSpeechModel option';

const revision = 'nOedd0Txqd';

async function upgrade() {
  const changes = {
    witSpeechApiKeys: {},
    tryEnglishSpeechModel: true
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/local/t335iRDhZ8.js
================================================
const message = 'Add simulateUserInput option';

const revision = 't335iRDhZ8';

async function upgrade() {
  const changes = {
    simulateUserInput: false
  };

  changes.storageVersion = revision;
  return browser.storage.local.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/revisions/session/20240514122825_initial_version.js
================================================
const message = 'Initial version';

const revision = '20240514122825_initial_version';

async function upgrade() {
  const changes = {
    platformInfo: null
  };

  changes.storageVersion = revision;
  return browser.storage.session.set(changes);
}

export {message, revision, upgrade};


================================================
FILE: src/storage/storage.js
================================================
import {storageRevisions} from 'utils/config';

async function isStorageArea({area = 'local'} = {}) {
  try {
    await browser.storage[area].get('');
    return true;
  } catch (err) {
    return false;
  }
}

const storageReady = {local: false, session: false, sync: false};
async function isStorageReady({area = 'local'} = {}) {
  if (storageReady[area]) {
    return true;
  } else {
    const {storageVersion} = await browser.storage[area].get('storageVersion');
    if (storageVersion && storageVersion === storageRevisions[area]) {
      storageReady[area] = true;
      return true;
    }
  }

  return false;
}

async function ensureStorageReady({area = 'local'} = {}) {
  if (!storageReady[area]) {
    return new Promise((resolve, reject) => {
      let stop;

      const checkStorage = async function () {
        if (await isStorageReady({area})) {
          self.clearTimeout(timeoutId);
          resolve();
        } else if (stop) {
          reject(new Error(`Storage (${area}) is not ready`));
        } else {
          self.setTimeout(checkStorage, 30);
        }
      };

      const timeoutId = self.setTimeout(function () {
        stop = true;
      }, 60000); // 1 minute

      checkStorage();
    });
  }
}

async function get(keys = null, {area = 'local'} = {}) {
  await ensureStorageReady({area});
  return browser.storage[area].get(keys);
}

async function set(obj, {area = 'local'} = {}) {
  await ensureStorageReady({area});
  return browser.storage[area].set(obj);
}

async function remove(keys, {area = 'local'} = {}) {
  await ensureStorageReady({area});
  return browser.storage[area].remove(keys);
}

async function clear({area = 'local'} = {}) {
  await ensureStorageReady({area});
  return browser.storage[area].clear();
}

export default {get, set, remove, clear};
export {isStorageArea, isStorageReady, ensureStorageReady};


================================================
FILE: src/utils/app.js
================================================
import {v4 as uuidv4} from 'uuid';

import storage from 'storage/storage';
import {
  getText,
  insertCSS,
  executeScript,
  createTab,
  getActiveTab,
  isValidTab,
  getPlatform,
  getDayPrecisionEpoch,
  getDarkColorSchemeQuery,
  getRandomInt,
  sleep
} from 'utils/common';
import {recaptchaChallengeUrlRx} from 'utils/data';
import {
  targetEnv,
  enableContributions,
  storageRevisions,
  appVersion,
  mv3
} from 'utils/config';

async function showNotification({
  message,
  messageId,
  title,
  type = 'info',
  timeout = 0
} = {}) {
  if (!title) {
    title = getText('extensionName');
  }
  if (messageId) {
    message = getText(messageId);
  }

  if (targetEnv === 'safari') {
    return browser.runtime.sendNativeMessage('application.id', {
      id: 'notification',
      message
    });
  } else {
    const notification = await browser.notifications.create(
      `bc-notification-${type}`,
      {
        type: 'basic',
        title,
        message,
        iconUrl: '/src/assets/icons/app/icon-64.png'
      }
    );

    if (timeout) {
      self.setTimeout(() => {
        browser.notifications.clear(notification);
      }, timeout);
    }

    return notification;
  }
}

function getListItems(data, {scope = '', shortScope = ''} = {}) {
  const results = {};

  for (const [group, items] of Object.entries(data)) {
    results[group] = [];

    items.forEach(function (item) {
      if (item.value === undefined) {
        item = {value: item};
      }

      item.title = getText(`${scope ? scope + '_' : ''}${item.value}`);

      if (shortScope) {
        item.shortTitle = getText(`${shortScope}_${item.value}`);
      }

      results[group].push(item);
    });
  }

  return results;
}

async function insertBaseModule({activeTab = false} = {}) {
  const tabs = [];
  if (activeTab) {
    const tab = await getActiveTab();
    if (tab) {
      tabs.push(tab);
    }
  } else {
    tabs.push(
      ...(await browser.tabs.query({
        url: ['http://*/*', 'https://*/*'],
        windowType: 'normal'
      }))
    );
  }

  for (const tab of tabs) {
    const tabId = tab.id;

    const frames = await browser.webNavigation.getAllFrames({tabId});
    for (const frame of frames) {
      const frameId = frame.frameId;

      if (frameId && recaptchaChallengeUrlRx.test(frame.url)) {
        insertCSS({
          files: ['/src/base/style.css'],
          tabId,
          frameIds: [frameId]
        });

        executeScript({
          files: ['/src/base/script.js'],
          tabId,
          frameIds: [frameId],
          injectImmediately: false
        });
      }
    }
  }
}

async function loadFonts(fonts) {
  await Promise.allSettled(fonts.map(font => document.fonts.load(font)));
}

function processMessageResponse(response, sendResponse) {
  if (targetEnv === 'safari') {
    response.then(function (result) {
      // Safari 15: undefined response will cause sendMessage to never resolve.
      if (result === undefined) {
        result = null;
      }
      sendResponse(result);
    });

    return true;
  } else {
    return response;
  }
}

async function configApp(app) {
  const platform = await getPlatform();

  const classes = [platform.targetEnv, platform.os];
  document.documentElement.classList.add(...classes);

  if (app) {
    app.config.globalProperties.$env = platform;
  }
}

async function getAppTheme(theme) {
  if (!theme) {
    ({appTheme: theme} = await storage.get('appTheme'));
  }

  if (theme === 'auto') {
    theme = getDarkColorSchemeQuery().matches ? 'dark' : 'light';
  }

  return theme;
}

function addSystemThemeListener(callback) {
  getDarkColorSchemeQuery().addEventListener('change', function () {
    callback();
  });
}

function addAppThemeListener(callback) {
  browser.storage.onChanged.addListener(function (changes, area) {
    if (area === 'local' && changes.appTheme) {
      callback();
    }
  });
}

function addThemeListener(callback) {
  addSystemThemeListener(callback);
  addAppThemeListener(callback);
}

async function getOpenerTabId({tab, tabId = null} = {}) {
  if (!tab && tabId !== null) {
    tab = await browser.tabs.get(tabId).catch(err => null);
  }

  if ((await isValidTab({tab})) && !(await getPlatform()).isMobile) {
    return tab.id;
  }

  return null;
}

async function showPage({
  url = '',
  setOpenerTab = true,
  getTab = false,
  activeTab = null
} = {}) {
  if (!activeTab) {
    activeTab = await getActiveTab();
  }

  const props = {url, index: activeTab.index + 1, active: true, getTab};

  if (setOpenerTab) {
    props.openerTabId = await getOpenerTabId({tab: activeTab});
  }

  return createTab(props);
}

async function autoShowContributePage({
  minUseCount = 0, // 0-1000
  minInstallDays = 0,
  minLastOpenDays = 0,
  minLastAutoOpenDays = 0,
  action = 'auto',
  activeTab = null
} = {}) {
  if (enableContributions) {
    const options = await storage.get([
      'showContribPage',
      'useCount',
      'installTime',
      'contribPageLastOpen',
      'contribPageLastAutoOpen'
    ]);

    const epoch = getDayPrecisionEpoch();

    if (
      options.showContribPage &&
      options.useCount >= minUseCount &&
      epoch - options.installTime >= minInstallDays * 86400000 &&
      epoch - options.contribPageLastOpen >= minLastOpenDays * 86400000 &&
      epoch - options.contribPageLastAutoOpen >= minLastAutoOpenDays * 86400000
    ) {
      await storage.set({
        contribPageLastOpen: epoch,
        contribPageLastAutoOpen: epoch
      });

      return showContributePage({
        action,
        updateStats: false,
        activeTab,
        getTab: true
      });
    }
  }
}

let useCountLastUpdate = 0;
async function updateUseCount({
  valueChange = 1,
  maxUseCount = Infinity,
  minInterval = 0
} = {}) {
  if (Date.now() - useCountLastUpdate >= minInterval) {
    useCountLastUpdate = Date.now();

    const {useCount} = await storage.get('useCount');

    if (useCount < maxUseCount) {
      await storage.set({useCount: useCount + valueChange});
    } else if (useCount > maxUseCount) {
      await storage.set({useCount: maxUseCount});
    }
  }
}

async function processAppUse({
  action = 'auto',
  activeTab = null,
  showContribPage = true
} = {}) {
  await updateUseCount({
    valueChange: 1,
    maxUseCount: 1000
  });

  if (showContribPage) {
    return autoShowContributePage({
      minUseCount: 10,
      minInstallDays: 14,
      minLastOpenDays: 14,
      minLastAutoOpenDays: 365,
      activeTab,
      action
    });
  }
}

async function showContributePage({
  action = '',
  updateStats = true,
  getTab = false,
  activeTab = null
} = {}) {
  if (updateStats) {
    await storage.set({contribPageLastOpen: getDayPrecisionEpoch()});
  }

  let url = browser.runtime.getURL('/src/contribute/index.html');
  if (action) {
    url = `${url}?action=${action}`;
  }

  return showPage({url, getTab, activeTab});
}

async function showOptionsPage({getTab = false, activeTab = null} = {}) {
  // Samsung Internet 13: runtime.openOptionsPage fails.
  // runtime.openOptionsPage adds new tab at the end of the tab list.
  return showPage({
    url: browser.runtime.getURL('/src/options/index.html'),
    getTab,
    activeTab
  });
}

async function setAppVersion() {
  await storage.set({appVersion});
}

async function isSessionStartup() {
  const privateContext = browser.extension.inIncognitoContext;

  const sessionKey = privateContext ? 'privateSession' : 'session';
  const session = (await browser.storage.session.get(sessionKey))[sessionKey];

  if (!session) {
    await browser.storage.session.set({[sessionKey]: true});
  }

  if (privateContext) {
    try {
      if (!(await self.caches.has(sessionKey))) {
        await self.caches.open(sessionKey);

        return true;
      }
    } catch (err) {
      return true;
    }
  }

  if (!session) {
    return true;
  }
}

async function isStartup() {
  const startup = {
    install: false,
    update: false,
    session: false,
    setupInstance: false,
    setupSession: false
  };

  const {storageVersion, appVersion: savedAppVersion} =
    await browser.storage.local.get(['storageVersion', 'appVersion']);

  if (!storageVersion) {
    startup.install = true;
  }

  if (
    storageVersion !== storageRevisions.local ||
    savedAppVersion !== appVersion
  ) {
    startup.update = true;
  }

  if (mv3 && (await isSessionStartup())) {
    startup.session = true;
  }

  if (startup.install || startup.update) {
    startup.setupInstance = true;
  }

  if (startup.session || !mv3) {
    startup.setupSession = true;
  }

  return startup;
}

let startupState;
async function getStartupState({event = ''} = {}) {
  if (!startupState) {
    startupState = isStartup();
    startupState.events = [];
  }

  if (event) {
    startupState.events.push(event);
  }

  const startup = await startupState;

  if (startupState.events.includes('install')) {
    startup.setupInstance = true;
  }
  if (startupState.events.includes('startup')) {
    startup.setupSession = true;
  }

  return startup;
}

function sendNativeMessage(port, message, {timeout = 10000} = {}) {
  return new Promise((resolve, reject) => {
    const id = uuidv4();
    message.id = id;

    const messageCallback = function (msg) {
      if (msg.id !== id) {
        return;
      }
      removeListeners();
      resolve(msg);
    };
    const errorCallback = function () {
      removeListeners();
      reject('No response from native app');
    };
    const removeListeners = function () {
      self.clearTimeout(timeoutId);
      port.onMessage.removeListener(messageCallback);
      port.onDisconnect.removeListener(errorCallback);
    };

    const timeoutId = self.setTimeout(function () {
      errorCallback();
    }, timeout);

    port.onMessage.addListener(messageCallback);
    port.onDisconnect.addListener(errorCallback);

    port.postMessage(message);
  });
}

async function pingClientApp({
  start = true,
  stop = true,
  checkResponse = true
} = {}) {
  if (start) {
    await browser.runtime.sendMessage({id: 'startClientApp'});
  }

  const rsp = await browser.runtime.sendMessage({
    id: 'messageClientApp',
    message: {command: 'ping'}
  });

  if (stop) {
    await browser.runtime.sendMessage({id: 'stopClientApp'});
  }

  if (checkResponse && (!rsp.success || rsp.data !== 'pong')) {
    
Download .txt
gitextract_irjtamld/

├── .browserslistrc
├── .github/
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.md
│   │   ├── config.yml
│   │   └── feature_request.md
│   ├── label-actions.yml
│   ├── pull_request_template.md
│   └── workflows/
│       ├── ci.yml
│       ├── label-actions.yml
│       └── lockdown.yml
├── .gitignore
├── .nvmrc
├── .prettierignore
├── .prettierrc.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── babel.config.js
├── gulpfile.js
├── package.json
├── postcss.config.js
├── secrets.json.example
├── src/
│   ├── assets/
│   │   ├── fonts/
│   │   │   └── roboto.css
│   │   ├── locales/
│   │   │   └── en/
│   │   │       ├── messages-firefox.json
│   │   │       └── messages.json
│   │   └── manifest/
│   │       ├── chrome.json
│   │       ├── edge.json
│   │       ├── firefox.json
│   │       └── opera.json
│   ├── background/
│   │   ├── index.html
│   │   └── main.js
│   ├── base/
│   │   ├── main.js
│   │   ├── solver-button.css
│   │   └── style.css
│   ├── contribute/
│   │   ├── App.vue
│   │   ├── index.html
│   │   └── main.js
│   ├── offscreen/
│   │   ├── index.html
│   │   └── main.js
│   ├── options/
│   │   ├── App.vue
│   │   ├── index.html
│   │   └── main.js
│   ├── scripts/
│   │   ├── init-setup.js
│   │   └── reset.js
│   ├── setup/
│   │   ├── App.vue
│   │   ├── index.html
│   │   └── main.js
│   ├── storage/
│   │   ├── config.json
│   │   ├── init.js
│   │   ├── revisions/
│   │   │   ├── local/
│   │   │   │   ├── 20221211221603_add_theme_support.js
│   │   │   │   ├── 20221214080901_update_services.js
│   │   │   │   ├── 20240514170322_add_appversion.js
│   │   │   │   ├── DlgF14Chrh.js
│   │   │   │   ├── Lj3MYlSr4L.js
│   │   │   │   ├── ONiJBs00o.js
│   │   │   │   ├── UidMDYaYA.js
│   │   │   │   ├── UoT3kGyBH.js
│   │   │   │   ├── X3djS8vZC.js
│   │   │   │   ├── ZtLMLoh1ag.js
│   │   │   │   ├── nOedd0Txqd.js
│   │   │   │   └── t335iRDhZ8.js
│   │   │   └── session/
│   │   │       └── 20240514122825_initial_version.js
│   │   └── storage.js
│   └── utils/
│       ├── app.js
│       ├── common.js
│       ├── config.js
│       ├── data.js
│       └── vuetify.js
└── webpack.config.js
Download .txt
SYMBOL INDEX (127 symbols across 26 files)

FILE: gulpfile.js
  function initEnv (line 33) | function initEnv() {
  function init (line 37) | function init(done) {
  function js (line 45) | function js(done) {
  function html (line 53) | function html() {
  function css (line 73) | function css() {
  function images (line 77) | async function images(done) {
  function fonts (line 129) | async function fonts(done) {
  function locale (line 149) | async function locale(done) {
  function manifest (line 187) | function manifest() {
  function license (line 202) | function license(done) {
  function secrets (line 226) | function secrets(done) {
  function zip (line 253) | function zip(done) {
  function inspect (line 264) | function inspect(done) {

FILE: src/background/main.js
  function getFrameClientPos (line 44) | function getFrameClientPos(index) {
  function getFramePos (line 67) | async function getFramePos(tabId, frameId, frameIndex) {
  function initResetCaptcha (line 98) | function initResetCaptcha() {
  function resetCaptcha (line 128) | async function resetCaptcha(tabId, frameId, challengeUrl) {
  function challengeRequestCallback (line 154) | function challengeRequestCallback(details) {
  function setChallengeLocale (line 162) | async function setChallengeLocale() {
  function removeRequestHeaders (line 240) | function removeRequestHeaders(details) {
  function addBackgroundRequestListener (line 262) | async function addBackgroundRequestListener() {
  function removeBackgroundRequestListener (line 344) | async function removeBackgroundRequestListener({ruleIds = null} = {}) {
  function loadSecrets (line 361) | async function loadSecrets() {
  function getWitSpeechApiKey (line 402) | async function getWitSpeechApiKey(speechService, language) {
  function getWitSpeechApiResult (line 420) | async function getWitSpeechApiResult(apiKey, audioContent) {
  function getGoogleSpeechApiResult (line 449) | async function getGoogleSpeechApiResult(
  function getIbmSpeechApiResult (line 491) | async function getIbmSpeechApiResult(apiUrl, apiKey, audioContent, model) {
  function getMicrosoftSpeechApiResult (line 611) | async function getMicrosoftSpeechApiResult(
  function transcribeAudio (line 640) | async function transcribeAudio(audioUrl, lang) {
  function processMessage (line 804) | async function processMessage(request, sender) {
  function onMessage (line 907) | function onMessage(request, sender, sendResponse) {
  function onClientAppInstall (line 913) | async function onClientAppInstall() {
  function onOptionChange (line 921) | async function onOptionChange() {
  function onActionButtonClick (line 925) | async function onActionButtonClick(tab) {
  function onInstall (line 929) | async function onInstall(details) {
  function onStartup (line 935) | async function onStartup() {
  function addActionListener (line 939) | function addActionListener() {
  function addMessageListener (line 947) | function addMessageListener() {
  function addInstallListener (line 951) | function addInstallListener() {
  function addStartupListener (line 955) | function addStartupListener() {
  function setup (line 959) | async function setup({event = ''} = {}) {
  function init (line 1000) | function init() {

FILE: src/base/main.js
  function main (line 12) | function main() {

FILE: src/contribute/main.js
  function init (line 7) | async function init() {

FILE: src/offscreen/main.js
  function processAudio (line 7) | async function processAudio(audioString, audioOptions) {
  function onMessage (line 16) | function onMessage(request) {
  function onConnect (line 23) | function onConnect(port) {

FILE: src/options/main.js
  function init (line 7) | async function init() {

FILE: src/scripts/init-setup.js
  function setup (line 1) | function setup() {

FILE: src/setup/main.js
  function init (line 7) | async function init() {

FILE: src/storage/init.js
  function initStorage (line 5) | async function initStorage({area = 'local', data = null, silent = false}...
  function migrateLegacyStorage (line 28) | async function migrateLegacyStorage() {

FILE: src/storage/revisions/local/20221211221603_add_theme_support.js
  function upgrade (line 7) | async function upgrade() {

FILE: src/storage/revisions/local/20221214080901_update_services.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/20240514170322_add_appversion.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/DlgF14Chrh.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/Lj3MYlSr4L.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/ONiJBs00o.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/UidMDYaYA.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/UoT3kGyBH.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/X3djS8vZC.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/ZtLMLoh1ag.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/nOedd0Txqd.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/local/t335iRDhZ8.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/revisions/session/20240514122825_initial_version.js
  function upgrade (line 5) | async function upgrade() {

FILE: src/storage/storage.js
  function isStorageArea (line 3) | async function isStorageArea({area = 'local'} = {}) {
  function isStorageReady (line 13) | async function isStorageReady({area = 'local'} = {}) {
  function ensureStorageReady (line 27) | async function ensureStorageReady({area = 'local'} = {}) {
  function get (line 52) | async function get(keys = null, {area = 'local'} = {}) {
  function set (line 57) | async function set(obj, {area = 'local'} = {}) {
  function remove (line 62) | async function remove(keys, {area = 'local'} = {}) {
  function clear (line 67) | async function clear({area = 'local'} = {}) {

FILE: src/utils/app.js
  function showNotification (line 26) | async function showNotification({
  function getListItems (line 66) | function getListItems(data, {scope = '', shortScope = ''} = {}) {
  function insertBaseModule (line 90) | async function insertBaseModule({activeTab = false} = {}) {
  function loadFonts (line 131) | async function loadFonts(fonts) {
  function processMessageResponse (line 135) | function processMessageResponse(response, sendResponse) {
  function configApp (line 151) | async function configApp(app) {
  function getAppTheme (line 162) | async function getAppTheme(theme) {
  function addSystemThemeListener (line 174) | function addSystemThemeListener(callback) {
  function addAppThemeListener (line 180) | function addAppThemeListener(callback) {
  function addThemeListener (line 188) | function addThemeListener(callback) {
  function getOpenerTabId (line 193) | async function getOpenerTabId({tab, tabId = null} = {}) {
  function showPage (line 205) | async function showPage({
  function autoShowContributePage (line 224) | async function autoShowContributePage({
  function updateUseCount (line 266) | async function updateUseCount({
  function processAppUse (line 284) | async function processAppUse({
  function showContributePage (line 306) | async function showContributePage({
  function showOptionsPage (line 324) | async function showOptionsPage({getTab = false, activeTab = null} = {}) {
  function setAppVersion (line 334) | async function setAppVersion() {
  function isSessionStartup (line 338) | async function isSessionStartup() {
  function isStartup (line 365) | async function isStartup() {
  function getStartupState (line 404) | async function getStartupState({event = ''} = {}) {
  function sendNativeMessage (line 426) | function sendNativeMessage(port, message, {timeout = 10000} = {}) {
  function pingClientApp (line 459) | async function pingClientApp({
  function meanSleep (line 484) | function meanSleep(ms) {

FILE: src/utils/common.js
  function getText (line 7) | function getText(messageName, substitutions) {
  function insertCSS (line 11) | function insertCSS({
  function executeScript (line 50) | async function executeScript({
  function scriptsAllowed (line 108) | async function scriptsAllowed({tabId, frameId = 0} = {}) {
  function createTab (line 121) | async function createTab({
  function getActiveTab (line 156) | async function getActiveTab() {
  function isValidTab (line 164) | async function isValidTab({tab, tabId = null} = {}) {
  function getPlatformInfo (line 175) | async function getPlatformInfo() {
  function getPlatform (line 221) | async function getPlatform() {
  function isAndroid (line 282) | async function isAndroid() {
  function getDarkColorSchemeQuery (line 287) | function getDarkColorSchemeQuery() {
  function getDayPrecisionEpoch (line 291) | function getDayPrecisionEpoch(epoch) {
  function isBackgroundPageContext (line 299) | function isBackgroundPageContext() {
  function getExtensionDomain (line 307) | function getExtensionDomain() {
  function getRandomInt (line 319) | function getRandomInt(min, max) {
  function getRandomFloat (line 323) | function getRandomFloat(min, max) {
  function arrayBufferToBase64 (line 327) | function arrayBufferToBase64(buffer) {
  function base64ToArrayBuffer (line 338) | function base64ToArrayBuffer(string) {
  function querySelectorXpath (line 350) | function querySelectorXpath(selector, {rootNode = null} = {}) {
  function nodeQuerySelector (line 362) | function nodeQuerySelector(
  function findNode (line 373) | function findNode(
  function getBrowser (line 423) | async function getBrowser() {
  function normalizeAudio (line 438) | async function normalizeAudio(buffer) {
  function sliceAudio (line 456) | async function sliceAudio({audioBuffer, start, end}) {
  function prepareAudio (line 477) | async function prepareAudio(audio, {trimStart = 0, trimEnd = 0} = {}) {
  function setupOffscreenDocument (line 490) | async function setupOffscreenDocument({url, reasons, justification} = {}) {
  function sendOffscreenMessage (line 514) | function sendOffscreenMessage(message) {
  function runOnce (line 537) | function runOnce(name, func) {
  function sleep (line 551) | function sleep(ms) {

FILE: src/utils/vuetify.js
  function configTheme (line 25) | async function configTheme(vuetify, {theme = ''} = {}) {
  function configVuetify (line 44) | async function configVuetify(app) {
Condensed preview — 69 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (237K chars).
[
  {
    "path": ".browserslistrc",
    "chars": 116,
    "preview": "[chrome]\nChrome >= 123\nEdge >= 123\nOpera >= 109\n\n[edge]\nEdge >= 123\n\n[firefox]\nFirefox >= 115\n\n[opera]\nOpera >= 109\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 106,
    "preview": "github: dessant\npatreon: dessant\ncustom:\n  - https://armin.dev/go/paypal\n  - https://armin.dev/go/bitcoin\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 1762,
    "preview": "---\nname: Bug report\nabout: Create a report if something isn't working as expected\n\n---\n\n<!--\nYou may experience a tempo"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 28,
    "preview": "blank_issues_enabled: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "chars": 724,
    "preview": "---\nname: Feature request\nabout: Suggest an idea for this project\n\n---\n\n<!--\nFull automation and scripting are not withi"
  },
  {
    "path": ".github/label-actions.yml",
    "chars": 941,
    "preview": "# Configuration for Label Actions - https://github.com/dessant/label-actions\n\nincomplete:\n  issues:\n    comment: >\n     "
  },
  {
    "path": ".github/pull_request_template.md",
    "chars": 102,
    "preview": "This project does not accept pull requests. Please use issues to report bugs or suggest new features.\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 2010,
    "preview": "name: CI\n\non: push\n\njobs:\n  build:\n    name: Build\n    runs-on: ubuntu-22.04\n    permissions:\n      contents: read\n    s"
  },
  {
    "path": ".github/workflows/label-actions.yml",
    "chars": 281,
    "preview": "name: 'Label Actions'\n\non:\n  issues:\n    types: [labeled, unlabeled]\n  pull_request:\n    types: [labeled, unlabeled]\n\npe"
  },
  {
    "path": ".github/workflows/lockdown.yml",
    "chars": 429,
    "preview": "name: 'Repo Lockdown'\n\non:\n  pull_request_target:\n    types: opened\n\npermissions:\n  pull-requests: write\n\njobs:\n  action"
  },
  {
    "path": ".gitignore",
    "chars": 161,
    "preview": "/.assets/\n/app/\n/artifacts/\n/dist/\n\n/secrets.json\n\n/report.json\n/report.html\n\n/web-ext-config.js\n\nnode_modules/\n/npm-deb"
  },
  {
    "path": ".nvmrc",
    "chars": 8,
    "preview": "20.14.0\n"
  },
  {
    "path": ".prettierignore",
    "chars": 18,
    "preview": "package.json\n*.md\n"
  },
  {
    "path": ".prettierrc.yml",
    "chars": 83,
    "preview": "singleQuote: true\nbracketSpacing: false\narrowParens: 'avoid'\ntrailingComma: 'none'\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 14086,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file. See [commit-and-tag-version](https://g"
  },
  {
    "path": "LICENSE",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 3360,
    "preview": "<p align=\"center\"><img width=\"128\" height=\"128\" src=\"https://i.imgur.com/uVpmR8l.png\"></p>\n<h1 align=\"center\">Buster: Ca"
  },
  {
    "path": "babel.config.js",
    "chars": 627,
    "preview": "const path = require('node:path');\n\nconst corejsVersion = require(\n  path.join(path.dirname(require.resolve('core-js')),"
  },
  {
    "path": "gulpfile.js",
    "chars": 7685,
    "preview": "const path = require('node:path');\nconst {exec} = require('node:child_process');\nconst {\n  lstatSync,\n  readdirSync,\n  r"
  },
  {
    "path": "package.json",
    "chars": 3080,
    "preview": "{\n  \"name\": \"buster\",\n  \"version\": \"3.1.0\",\n  \"author\": \"Armin Sebastian\",\n  \"license\": \"GPL-3.0-only\",\n  \"homepage\": \"h"
  },
  {
    "path": "postcss.config.js",
    "chars": 296,
    "preview": "const postcssPresetEnv = require('postcss-preset-env');\nconst cssnano = require('cssnano');\n\nmodule.exports = function ("
  },
  {
    "path": "secrets.json.example",
    "chars": 550,
    "preview": "{\n  \"witApiKeys\": {\n    \"arabic\": \"\",\n    \"bengali\": \"\",\n    \"chinese\": \"\",\n    \"dutch\": \"\",\n    \"english\": \"\",\n    \"fin"
  },
  {
    "path": "src/assets/fonts/roboto.css",
    "chars": 601,
    "preview": "@font-face {\n  font-family: 'Roboto';\n  font-style: normal;\n  font-weight: 400;\n  src: url('./files/roboto-latin-400-nor"
  },
  {
    "path": "src/assets/locales/en/messages-firefox.json",
    "chars": 121,
    "preview": "{\n  \"optionSectionTitle_client\": {\n    \"message\": \"Client App\",\n    \"description\": \"Title of the options section.\"\n  }\n}"
  },
  {
    "path": "src/assets/locales/en/messages.json",
    "chars": 16075,
    "preview": "{\n  \"extensionName\": {\n    \"message\": \"Buster: Captcha Solver for Humans\",\n    \"description\": \"Name of the extension.\"\n "
  },
  {
    "path": "src/assets/manifest/chrome.json",
    "chars": 2894,
    "preview": "{\n  \"manifest_version\": 3,\n  \"name\": \"__MSG_extensionName__\",\n  \"description\": \"__MSG_extensionDescription__\",\n  \"versio"
  },
  {
    "path": "src/assets/manifest/edge.json",
    "chars": 2894,
    "preview": "{\n  \"manifest_version\": 3,\n  \"name\": \"__MSG_extensionName__\",\n  \"description\": \"__MSG_extensionDescription__\",\n  \"versio"
  },
  {
    "path": "src/assets/manifest/firefox.json",
    "chars": 2789,
    "preview": "{\n  \"manifest_version\": 2,\n  \"name\": \"__MSG_extensionName__\",\n  \"description\": \"__MSG_extensionDescription__\",\n  \"versio"
  },
  {
    "path": "src/assets/manifest/opera.json",
    "chars": 2893,
    "preview": "{\n  \"manifest_version\": 3,\n  \"name\": \"__MSG_extensionName__\",\n  \"description\": \"__MSG_extensionDescription__\",\n  \"versio"
  },
  {
    "path": "src/background/index.html",
    "chars": 187,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"referrer\" content=\"no-referrer\" />\n  </head"
  },
  {
    "path": "src/background/main.js",
    "chars": 26904,
    "preview": "import aes from 'crypto-js/aes';\nimport sha256 from 'crypto-js/sha256';\nimport utf8 from 'crypto-js/enc-utf8';\n\nimport {"
  },
  {
    "path": "src/base/main.js",
    "chars": 13734,
    "preview": "import storage from 'storage/storage';\nimport {meanSleep, pingClientApp} from 'utils/app';\nimport {\n  getText,\n  findNod"
  },
  {
    "path": "src/base/solver-button.css",
    "chars": 2605,
    "preview": "#solver-button {\n  background-image: url('data:image/svg+xml,%3Csvg%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%"
  },
  {
    "path": "src/base/style.css",
    "chars": 1027,
    "preview": "#reset-button {\n  background-image: url('data:image/svg+xml,%3Csvg%20width%3D%2224%22%20height%3D%2224%22%20xmlns%3D%22h"
  },
  {
    "path": "src/contribute/App.vue",
    "chars": 1246,
    "preview": "<template>\n  <vn-app>\n    <vn-contribute\n      :extName=\"extName\"\n      :extSlug=\"extSlug\"\n      :notice=\"notice\"\n      "
  },
  {
    "path": "src/contribute/index.html",
    "chars": 655,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, init"
  },
  {
    "path": "src/contribute/main.js",
    "chars": 370,
    "preview": "import {createApp} from 'vue';\n\nimport {configApp, loadFonts} from 'utils/app';\nimport {configVuetify} from 'utils/vueti"
  },
  {
    "path": "src/offscreen/index.html",
    "chars": 187,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"referrer\" content=\"no-referrer\" />\n  </head"
  },
  {
    "path": "src/offscreen/main.js",
    "chars": 713,
    "preview": "import {\n  arrayBufferToBase64,\n  base64ToArrayBuffer,\n  prepareAudio\n} from 'utils/common';\n\nasync function processAudi"
  },
  {
    "path": "src/options/App.vue",
    "chars": 15410,
    "preview": "<template>\n  <vn-app v-if=\"dataLoaded\">\n    <div class=\"section\">\n      <div class=\"section-title\" v-once>\n        {{ ge"
  },
  {
    "path": "src/options/index.html",
    "chars": 655,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, init"
  },
  {
    "path": "src/options/main.js",
    "chars": 351,
    "preview": "import {createApp} from 'vue';\n\nimport {configApp, loadFonts} from 'utils/app';\nimport {configVuetify} from 'utils/vueti"
  },
  {
    "path": "src/scripts/init-setup.js",
    "chars": 374,
    "preview": "function setup() {\n  const url = new URL(browser.runtime.getURL('/src/setup/index.html'));\n  url.searchParams.set(\n    '"
  },
  {
    "path": "src/scripts/reset.js",
    "chars": 997,
    "preview": "(function () {\n  const reset = function (challengeUrl) {\n    for (const [id, client] of Object.entries(___grecaptcha_cfg"
  },
  {
    "path": "src/setup/App.vue",
    "chars": 6148,
    "preview": "<template>\n  <vn-app v-if=\"dataLoaded\">\n    <div class=\"wrap\" v-if=\"!isInstallSuccess && !isInstallError\">\n      <div cl"
  },
  {
    "path": "src/setup/index.html",
    "chars": 601,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, init"
  },
  {
    "path": "src/setup/main.js",
    "chars": 407,
    "preview": "import {createApp} from 'vue';\n\nimport {configApp, loadFonts} from 'utils/app';\nimport {configVuetify} from 'utils/vueti"
  },
  {
    "path": "src/storage/config.json",
    "chars": 393,
    "preview": "{\n  \"revisions\": {\n    \"local\": [\n      \"UoT3kGyBH\",\n      \"ONiJBs00o\",\n      \"UidMDYaYA\",\n      \"nOedd0Txqd\",\n      \"Zt"
  },
  {
    "path": "src/storage/init.js",
    "chars": 1405,
    "preview": "import {migrate} from 'wesa';\n\nimport {isStorageArea} from './storage';\n\nasync function initStorage({area = 'local', dat"
  },
  {
    "path": "src/storage/revisions/local/20221211221603_add_theme_support.js",
    "chars": 580,
    "preview": "import {getDayPrecisionEpoch} from 'utils/common';\n\nconst message = 'Add theme support';\n\nconst revision = '202212112216"
  },
  {
    "path": "src/storage/revisions/local/20221214080901_update_services.js",
    "chars": 608,
    "preview": "const message = 'Update services';\n\nconst revision = '20221214080901_update_services';\n\nasync function upgrade() {\n  con"
  },
  {
    "path": "src/storage/revisions/local/20240514170322_add_appversion.js",
    "chars": 280,
    "preview": "const message = 'Add appVersion';\n\nconst revision = '20240514170322_add_appversion';\n\nasync function upgrade() {\n  const"
  },
  {
    "path": "src/storage/revisions/local/DlgF14Chrh.js",
    "chars": 422,
    "preview": "const message = 'Revision description';\n\nconst revision = 'DlgF14Chrh';\n\nasync function upgrade() {\n  const changes = {}"
  },
  {
    "path": "src/storage/revisions/local/Lj3MYlSr4L.js",
    "chars": 284,
    "preview": "const message = 'Add navigateWithKeyboard';\n\nconst revision = 'Lj3MYlSr4L';\n\nasync function upgrade() {\n  const changes "
  },
  {
    "path": "src/storage/revisions/local/ONiJBs00o.js",
    "chars": 376,
    "preview": "const message = 'Add IBM Watson Speech to Text API';\n\nconst revision = 'ONiJBs00o';\n\nasync function upgrade() {\n  const "
  },
  {
    "path": "src/storage/revisions/local/UidMDYaYA.js",
    "chars": 426,
    "preview": "const message = 'Add Microsoft Azure Speech to Text API';\n\nconst revision = 'UidMDYaYA';\n\nasync function upgrade() {\n  c"
  },
  {
    "path": "src/storage/revisions/local/UoT3kGyBH.js",
    "chars": 485,
    "preview": "const message = 'Initial version';\n\nconst revision = 'UoT3kGyBH';\n\nasync function upgrade() {\n  const changes = {\n    sp"
  },
  {
    "path": "src/storage/revisions/local/X3djS8vZC.js",
    "chars": 287,
    "preview": "const message = 'Add autoUpdateClientApp option';\n\nconst revision = 'X3djS8vZC';\n\nasync function upgrade() {\n  const cha"
  },
  {
    "path": "src/storage/revisions/local/ZtLMLoh1ag.js",
    "chars": 290,
    "preview": "const message = 'Add loadEnglishChallenge option';\n\nconst revision = 'ZtLMLoh1ag';\n\nasync function upgrade() {\n  const c"
  },
  {
    "path": "src/storage/revisions/local/nOedd0Txqd.js",
    "chars": 337,
    "preview": "const message = 'Add Wit Speech API and tryEnglishSpeechModel option';\n\nconst revision = 'nOedd0Txqd';\n\nasync function u"
  },
  {
    "path": "src/storage/revisions/local/t335iRDhZ8.js",
    "chars": 285,
    "preview": "const message = 'Add simulateUserInput option';\n\nconst revision = 't335iRDhZ8';\n\nasync function upgrade() {\n  const chan"
  },
  {
    "path": "src/storage/revisions/session/20240514122825_initial_version.js",
    "chars": 288,
    "preview": "const message = 'Initial version';\n\nconst revision = '20240514122825_initial_version';\n\nasync function upgrade() {\n  con"
  },
  {
    "path": "src/storage/storage.js",
    "chars": 1869,
    "preview": "import {storageRevisions} from 'utils/config';\n\nasync function isStorageArea({area = 'local'} = {}) {\n  try {\n    await "
  },
  {
    "path": "src/utils/app.js",
    "chars": 11022,
    "preview": "import {v4 as uuidv4} from 'uuid';\n\nimport storage from 'storage/storage';\nimport {\n  getText,\n  insertCSS,\n  executeScr"
  },
  {
    "path": "src/utils/common.js",
    "chars": 12497,
    "preview": "import Bowser from 'bowser';\nimport audioBufferToWav from 'audiobuffer-to-wav';\n\nimport storage from 'storage/storage';\n"
  },
  {
    "path": "src/utils/config.js",
    "chars": 470,
    "preview": "const targetEnv = process.env.TARGET_ENV;\n\nconst enableContributions = process.env.ENABLE_CONTRIBUTIONS === 'true';\n\ncon"
  },
  {
    "path": "src/utils/data.js",
    "chars": 11367,
    "preview": "const optionKeys = [\n  'speechService',\n  'googleSpeechApiKey',\n  'ibmSpeechApiUrl',\n  'ibmSpeechApiKey',\n  'microsoftSp"
  },
  {
    "path": "src/utils/vuetify.js",
    "chars": 1430,
    "preview": "import {createVuetify} from 'vuetify';\n\nimport {getAppTheme, addThemeListener} from 'utils/app';\n\nconst LightTheme = {\n "
  },
  {
    "path": "webpack.config.js",
    "chars": 4210,
    "preview": "const path = require('node:path');\nconst {lstatSync, readdirSync} = require('node:fs');\n\nconst webpack = require('webpac"
  }
]

About this extraction

This page contains the full source code of the dessant/buster GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 69 files (216.8 KB), approximately 60.2k tokens, and a symbol index with 127 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!