[
  {
    "path": ".github/FUNDING.yml",
    "content": "github: samuelhwilliams\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\ncustom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n**Eel version**\nPlease state the version of Eel you're using.\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**System Information**\n - OS: [e.g. Windows 10 x64, Linux Ubuntu, macOS 12]\n - Browser: [e.g. Chrome 108.0.5359.99 (Official Build) (64-bit), Safari 16, Firefox 107.0.1]\n - Python Distribution: [e.g. Python.org 3.9, Anaconda3 2021.11 3.9, ActivePython 3.9]\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/help-me.md",
    "content": "---\nname: Help me\nabout: Get help with Eel\ntitle: ''\nlabels: help wanted\nassignees: ''\n\n---\n\n**Describe the problem**\nA clear and concise description of what you're trying to accomplish, and where you're having difficulty.\n\n**Code snippet(s)**\nHere is some code that can be easily used to reproduce the problem or understand what I need help with.\n\n- [ ] I know that if I don't provide sample code that allows someone to quickly step into my shoes, I may not get the help I want or my issue may be closed.\n\n```python\nimport eel\n\n...\n```\n\n```html\n<html>\n   ...\n</html>\n```\n\n**Desktop (please complete the following information):**\n - OS: [e.g. iOS]\n - Browser [e.g. chrome, safari]\n - Version [e.g. 22]\n\n**Smartphone (please complete the following information):**\n - Device: [e.g. iPhone6]\n - OS: [e.g. iOS8.1]\n - Browser [e.g. stock browser, safari]\n - Version [e.g. 22]\n"
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "content": "name: \"CodeQL\"\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    # The branches below must be a subset of the branches above\n    branches: [main]\n  schedule:\n    - cron: '0 11 * * 0'\n\njobs:\n  analyse:\n    name: Analyse\n    runs-on: ubuntu-latest\n\n    steps:\n    - name: Checkout repository\n      uses: actions/checkout@v2\n      with:\n        # We must fetch at least the immediate parents so that if this is\n        # a pull request then we can checkout the head.\n        fetch-depth: 2\n\n    # If this run was triggered by a pull request event, then checkout\n    # the head of the pull request instead of the merge commit.\n    - run: git checkout HEAD^2\n      if: ${{ github.event_name == 'pull_request' }}\n\n    # Initializes the CodeQL tools for scanning.\n    - name: Initialize CodeQL\n      uses: github/codeql-action/init@v1\n      # Override language selection by uncommenting this and choosing your languages\n      with:\n        languages: javascript, python\n\n    - name: Perform CodeQL Analysis\n      uses: github/codeql-action/analyze@v1\n"
  },
  {
    "path": ".github/workflows/main.yml",
    "content": "name: Publish\n\non:\n  release:\n    types: [published]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@master\n      - name: Setup Python\n        uses: actions/setup-python@master\n        with:\n          python-version: 3.x\n          architecture: x64\n      - name: Install setuptools\n        run: pip install setuptools==76.1.0\n      - name: Build a source distribution\n        run: python setup.py sdist\n      - name: Publish to prod PyPI\n        uses: pypa/gh-action-pypi-publish@4f4304928fc886cd021893f6defb1bd53d0a1e5a\n        with:\n          user: __token__\n          password: ${{ secrets.pypi_token }}\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Test Eel\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    # The branches below must be a subset of the branches above\n    branches: [main]\n  workflow_dispatch:\n\njobs:\n  test:\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [ubuntu-24.04, windows-latest, macos-latest]\n        python-version: [3.7, 3.8, 3.9, \"3.10\", \"3.11\", \"3.12\"]\n        exclude:\n          - os: macos-latest\n            python-version: 3.7\n          - os: ubuntu-24.04\n            python-version: 3.7\n\n    runs-on: ${{ matrix.os }}\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v2\n      - name: Setup python\n        uses: actions/setup-python@v2\n        with:\n          python-version: ${{ matrix.python-version }}\n      - name: Setup test execution environment.\n        run: pip3 install -r requirements-meta.txt\n      - name: Run tox tests\n        run: tox -- --durations=0 --timeout=240\n\n  typecheck:\n    strategy:\n      matrix:\n        os: [windows-latest]\n\n    runs-on: ${{ matrix.os }}\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v2\n      - name: Setup python\n        uses: actions/setup-python@v2\n        with:\n          python-version: \"3.x\"\n      - name: Setup test execution environment.\n        run: pip3 install -r requirements-meta.txt\n      - name: Run tox tests\n        run: tox -e typecheck\n"
  },
  {
    "path": ".gitignore",
    "content": "__pycache__\ndist\nbuild\nDrivers\nEel.egg-info\n.tmp\n.DS_Store\n*.pyc\n*.swp\nvenv/\n.tox\n"
  },
  {
    "path": ".python-version",
    "content": "3.10\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: python\ncache: pip\npython:\n    - 2.7\n    - 3.6\nmatrix:\n    allow_failures:\n        - python: 2.7\ninstall:\n    #- pip install -r requirements.txt\n    - pip install flake8  # pytest  # add another testing frameworks later\nbefore_script:\n    # stop the build if there are Python syntax errors or undefined names\n    - flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics\n    # exit-zero treats all errors as warnings.  The GitHub editor is 127 chars wide\n    - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics\nscript:\n    - true  # pytest --capture=sys  # add other tests here\nnotifications:\n    on_success: change\n    on_failure: change  # `always` will be the setting once code changes slow down\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change log\n\n### 0.18.2\n\n* Switch from using `pkg_resources` to `importlib.resources`: https://github.com/python-eel/Eel/pull/766\n\n### 0.18.1\n\n* Fix: Include `typing_extensions` in install requirements.\n\n### 0.18.0\n* Added support for MS Internet Explorer in #744.\n* Added supported for app_mode in the Edge browser in #744.\n* Improved type annotations in #683.\n\n### 0.17.0\n* Adds support for Python 3.11 and Python 3.12\n\n### v0.16.0\n* Drop support for Python versions below 3.7\n\n### v0.15.3\n* Comprehensive type hints implement by @thatfloflo in https://github.com/python-eel/Eel/pull/577.\n\n### v0.15.2\n* Adds `register_eel_routes` to handle applying Eel routes to non-Bottle custom app instances.\n\n### v0.15.1\n* Bump bottle dependency from 0.12.13 to 0.12.20 to address the critical CVE-2022-31799 and moderate CVE-2020-28473.\n\n### v0.15.0\n* Add `shutdown_delay` as a `start()` function parameter ([#529](https://github.com/python-eel/Eel/pull/529))\n\n### v0.14.0\n* Change JS function name parsing to use PyParsing rather than regex, courtesy @KyleKing.\n\n### v0.13.2\n* Add `default_path` start arg to define a default file to retrieve when hitting the root URL.\n\n### v0.13.1\n* Shut down the Eel server less aggressively when websockets get closed (#337)\n\n## v0.13.0\n* Drop support for Python versions below 3.6\n* Add `jinja2` as an extra for pip installation, e.g. `pip install eel[jinja2]`.\n* Bump dependencies in examples to dismiss github security notices. We probably want to set up a policy to ignore example dependencies as they shouldn't be considered a source of vulnerabilities.\n* Disable edge on non-Windows platforms until we implement proper support.\n\n### v0.12.4\n* Return greenlet task from `spawn()` ([#300](https://github.com/samuelhwilliams/Eel/pull/300))\n* Set JS mimetype to reduce errors on Windows platform ([#289](https://github.com/samuelhwilliams/Eel/pull/289))\n\n### v0.12.3\n* Search for Chromium on macOS.\n\n### v0.12.2\n* Fix a bug that prevents using middleware via a custom Bottle.\n\n### v0.12.1\n* Check that Chrome path is a file that exists on Windows before blindly returning it.\n\n## v0.12.0\n* Allow users to override the amount of time Python will wait for Javascript functions running via Eel to run before bailing and returning None.\n\n### v0.11.1\n* Fix the implementation of #203, allowing users to pass their own bottle instances into Eel.\n\n## v0.11.0\n* Added support for `app` parameter to `eel.start`, which will override the bottle app instance used to run eel. This\nallows developers to apply any middleware they wish to before handing over to eel.\n* Disable page caching by default via new `disable_cache` parameter to `eel.start`.\n* Add support for listening on all network interfaces via new `all_interfaces` parameter to `eel.start`.\n* Support for Microsoft Edge\n\n### v0.10.4\n* Fix PyPi project description.\n\n### v0.10.3\n* Fix a bug that prevented using Eel without Jinja templating.\n\n### v0.10.2\n* Only render templates from within the declared jinja template directory.\n\n### v0.10.1\n* Avoid name collisions when using Electron, so jQuery etc work normally\n\n## v0.10.0\n* Corrective version bump after new feature included in 0.9.13\n* Fix a bug with example 06 for Jinja templating; the `templates` kwarg to `eel.start` takes a filepath, not a bool.\n\n### v0.9.13\n* Add support for Jinja templating.\n\n### Earlier\n* No changelog notes for earlier versions.\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 Chris Knott\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include README.md"
  },
  {
    "path": "README-developers.md",
    "content": "# Eel Developers\n\n## Setting up your environment\n\nIn order to start developing with Eel you'll need to checkout the code, set up a development and testing environment, and check that everything is in order.\n\n### Clone the repository\n```bash\ngit clone git@github.com:python-eel/Eel.git\n```\n\n### (Recommended) Create a virtual environment\nIt's recommended that you use virtual environments for this project. Your process for setting up a virutal environment will vary depending on OS and tool of choice, but might look something like this:\n\n```bash\npython3 -m venv venv\nsource venv/bin/activate\n```\n\n**Note**: `venv` is listed in the `.gitignore` file so it's the recommended virtual environment name\n    \n\n### Install project requirements\n\n```bash\npip3 install -r requirements.txt        # eel's 'prod' requirements\npip3 install -r requirements-test.txt   # pytest and selenium\npip3 install -r requirements-meta.txt   # tox \n```\n\n### (Recommended) Run Automated Tests\nTox is configured to run tests against each major version we support (3.7+). In order to run Tox as configured, you will need to install multiple versions of Python. See the pinned minor versions in `.python-version` for recommendations.\n\n#### Tox Setup\nOur Tox configuration requires [Chrome](https://www.google.com/chrome) and [ChromeDriver](https://chromedriver.chromium.org/home). See each of those respective project pages for more information on setting each up.\n\n**Note**: Pay attention to the version of Chrome that is installed on your OS because you need to select the compatible ChromeDriver version.\n\n#### Running Tests\n\nTo test Eel against a specific version of Python you have installed, e.g. Python 3.7 in this case, run:\n\n```bash\ntox -e py36\n```\n\nTo test Eel against all supported versions, run the following:\n\n```bash\ntox\n```\n"
  },
  {
    "path": "README.md",
    "content": "# Eel\n\n> [!CAUTION]\n> This project is effectively unmaintained. It has not received regular update in a number of years, and there are no plans by active maintainers for this to change. Please treat this project in that light and use it with careful consideration towards how you will secure and maintain anything you build using it.\n\n[![PyPI version](https://img.shields.io/pypi/v/Eel?style=for-the-badge)](https://pypi.org/project/Eel/)\n[![PyPi Downloads](https://img.shields.io/pypi/dm/Eel?style=for-the-badge)](https://pypistats.org/packages/eel)\n![Python](https://img.shields.io/pypi/pyversions/Eel?style=for-the-badge)\n[![License](https://img.shields.io/pypi/l/Eel.svg?style=for-the-badge)](https://pypi.org/project/Eel/)\n\nEel is a little Python library for making simple Electron-like offline HTML/JS GUI apps, with full access to Python capabilities and libraries.\n\n> **Eel hosts a local webserver, then lets you annotate functions in Python so that they can be called from Javascript, and vice versa.**\n\nEel is designed to take the hassle out of writing short and simple GUI applications. If you are familiar with Python and web development, probably just jump to [this example](https://github.com/ChrisKnott/Eel/tree/master/examples/04%20-%20file_access) which picks random file names out of the given folder (something that is impossible from a browser).\n\n<p align=\"center\"><img src=\"https://raw.githubusercontent.com/samuelhwilliams/Eel/master/examples/04%20-%20file_access/Screenshot.png\" ></p>\n\n<!-- TOC -->\n\n- [Eel](#eel)\n  - [Intro](#intro)\n  - [Install](#install)\n  - [Usage](#usage)\n    - [Directory Structure](#directory-structure)\n    - [Starting the app](#starting-the-app)\n    - [App options](#app-options)\n      - [Chrome/Chromium flags](#chromechromium-flags)\n    - [Exposing functions](#exposing-functions)\n    - [Eello, World!](#eello-world)\n    - [Return values](#return-values)\n      - [Callbacks](#callbacks)\n      - [Synchronous returns](#synchronous-returns)\n  - [Asynchronous Python](#asynchronous-python)\n  - [Building distributable binary with PyInstaller](#building-distributable-binary-with-pyinstaller)\n  - [Microsoft Edge](#microsoft-edge)\n\n<!-- /TOC -->\n\n## Intro\n\nThere are several options for making GUI apps in Python, but if you want to use HTML/JS (in order to use jQueryUI or Bootstrap, for example) then you generally have to write a lot of boilerplate code to communicate from the Client (Javascript) side to the Server (Python) side.\n\nThe closest Python equivalent to Electron (to my knowledge) is [cefpython](https://github.com/cztomczak/cefpython). It is a bit heavy weight for what I wanted.\n\nEel is not as fully-fledged as Electron or cefpython - it is probably not suitable for making full blown applications like Atom - but it is very suitable for making the GUI equivalent of little utility scripts that you use internally in your team.\n\nFor some reason many of the best-in-class number crunching and maths libraries are in Python (Tensorflow, Numpy, Scipy etc) but many of the best visualization libraries are in Javascript (D3, THREE.js etc). Hopefully Eel makes it easy to combine these into simple utility apps for assisting your development.\n\nJoin Eel's users and maintainers on [Discord](https://discord.com/invite/3nqXPFX), if you like.\n\n## Install\n\nInstall from pypi with `pip`:\n\n```shell\npip install eel\n```\n\nTo include support for HTML templating, currently using [Jinja2](https://pypi.org/project/Jinja2/#description):\n\n```shell\npip install eel[jinja2]\n```\n\n## Usage\n\n### Directory Structure\n\nAn Eel application will be split into a frontend consisting of various web-technology files (.html, .js, .css) and a backend consisting of various Python scripts.\n\nAll the frontend files should be put in a single directory (they can be further divided into folders inside this if necessary).\n\n```\nmy_python_script.py     <-- Python scripts\nother_python_module.py\nstatic_web_folder/      <-- Web folder\n  main_page.html\n  css/\n    style.css\n  img/\n    logo.png\n```\n\n### Starting the app\n\nSuppose you put all the frontend files in a directory called `web`, including your start page `main.html`, then the app is started like this;\n\n```python\nimport eel\neel.init('web')\neel.start('main.html')\n```\n\nThis will start a webserver on the default settings (http://localhost:8000) and open a browser to http://localhost:8000/main.html.\n\nIf Chrome or Chromium is installed then by default it will open in that in App Mode (with the `--app` cmdline flag), regardless of what the OS's default browser is set to (it is possible to override this behaviour).\n\n### App options\n\nAdditional options can be passed to `eel.start()` as keyword arguments.\n\nSome of the options include the mode the app is in (e.g. 'chrome'), the port the app runs on, the host name of the app, and adding additional command line flags.\n\nAs of Eel v0.12.0, the following options are available to `start()`:\n - **mode**, a string specifying what browser to use (e.g. `'chrome'`, `'electron'`, `'edge'`,`'msie'`, `'custom'`). Can also be `None` or `False` to not open a window. *Default: `'chrome'`*\n - **host**, a string specifying what hostname to use for the Bottle server. *Default: `'localhost'`)*\n - **port**, an int specifying what port to use for the Bottle server. Use `0` for port to be picked automatically. *Default: `8000`*.\n - **block**, a bool saying whether or not the call to `start()` should block the calling thread. *Default: `True`*\n - **jinja_templates**, a string specifying a folder to use for Jinja2 templates, e.g. `my_templates`. *Default:  `None`*\n - **cmdline_args**, a list of strings to pass to the command to start the browser. For example, we might add extra flags for Chrome; ```eel.start('main.html', mode='chrome-app', port=8080, cmdline_args=['--start-fullscreen', '--browser-startup-dialog'])```. *Default: `[]`*\n - **size**, a tuple of ints specifying the (width, height) of the main window in pixels *Default: `None`*\n - **position**, a tuple of ints specifying the (left, top) of the main window in pixels *Default: `None`*\n - **geometry**, a dictionary specifying the size and position for all windows. The keys should be the relative path of the page, and the values should be a dictionary of the form `{'size': (200, 100), 'position': (300, 50)}`. *Default: {}*\n - **close_callback**, a lambda or function that is called when a websocket to a window closes (i.e. when the user closes the window). It should take two arguments; a string which is the relative path of the page that just closed, and a list of other websockets that are still open. *Default: `None`*\n - **app**, an instance of Bottle which will be used rather than creating a fresh one. This can be used to install middleware on the instance before starting eel, e.g. for session management, authentication, etc. If your `app` is not a Bottle instance, you will need to call `eel.register_eel_routes(app)` on your custom app instance.\n - **shutdown_delay**, timer configurable for Eel's shutdown detection mechanism, whereby when any websocket closes, it waits `shutdown_delay` seconds, and then checks if there are now any websocket connections. If not, then Eel closes. In case the user has closed the browser and wants to exit the program. By default, the value of **shutdown_delay** is `1.0` second\n\n\n\n### Exposing functions\n\nIn addition to the files in the frontend folder, a Javascript library will be served at `/eel.js`. You should include this in any pages:\n\n```html\n<script type=\"text/javascript\" src=\"/eel.js\"></script>\n```\n\nIncluding this library creates an `eel` object which can be used to communicate with the Python side.\n\nAny functions in the Python code which are decorated with `@eel.expose` like this...\n\n```python\n@eel.expose\ndef my_python_function(a, b):\n    print(a, b, a + b)\n```\n\n...will appear as methods on the `eel` object on the Javascript side, like this...\n\n```javascript\nconsole.log(\"Calling Python...\");\neel.my_python_function(1, 2); // This calls the Python function that was decorated\n```\n\nSimilarly, any Javascript functions which are exposed like this...\n\n```javascript\neel.expose(my_javascript_function);\nfunction my_javascript_function(a, b, c, d) {\n  if (a < b) {\n    console.log(c * d);\n  }\n}\n```\n\ncan be called from the Python side like this...\n\n```python\nprint('Calling Javascript...')\neel.my_javascript_function(1, 2, 3, 4)  # This calls the Javascript function\n```\n\nThe exposed name can also be overridden by passing in a second argument. If your app minifies JavaScript during builds, this may be necessary to ensure that functions can be resolved on the Python side:\n\n```javascript\neel.expose(someFunction, \"my_javascript_function\");\n```\n\nWhen passing complex objects as arguments, bear in mind that internally they are converted to JSON and sent down a websocket (a process that potentially loses information).\n\n### Eello, World!\n\n> See full example in: [examples/01 - hello_world](https://github.com/ChrisKnott/Eel/tree/master/examples/01%20-%20hello_world)\n\nPutting this together into a **Hello, World!** example, we have a short HTML page, `web/hello.html`:\n\n```html\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>Hello, World!</title>\n\n    <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->\n    <script type=\"text/javascript\" src=\"/eel.js\"></script>\n    <script type=\"text/javascript\">\n      eel.expose(say_hello_js); // Expose this function to Python\n      function say_hello_js(x) {\n        console.log(\"Hello from \" + x);\n      }\n\n      say_hello_js(\"Javascript World!\");\n      eel.say_hello_py(\"Javascript World!\"); // Call a Python function\n    </script>\n  </head>\n\n  <body>\n    Hello, World!\n  </body>\n</html>\n```\n\nand a short Python script `hello.py`:\n\n```python\nimport eel\n\n# Set web files folder and optionally specify which file types to check for eel.expose()\n#   *Default allowed_extensions are: ['.js', '.html', '.txt', '.htm', '.xhtml']\neel.init('web', allowed_extensions=['.js', '.html'])\n\n@eel.expose                         # Expose this function to Javascript\ndef say_hello_py(x):\n    print('Hello from %s' % x)\n\nsay_hello_py('Python World!')\neel.say_hello_js('Python World!')   # Call a Javascript function\n\neel.start('hello.html')             # Start (this blocks and enters loop)\n```\n\nIf we run the Python script (`python hello.py`), then a browser window will open displaying `hello.html`, and we will see...\n\n```\nHello from Python World!\nHello from Javascript World!\n```\n\n...in the terminal, and...\n\n```\nHello from Javascript World!\nHello from Python World!\n```\n\n...in the browser console (press F12 to open).\n\nYou will notice that in the Python code, the Javascript function is called before the browser window is even started - any early calls like this are queued up and then sent once the websocket has been established.\n\n### Return values\n\nWhile we want to think of our code as comprising a single application, the Python interpreter and the browser window run in separate processes. This can make communicating back and forth between them a bit of a mess, especially if we always had to explicitly _send_ values from one side to the other.\n\nEel supports two ways of retrieving _return values_ from the other side of the app, which helps keep the code concise.\n\nTo prevent hanging forever on the Python side, a timeout has been put in place for trying to retrieve values from\nthe JavaScript side, which defaults to 10000 milliseconds (10 seconds). This can be changed with the `_js_result_timeout` parameter to `eel.init`. There is no corresponding timeout on the JavaScript side.\n\n#### Callbacks\n\nWhen you call an exposed function, you can immediately pass a callback function afterwards. This callback will automatically be called asynchronously with the return value when the function has finished executing on the other side.\n\nFor example, if we have the following function defined and exposed in Javascript:\n\n```javascript\neel.expose(js_random);\nfunction js_random() {\n  return Math.random();\n}\n```\n\nThen in Python we can retrieve random values from the Javascript side like so:\n\n```python\ndef print_num(n):\n    print('Got this from Javascript:', n)\n\n# Call Javascript function, and pass explicit callback function\neel.js_random()(print_num)\n\n# Do the same with an inline lambda as callback\neel.js_random()(lambda n: print('Got this from Javascript:', n))\n```\n\n(It works exactly the same the other way around).\n\n#### Synchronous returns\n\nIn most situations, the calls to the other side are to quickly retrieve some piece of data, such as the state of a widget or contents of an input field. In these cases it is more convenient to just synchronously wait a few milliseconds then continue with your code, rather than breaking the whole thing up into callbacks.\n\nTo synchronously retrieve the return value, simply pass nothing to the second set of brackets. So in Python we would write:\n\n```python\nn = eel.js_random()()  # This immediately returns the value\nprint('Got this from Javascript:', n)\n```\n\nYou can only perform synchronous returns after the browser window has started (after calling `eel.start()`), otherwise obviously the call will hang.\n\nIn Javascript, the language doesn't allow us to block while we wait for a callback, except by using `await` from inside an `async` function. So the equivalent code from the Javascript side would be:\n\n```javascript\nasync function run() {\n  // Inside a function marked 'async' we can use the 'await' keyword.\n\n  let n = await eel.py_random()(); // Must prefix call with 'await', otherwise it's the same syntax\n  console.log(\"Got this from Python: \" + n);\n}\n\nrun();\n```\n\n## Asynchronous Python\n\nEel is built on Bottle and Gevent, which provide an asynchronous event loop similar to Javascript. A lot of Python's standard library implicitly assumes there is a single execution thread - to deal with this, Gevent can \"[monkey patch](https://en.wikipedia.org/wiki/Monkey_patch)\" many of the standard modules such as `time`. ~~This monkey patching is done automatically when you call `import eel`~~. If you need monkey patching you should `import gevent.monkey` and call `gevent.monkey.patch_all()` _before_ you `import eel`. Monkey patching can interfere with things like debuggers so should be avoided unless necessary.\n\nFor most cases you should be fine by avoiding using `time.sleep()` and instead using the versions provided by `gevent`. For convenience, the two most commonly needed gevent methods, `sleep()` and `spawn()` are provided directly from Eel (to save importing `time` and/or `gevent` as well).\n\nIn this example...\n\n```python\nimport eel\neel.init('web')\n\ndef my_other_thread():\n    while True:\n        print(\"I'm a thread\")\n        eel.sleep(1.0)                  # Use eel.sleep(), not time.sleep()\n\neel.spawn(my_other_thread)\n\neel.start('main.html', block=False)     # Don't block on this call\n\nwhile True:\n    print(\"I'm a main loop\")\n    eel.sleep(1.0)                      # Use eel.sleep(), not time.sleep()\n```\n\n...we would then have three \"threads\" (greenlets) running;\n\n1. Eel's internal thread for serving the web folder\n2. The `my_other_thread` method, repeatedly printing **\"I'm a thread\"**\n3. The main Python thread, which would be stuck in the final `while` loop, repeatedly printing **\"I'm a main loop\"**\n\n## Building distributable binary with PyInstaller\n\nIf you want to package your app into a program that can be run on a computer without a Python interpreter installed, you should use **PyInstaller**.\n\n1. Configure a virtualenv with desired Python version and minimum necessary Python packages\n2. Install PyInstaller `pip install PyInstaller`\n3. In your app's folder, run `python -m eel [your_main_script] [your_web_folder]` (for example, you might run `python -m eel hello.py web`)\n4. This will create a new folder `dist/`\n5. Valid PyInstaller flags can be passed through, such as excluding modules with the flag: `--exclude module_name`. For example, you might run `python -m eel file_access.py web --exclude win32com --exclude numpy --exclude cryptography`\n6. When happy that your app is working correctly, add `--onefile --noconsole` flags to build a single executable file\n\nConsult the [documentation for PyInstaller](http://PyInstaller.readthedocs.io/en/stable/) for more options.\n\n## Microsoft Edge\n\nFor Windows 10 users, Microsoft Edge (`eel.start(.., mode='edge')`) is installed by default and a useful fallback if a preferred browser is not installed. See the examples:\n\n- A Hello World example using Microsoft Edge: [examples/01 - hello_world-Edge/](https://github.com/ChrisKnott/Eel/tree/master/examples/01%20-%20hello_world-Edge)\n- Example implementing browser-fallbacks: [examples/07 - CreateReactApp/eel_CRA.py](https://github.com/ChrisKnott/Eel/tree/master/examples/07%20-%20CreateReactApp/eel_CRA.py)\n"
  },
  {
    "path": "eel/__init__.py",
    "content": "from __future__ import annotations\nfrom builtins import range\nimport traceback\nfrom io import open\nfrom typing import Union, Any, Dict, List, Set, Tuple, Optional, Callable\nfrom typing_extensions import Literal\nfrom eel.types import OptionsDictT, WebSocketT\nimport gevent as gvt\nimport json as jsn\nimport bottle as btl\ntry:\n    import bottle_websocket as wbs\nexcept ImportError:\n    import bottle.ext.websocket as wbs\nimport re as rgx\nimport os\nimport eel.browsers as brw\nimport pyparsing as pp\nimport random as rnd\nimport sys\nimport importlib_resources\nimport socket\nimport mimetypes\n\n\nmimetypes.add_type('application/javascript', '.js')\n\n# https://setuptools.pypa.io/en/latest/pkg_resources.html\n#     Use of pkg_resources is deprecated in favor of importlib.resources\n# Migration guide: https://importlib-resources.readthedocs.io/en/latest/migration.html\n_eel_js_reference = importlib_resources.files('eel') / 'eel.js'\nwith importlib_resources.as_file(_eel_js_reference) as _eel_js_path:\n    _eel_js: str = _eel_js_path.read_text(encoding='utf-8')\n\n_websockets: List[Tuple[Any, WebSocketT]] = []\n_call_return_values: Dict[Any, Any] = {}\n_call_return_callbacks: Dict[float, Tuple[Callable[..., Any], Optional[Callable[..., Any]]]] = {}\n_call_number: int = 0\n_exposed_functions: Dict[Any, Any] = {}\n_js_functions: List[Any] = []\n_mock_queue: List[Any] = []\n_mock_queue_done: Set[Any] = set()\n_shutdown: Optional[gvt.Greenlet] = None    # Later assigned as global by _websocket_close()\nroot_path: str                              # Later assigned as global by init()\n\n# The maximum time (in milliseconds) that Python will try to retrieve a return value for functions executing in JS\n# Can be overridden through `eel.init` with the kwarg `js_result_timeout` (default: 10000)\n_js_result_timeout: int = 10000\n\n# Attribute holding the start args from calls to eel.start()\n_start_args: OptionsDictT = {}\n\n# == Temporary (suppressible) error message to inform users of breaking API change for v1.0.0 ===\napi_error_message: str = '''\n----------------------------------------------------------------------------------\n  'options' argument deprecated in v1.0.0, see https://github.com/ChrisKnott/Eel\n  To suppress this error, add 'suppress_error=True' to start() call.\n  This option will be removed in future versions\n----------------------------------------------------------------------------------\n'''\n# ===============================================================================================\n\n\n# Public functions\n\n\ndef expose(name_or_function: Optional[Callable[..., Any]] = None) -> Callable[..., Any]:\n    '''Decorator to expose Python callables via Eel's JavaScript API.\n\n    When an exposed function is called, a callback function can be passed\n    immediately afterwards. This callback will be called asynchronously with\n    the return value (possibly `None`) when the Python function has finished\n    executing.\n\n    Blocking calls to the exposed function from the JavaScript side are only\n    possible using the :code:`await` keyword inside an :code:`async function`.\n    These still have to make a call to the response, i.e.\n    :code:`await eel.py_random()();` inside an :code:`async function` will work,\n    but just :code:`await eel.py_random();` will not.\n\n    :Example:\n\n    In Python do:\n\n    .. code-block:: python\n\n        @expose\n        def say_hello_py(name: str = 'You') -> None:\n            print(f'{name} said hello from the JavaScript world!')\n\n    In JavaScript do:\n\n    .. code-block:: javascript\n\n        eel.say_hello_py('Alice')();\n\n    Expected output on the Python console::\n\n        Alice said hello from the JavaScript world!\n\n    '''\n    # Deal with '@eel.expose()' - treat as '@eel.expose'\n    if name_or_function is None:\n        return expose\n\n    if isinstance(name_or_function, str):   # Called as '@eel.expose(\"my_name\")'\n        name = name_or_function\n\n        def decorator(function: Callable[..., Any]) -> Any:\n            _expose(name, function)\n            return function\n        return decorator\n    else:\n        function = name_or_function\n        _expose(function.__name__, function)\n        return function\n\n\n# PyParsing grammar for parsing exposed functions in JavaScript code\n# Examples: `eel.expose(w, \"func_name\")`, `eel.expose(func_name)`, `eel.expose((function (e){}), \"func_name\")`\nEXPOSED_JS_FUNCTIONS: pp.ZeroOrMore = pp.ZeroOrMore(\n    pp.Suppress(\n        pp.SkipTo(pp.Literal('eel.expose('))\n        + pp.Literal('eel.expose(')\n        + pp.Optional(\n            pp.Or([pp.nestedExpr(), pp.Word(pp.printables, excludeChars=',')]) + pp.Literal(',')\n        )\n    )\n    + pp.Suppress(pp.Regex(r'[\"\\']?'))\n    + pp.Word(pp.printables, excludeChars='\"\\')')\n    + pp.Suppress(pp.Regex(r'[\"\\']?\\s*\\)')),\n)\n\n\ndef init(\n        path: str,\n        allowed_extensions: List[str] = ['.js', '.html', '.txt', '.htm', '.xhtml', '.vue'],\n        js_result_timeout: int = 10000) -> None:\n    '''Initialise Eel.\n\n    This function should be called before :func:`start()` to initialise the\n    parameters for the web interface, such as the path to the files to be\n    served.\n\n    :param path: Sets the path on the filesystem where files to be served to\n        the browser are located, e.g. :file:`web`.\n    :param allowed_extensions: A list of filename extensions which will be\n        parsed for exposed eel functions which should be callable from python.\n        Files with extensions not in *allowed_extensions* will still be served,\n        but any JavaScript functions, even if marked as exposed, will not be\n        accessible from python.\n        *Default:* :code:`['.js', '.html', '.txt', '.htm', '.xhtml', '.vue']`.\n    :param js_result_timeout: How long Eel should be waiting to register the\n        results from a call to Eel's JavaScript API before before timing out.\n        *Default:* :code:`10000` milliseconds.\n    '''\n    global root_path, _js_functions, _js_result_timeout\n    root_path = _get_real_path(path)\n\n    js_functions = set()\n    for root, _, files in os.walk(root_path):\n        for name in files:\n            if not any(name.endswith(ext) for ext in allowed_extensions):\n                continue\n\n            try:\n                with open(os.path.join(root, name), encoding='utf-8') as file:\n                    contents = file.read()\n                    expose_calls = set()\n                    matches = EXPOSED_JS_FUNCTIONS.parseString(contents).asList()\n                    for expose_call in matches:\n                        # Verify that function name is valid\n                        msg = \"eel.expose() call contains '(' or '='\"\n                        assert rgx.findall(r'[\\(=]', expose_call) == [], msg\n                        expose_calls.add(expose_call)\n                    js_functions.update(expose_calls)\n            except UnicodeDecodeError:\n                pass    # Malformed file probably\n\n    _js_functions = list(js_functions)\n    for js_function in _js_functions:\n        _mock_js_function(js_function)\n\n    _js_result_timeout = js_result_timeout\n\n\ndef start(\n        *start_urls: str,\n        mode: Optional[Union[str, Literal[False]]] = 'chrome',\n        host: str = 'localhost',\n        port: int = 8000,\n        block: bool = True,\n        jinja_templates: Optional[str] = None,\n        cmdline_args: List[str] = ['--disable-http-cache'],\n        size: Optional[Tuple[int, int]] = None,\n        position: Optional[Tuple[int, int]] = None,\n        geometry: Dict[str, Tuple[int, int]] = {},\n        close_callback: Optional[Callable[..., Any]] = None,\n        app_mode: bool = True,\n        all_interfaces: bool = False,\n        disable_cache: bool = True,\n        default_path: str = 'index.html',\n        app: btl.Bottle = btl.default_app(),\n        shutdown_delay: float = 1.0,\n        suppress_error: bool = False) -> None:\n    '''Start the Eel app.\n\n    Suppose you put all the frontend files in a directory called\n    :file:`web`, including your start page :file:`main.html`, then the app\n    is started like this:\n\n    .. code-block:: python\n\n        import eel\n        eel.init('web')\n        eel.start('main.html')\n\n    This will start a webserver on the default settings\n    (http://localhost:8000) and open a browser to\n    http://localhost:8000/main.html.\n\n    If Chrome or Chromium is installed then by default it will open that in\n    *App Mode* (with the `--app` cmdline flag), regardless of what the OS's\n    default browser is set to (it is possible to override this behaviour).\n\n    :param mode: What browser is used, e.g. :code:`'chrome'`,\n        :code:`'electron'`, :code:`'edge'`, :code:`'custom'`. Can also be\n        `None` or `False` to not open a window. *Default:* :code:`'chrome'`.\n    :param host: Hostname used for Bottle server. *Default:*\n        :code:`'localhost'`.\n    :param port: Port used for Bottle server. Use :code:`0` for port to be\n        picked automatically. *Default:* :code:`8000`.\n    :param block: Whether the call to :func:`start()` blocks the calling\n        thread. *Default:* `True`.\n    :param jinja_templates: Folder for :mod:`jinja2` templates, e.g.\n        :file:`my_templates`. *Default:* `None`.\n    :param cmdline_args: A list of strings to pass to the command starting the\n        browser. For example, we might add extra flags to Chrome with\n        :code:`eel.start('main.html', mode='chrome-app', port=8080,\n        cmdline_args=['--start-fullscreen', '--browser-startup-dialog'])`.\n        *Default:* :code:`[]`.\n    :param size: Tuple specifying the (width, height) of the main window in\n        pixels. *Default:* `None`.\n    :param position: Tuple specifying the (left, top) position of the main\n        window in pixels. *Default*: `None`.\n    :param geometry: A dictionary of specifying the size/position for all\n        windows. The keys should be the relative path of the page, and the\n        values should be a dictionary of the form\n        :code:`{'size': (200, 100), 'position': (300, 50)}`. *Default:*\n        :code:`{}`.\n    :param close_callback: A lambda or function that is called when a websocket\n        or window closes (i.e. when the user closes the window). It should take\n        two arguments: a string which is the relative path of the page that\n        just closed, and a list of the other websockets that are still open.\n        *Default:* `None`.\n    :param app_mode: Whether to run Chrome/Edge in App Mode. You can also\n        specify *mode* as :code:`mode='chrome-app'` as a shorthand to start\n        Chrome in App Mode.\n    :param all_interfaces: Whether to allow the :mod:`bottle` server to listen\n        for connections on all interfaces.\n    :param disable_cache: Sets the no-store response header when serving\n        assets.\n    :param default_path: The default file to retrieve for the root URL.\n    :param app: An instance of :class:`bottle.Bottle` which will be used rather\n        than creating a fresh one. This can be used to install middleware on\n        the instance before starting Eel, e.g. for session management,\n        authentication, etc. If *app* is not a :class:`bottle.Bottle` instance,\n        you will need to call :code:`eel.register_eel_routes(app)` on your\n        custom app instance.\n    :param shutdown_delay: Timer configurable for Eel's shutdown detection\n        mechanism, whereby when any websocket closes, it waits *shutdown_delay*\n        seconds, and then checks if there are now any websocket connections.\n        If not, then Eel closes. In case the user has closed the browser and\n        wants to exit the program. *Default:* :code:`1.0` seconds.\n    :param suppress_error: Temporary (suppressible) error message to inform\n        users of breaking API change for v1.0.0. Set to `True` to suppress\n        the error message.\n    '''\n    _start_args.update({\n        'mode': mode,\n        'host': host,\n        'port': port,\n        'block': block,\n        'jinja_templates': jinja_templates,\n        'cmdline_args': cmdline_args,\n        'size': size,\n        'position': position,\n        'geometry': geometry,\n        'close_callback': close_callback,\n        'app_mode': app_mode,\n        'all_interfaces': all_interfaces,\n        'disable_cache': disable_cache,\n        'default_path': default_path,\n        'app': app,\n        'shutdown_delay': shutdown_delay,\n        'suppress_error': suppress_error,\n    })\n\n    if _start_args['port'] == 0:\n        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        sock.bind(('localhost', 0))\n        _start_args['port'] = sock.getsockname()[1]\n        sock.close()\n\n    if _start_args['jinja_templates'] is not None:\n        from jinja2 import Environment, FileSystemLoader, select_autoescape\n        if not isinstance(_start_args['jinja_templates'], str):\n            raise TypeError(\"'jinja_templates' start_arg/option must be of type str\")\n        templates_path = os.path.join(root_path, _start_args['jinja_templates'])\n        _start_args['jinja_env'] = Environment(\n            loader=FileSystemLoader(templates_path),\n            autoescape=select_autoescape(['html', 'xml'])\n        )\n\n    # verify shutdown_delay is correct value\n    if not isinstance(_start_args['shutdown_delay'], (int, float)):\n        raise ValueError(\n            '`shutdown_delay` must be a number, '\n            'got a {}'.format(type(_start_args['shutdown_delay']))\n        )\n\n    # Launch the browser to the starting URLs\n    show(*start_urls)\n\n    def run_lambda() -> None:\n        if _start_args['all_interfaces'] is True:\n            HOST = '0.0.0.0'\n        else:\n            if not isinstance(_start_args['host'], str):\n                raise TypeError(\"'host' start_arg/option must be of type str\")\n            HOST = _start_args['host']\n\n        app = _start_args['app']\n\n        if isinstance(app, btl.Bottle):\n            register_eel_routes(app)\n        else:\n            register_eel_routes(btl.default_app())\n\n        btl.run(\n            host=HOST,\n            port=_start_args['port'],\n            server=wbs.GeventWebSocketServer,\n            quiet=True,\n            app=app)  # Always returns None\n\n    # Start the webserver\n    if _start_args['block']:\n        run_lambda()\n    else:\n        spawn(run_lambda)\n\n\ndef show(*start_urls: str) -> None:\n    '''Show the specified URL(s) in the browser.\n\n    Suppose you have two files in your :file:`web` folder. The file\n    :file:`hello.html` regularly includes :file:`eel.js` and provides\n    interactivity, and the file :file:`goodbye.html` does not include\n    :file:`eel.js` and simply provides plain HTML content not reliant on Eel.\n\n    First, we defien a callback function to be called when the browser\n    window is closed:\n\n    .. code-block:: python\n\n        def last_calls():\n           eel.show('goodbye.html')\n\n    Now we initialise and start Eel, with a :code:`close_callback` to our\n    function:\n\n    ..code-block:: python\n\n        eel.init('web')\n        eel.start('hello.html', mode='chrome-app', close_callback=last_calls)\n\n    When the websocket from :file:`hello.html` is closed (e.g. because the\n    user closed the browser window), Eel will wait *shutdown_delay* seconds\n    (by default 1 second), then call our :code:`last_calls()` function, which\n    opens another window with the :file:`goodbye.html` shown before our Eel app\n    terminates.\n\n    :param start_urls: One or more URLs to be opened.\n    '''\n    brw.open(list(start_urls), _start_args)\n\n\ndef sleep(seconds: Union[int, float]) -> None:\n    '''A non-blocking sleep call compatible with the Gevent event loop.\n\n    .. note::\n        While this function simply wraps :func:`gevent.sleep()`, it is better\n        to call :func:`eel.sleep()` in your eel app, as this will ensure future\n        compatibility in case the implementation of Eel should change in some\n        respect.\n\n    :param seconds: The number of seconds to sleep.\n    '''\n    gvt.sleep(seconds)\n\n\ndef spawn(function: Callable[..., Any], *args: Any, **kwargs: Any) -> gvt.Greenlet:\n    '''Spawn a new Greenlet.\n\n    Calling this function will spawn a new :class:`gevent.Greenlet` running\n    *function* asynchronously.\n\n    .. caution::\n        If you spawn your own Greenlets to run in addition to those spawned by\n        Eel's internal core functionality, you will have to ensure that those\n        Greenlets will terminate as appropriate (either by returning or by\n        being killed via Gevent's kill mechanism), otherwise your app may not\n        terminate correctly when Eel itself terminates.\n\n    :param function: The function to be called and run as the Greenlet.\n    :param *args: Any positional arguments that should be passed to *function*.\n    :param **kwargs: Any key-word arguments that should be passed to\n        *function*.\n    '''\n    return gvt.spawn(function, *args, **kwargs)\n\n\n# Bottle Routes\n\n\ndef _eel() -> str:\n    start_geometry = {'default': {'size': _start_args['size'],\n                                  'position': _start_args['position']},\n                      'pages':   _start_args['geometry']}\n\n    page = _eel_js.replace('/** _py_functions **/',\n                           '_py_functions: %s,' % list(_exposed_functions.keys()))\n    page = page.replace('/** _start_geometry **/',\n                        '_start_geometry: %s,' % _safe_json(start_geometry))\n    btl.response.content_type = 'application/javascript'\n    _set_response_headers(btl.response)\n    return page\n\n\ndef _root() -> btl.Response:\n    if not isinstance(_start_args['default_path'], str):\n        raise TypeError(\"'default_path' start_arg/option must be of type str\")\n    return _static(_start_args['default_path'])\n\n\ndef _static(path: str) -> btl.Response:\n    response = None\n    if 'jinja_env' in _start_args and 'jinja_templates' in _start_args:\n        if not isinstance(_start_args['jinja_templates'], str):\n            raise TypeError(\"'jinja_templates' start_arg/option must be of type str\")\n        template_prefix = _start_args['jinja_templates'] + '/'\n        if path.startswith(template_prefix):\n            n = len(template_prefix)\n            template = _start_args['jinja_env'].get_template(path[n:])\n            response = btl.HTTPResponse(template.render())\n\n    if response is None:\n        response = btl.static_file(path, root=root_path)\n\n    _set_response_headers(response)\n    return response\n\n\ndef _websocket(ws: WebSocketT) -> None:\n    global _websockets\n\n    for js_function in _js_functions:\n        _import_js_function(js_function)\n\n    page = btl.request.query.page\n    if page not in _mock_queue_done:\n        for call in _mock_queue:\n            _repeated_send(ws, _safe_json(call))\n        _mock_queue_done.add(page)\n\n    _websockets += [(page, ws)]\n\n    while True:\n        msg = ws.receive()\n        if msg is not None:\n            message = jsn.loads(msg)\n            spawn(_process_message, message, ws)\n        else:\n            _websockets.remove((page, ws))\n            break\n\n    _websocket_close(page)\n\n\nBOTTLE_ROUTES: Dict[str, Tuple[Callable[..., Any], Dict[Any, Any]]] = {\n    \"/eel.js\": (_eel, dict()),\n    \"/\": (_root, dict()),\n    \"/<path:path>\": (_static, dict()),\n    \"/eel\": (_websocket, dict(apply=[wbs.websocket]))\n}\n\n\ndef register_eel_routes(app: btl.Bottle) -> None:\n    '''Register the required eel routes with `app`.\n\n    .. note::\n\n        :func:`eel.register_eel_routes()` is normally invoked implicitly by\n        :func:`eel.start()` and does not need to be called explicitly in most\n        cases. Registering the eel routes explicitly is only needed if you are\n        passing something other than an instance of :class:`bottle.Bottle` to\n        :func:`eel.start()`.\n\n    :Example:\n\n        >>> app = bottle.Bottle()\n        >>> eel.register_eel_routes(app)\n        >>> middleware = beaker.middleware.SessionMiddleware(app)\n        >>> eel.start(app=middleware)\n\n    '''\n    for route_path, route_params in BOTTLE_ROUTES.items():\n        route_func, route_kwargs = route_params\n        app.route(path=route_path, callback=route_func, **route_kwargs)\n\n\n# Private functions\n\n\ndef _safe_json(obj: Any) -> str:\n    return jsn.dumps(obj, default=lambda o: None)\n\n\ndef _repeated_send(ws: WebSocketT, msg: str) -> None:\n    for attempt in range(100):\n        try:\n            ws.send(msg)\n            break\n        except Exception:\n            sleep(0.001)\n\n\ndef _process_message(message: Dict[str, Any], ws: WebSocketT) -> None:\n    if 'call' in message:\n        error_info = {}\n        try:\n            return_val = _exposed_functions[message['name']](*message['args'])\n            status = 'ok'\n        except Exception as e:\n            err_traceback = traceback.format_exc()\n            traceback.print_exc()\n            return_val = None\n            status = 'error'\n            error_info['errorText'] = repr(e)\n            error_info['errorTraceback'] = err_traceback\n        _repeated_send(ws, _safe_json({ 'return': message['call'],\n                                        'status': status,\n                                        'value': return_val,\n                                        'error': error_info,}))\n    elif 'return' in message:\n        call_id = message['return']\n        if call_id in _call_return_callbacks:\n            callback, error_callback = _call_return_callbacks.pop(call_id)\n            if message['status'] == 'ok':\n                callback(message['value'])\n            elif message['status'] == 'error' and error_callback is not None:\n                error_callback(message['error'], message['stack'])\n        else:\n            _call_return_values[call_id] = message['value']\n\n    else:\n        print('Invalid message received: ', message)\n\n\ndef _get_real_path(path: str) -> str:\n    if getattr(sys, 'frozen', False):\n        return os.path.join(sys._MEIPASS, path)  # type: ignore # sys._MEIPASS is dynamically added by PyInstaller\n    else:\n        return os.path.abspath(path)\n\n\ndef _mock_js_function(f: str) -> None:\n    exec('%s = lambda *args: _mock_call(\"%s\", args)' % (f, f), globals())\n\n\ndef _import_js_function(f: str) -> None:\n    exec('%s = lambda *args: _js_call(\"%s\", args)' % (f, f), globals())\n\n\ndef _call_object(name: str, args: Any) -> Dict[str, Any]:\n    global _call_number\n    _call_number += 1\n    call_id = _call_number + rnd.random()\n    return {'call': call_id, 'name': name, 'args': args}\n\n\ndef _mock_call(name: str, args: Any) -> Callable[[Optional[Callable[..., Any]], Optional[Callable[..., Any]]], Any]:\n    call_object = _call_object(name, args)\n    global _mock_queue\n    _mock_queue += [call_object]\n    return _call_return(call_object)\n\n\ndef _js_call(name: str, args: Any) -> Callable[[Optional[Callable[..., Any]], Optional[Callable[..., Any]]], Any]:\n    call_object = _call_object(name, args)\n    for _, ws in _websockets:\n        _repeated_send(ws, _safe_json(call_object))\n    return _call_return(call_object)\n\n\ndef _call_return(call: Dict[str, Any]) -> Callable[[Optional[Callable[..., Any]], Optional[Callable[..., Any]]], Any]:\n    global _js_result_timeout\n    call_id = call['call']\n\n    def return_func(callback: Optional[Callable[..., Any]] = None,\n                    error_callback: Optional[Callable[..., Any]] = None) -> Any:\n        if callback is not None:\n            _call_return_callbacks[call_id] = (callback, error_callback)\n        else:\n            for w in range(_js_result_timeout):\n                if call_id in _call_return_values:\n                    return _call_return_values.pop(call_id)\n                sleep(0.001)\n    return return_func\n\n\ndef _expose(name: str, function: Callable[..., Any]) -> None:\n    msg = 'Already exposed function with name \"%s\"' % name\n    assert name not in _exposed_functions, msg\n    _exposed_functions[name] = function\n\n\ndef _detect_shutdown() -> None:\n    if len(_websockets) == 0:\n        sys.exit()\n\n\ndef _websocket_close(page: str) -> None:\n    global _shutdown\n\n    close_callback = _start_args.get('close_callback')\n\n    if close_callback is not None:\n        if not callable(close_callback):\n            raise TypeError(\"'close_callback' start_arg/option must be callable or None\")\n        sockets = [p for _, p in _websockets]\n        close_callback(page, sockets)\n    else:\n        if isinstance(_shutdown, gvt.Greenlet):\n            _shutdown.kill()\n\n        _shutdown = gvt.spawn_later(_start_args['shutdown_delay'], _detect_shutdown)\n\n\ndef _set_response_headers(response: btl.Response) -> None:\n    if _start_args['disable_cache']:\n        # https://stackoverflow.com/a/24748094/280852\n        response.set_header('Cache-Control', 'no-store')\n"
  },
  {
    "path": "eel/__main__.py",
    "content": "from __future__ import annotations\nimport pkg_resources as pkg\nimport PyInstaller.__main__ as pyi\nimport os\nfrom argparse import ArgumentParser, Namespace\nfrom typing import List\n\nparser: ArgumentParser = ArgumentParser(description=\"\"\"\nEel is a little Python library for making simple Electron-like offline HTML/JS GUI apps,\n with full access to Python capabilities and libraries.\n\"\"\")\nparser.add_argument(\n    \"main_script\",\n    type=str,\n    help=\"Main python file to run app from\"\n)\nparser.add_argument(\n    \"web_folder\",\n    type=str,\n    help=\"Folder including all web files including file as html, css, ico, etc.\"\n)\nargs: Namespace\nunknown_args: List[str]\nargs, unknown_args = parser.parse_known_args()\nmain_script: str = args.main_script\nweb_folder: str = args.web_folder\n\nprint(\"Building executable with main script '%s' and web folder '%s'...\\n\" %\n      (main_script, web_folder))\n\neel_js_file: str = pkg.resource_filename('eel', 'eel.js')\njs_file_arg: str = '%s%seel' % (eel_js_file, os.pathsep)\nweb_folder_arg: str = '%s%s%s' % (web_folder, os.pathsep, web_folder)\n\nneeded_args: List[str] = ['--hidden-import', 'bottle_websocket',\n                          '--add-data', js_file_arg, '--add-data', web_folder_arg]\nfull_args: List[str] = [main_script] + needed_args + unknown_args\nprint('Running:\\npyinstaller', ' '.join(full_args), '\\n')\n\npyi.run(full_args)\n"
  },
  {
    "path": "eel/browsers.py",
    "content": "from __future__ import annotations\nimport subprocess as sps\nimport webbrowser as wbr\nfrom typing import Union, List, Dict, Iterable, Optional\nfrom types import ModuleType\n\nfrom eel.types import OptionsDictT\nimport eel.chrome as chm\nimport eel.electron as ele\nimport eel.edge as edge\nimport eel.msIE as ie\n#import eel.firefox as ffx      TODO\n#import eel.safari as saf       TODO\n\n_browser_paths: Dict[str, str] = {}\n_browser_modules: Dict[str, ModuleType] = {'chrome':   chm,\n                                           'electron': ele,\n                                           'edge': edge,\n                                           'msie':ie}\n\n\ndef _build_url_from_dict(page: Dict[str, str], options: OptionsDictT) -> str:\n    scheme = page.get('scheme', 'http')\n    host = page.get('host', 'localhost')\n    port = page.get('port', options[\"port\"])\n    path = page.get('path', '')\n    if not isinstance(port, (int, str)):\n        raise TypeError(\"'port' option must be an integer\")\n    return '%s://%s:%d/%s' % (scheme, host, int(port), path)\n\n\ndef _build_url_from_string(page: str, options: OptionsDictT) -> str:\n    if not isinstance(options['port'], (int, str)):\n        raise TypeError(\"'port' option must be an integer\")\n    base_url = 'http://%s:%d/' % (options['host'], int(options['port']))\n    return base_url + page\n\n\ndef _build_urls(start_pages: Iterable[Union[str, Dict[str, str]]], options: OptionsDictT) -> List[str]:\n    urls: List[str] = []\n\n    for page in start_pages:\n        if isinstance(page, dict):\n            url = _build_url_from_dict(page, options)\n        else:\n            url = _build_url_from_string(page, options)\n        urls.append(url)\n\n    return urls\n\n\ndef open(start_pages: Iterable[Union[str, Dict[str, str]]], options: OptionsDictT) -> None:\n    # Build full URLs for starting pages (including host and port)\n    start_urls = _build_urls(start_pages, options)\n    \n    mode = options.get('mode')\n    if not isinstance(mode, (str, type(None))) and mode is not False:\n        raise TypeError(\"'mode' option must by either a string, False, or None\")\n    if mode is None or mode is False:\n        # Don't open a browser\n        pass\n    elif mode == 'custom':\n        # Just run whatever command the user provided\n        if not isinstance(options['cmdline_args'], list):\n            raise TypeError(\"'cmdline_args' option must be of type List[str]\")\n        sps.Popen(options['cmdline_args'],\n                  stdout=sps.PIPE, stderr=sps.PIPE, stdin=sps.PIPE)\n    elif mode in _browser_modules:\n        # Run with a specific browser\n        browser_module = _browser_modules[mode]\n        path = _browser_paths.get(mode)\n        if path is None:\n            # Don't know this browser's path, try and find it ourselves\n            path = browser_module.find_path()\n            _browser_paths[mode] = path\n\n        if path is not None:\n            browser_module.run(path, options, start_urls)\n        else:\n            raise EnvironmentError(\"Can't find %s installation\" % browser_module.name)\n    else:\n        # Fall back to system default browser\n        for url in start_urls:\n            wbr.open(url)\n\n\ndef set_path(browser_name: str, path: str) -> None:\n    _browser_paths[browser_name] = path\n\n\ndef get_path(browser_name: str) -> Optional[str]:\n    return _browser_paths.get(browser_name)\n\n"
  },
  {
    "path": "eel/chrome.py",
    "content": "from __future__ import annotations\nimport sys\nimport os\nimport subprocess as sps\nfrom shutil import which\nfrom typing import List, Optional\nfrom eel.types import OptionsDictT\n\n# Every browser specific module must define run(), find_path() and name like this\n\nname: str = 'Google Chrome/Chromium'\n\ndef run(path: str, options: OptionsDictT, start_urls: List[str]) -> None:\n    if not isinstance(options['cmdline_args'], list):\n        raise TypeError(\"'cmdline_args' option must be of type List[str]\")\n    if options['app_mode']:\n        for url in start_urls:\n            sps.Popen([path, '--app=%s' % url] +\n                       options['cmdline_args'],\n                       stdout=sps.PIPE, stderr=sps.PIPE, stdin=sps.PIPE)\n    else:\n        args: List[str] = options['cmdline_args'] + start_urls\n        sps.Popen([path, '--new-window'] + args,\n                   stdout=sps.PIPE, stderr=sys.stderr, stdin=sps.PIPE)\n\n\ndef find_path() -> Optional[str]:\n    if sys.platform in ['win32', 'win64']:\n        return _find_chrome_win()\n    elif sys.platform == 'darwin':\n        return _find_chrome_mac() or _find_chromium_mac()\n    elif sys.platform.startswith('linux'):\n        return _find_chrome_linux()\n    else:\n        return None\n\n\ndef _find_chrome_mac() -> Optional[str]:\n    default_dir = r'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'\n    if os.path.exists(default_dir):\n        return default_dir\n    # use mdfind ci to locate Chrome in alternate locations and return the first one\n    name = 'Google Chrome.app'\n    alternate_dirs = [x for x in sps.check_output([\"mdfind\", name]).decode().split('\\n') if x.endswith(name)]\n    if len(alternate_dirs):\n        return alternate_dirs[0] + '/Contents/MacOS/Google Chrome'\n    return None\n\n\ndef _find_chromium_mac() -> Optional[str]:\n    default_dir = r'/Applications/Chromium.app/Contents/MacOS/Chromium'\n    if os.path.exists(default_dir):\n        return default_dir\n    # use mdfind ci to locate Chromium in alternate locations and return the first one\n    name = 'Chromium.app'\n    alternate_dirs = [x for x in sps.check_output([\"mdfind\", name]).decode().split('\\n') if x.endswith(name)]\n    if len(alternate_dirs):\n        return alternate_dirs[0] + '/Contents/MacOS/Chromium'\n    return None\n\n\ndef _find_chrome_linux() -> Optional[str]:\n    chrome_names = ['chromium-browser',\n                    'chromium',\n                    'google-chrome',\n                    'google-chrome-stable']\n\n    for name in chrome_names:\n        chrome = which(name)\n        if chrome is not None:\n            return chrome\n    return None\n\n\ndef _find_chrome_win() -> Optional[str]:\n    import winreg as reg\n    reg_path = r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe'\n    chrome_path: Optional[str] = None\n\n    for install_type in reg.HKEY_CURRENT_USER, reg.HKEY_LOCAL_MACHINE:\n        try:\n            reg_key = reg.OpenKey(install_type, reg_path, 0, reg.KEY_READ)\n            chrome_path = reg.QueryValue(reg_key, None)\n            reg_key.Close()\n            if not os.path.isfile(chrome_path):\n                continue\n        except WindowsError:\n            chrome_path = None\n        else:\n            break\n\n    return chrome_path\n"
  },
  {
    "path": "eel/edge.py",
    "content": "from __future__ import annotations\nimport platform\nimport subprocess as sps\nimport sys\nfrom typing import List\n\nfrom eel.types import OptionsDictT\n\nname: str = 'Edge'\n\n\ndef run(_path: str, options: OptionsDictT, start_urls: List[str]) -> None:\n    if not isinstance(options['cmdline_args'], list):\n        raise TypeError(\"'cmdline_args' option must be of type List[str]\")\n    args: List[str] = options['cmdline_args']\n    if options['app_mode']:\n        cmd = 'start msedge --app={} '.format(start_urls[0])\n        cmd = cmd + (\" \".join(args))\n        sps.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=sps.PIPE, shell=True)\n    else:\n        cmd = \"start msedge --new-window \"+(\" \".join(args)) +\" \"+(start_urls[0])\n        sps.Popen(cmd,stdout=sys.stdout, stderr=sys.stderr, stdin=sps.PIPE, shell=True)\n\ndef find_path() -> bool:\n    if platform.system() == 'Windows':\n        return True\n\n    return False\n"
  },
  {
    "path": "eel/eel.js",
    "content": "eel = {\n    _host: window.location.origin,\n\n    set_host: function (hostname) {\n        eel._host = hostname\n    },\n\n    expose: function(f, name) {\n        if(name === undefined){\n            name = f.toString();\n            let i = 'function '.length, j = name.indexOf('(');\n            name = name.substring(i, j).trim();\n        }\n\n        eel._exposed_functions[name] = f;\n    },\n\n    guid: function() {\n        return eel._guid;\n    },\n\n    // These get dynamically added by library when file is served\n    /** _py_functions **/\n    /** _start_geometry **/\n\n    _guid: ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>\n            (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)\n        ),\n\n    _exposed_functions: {},\n\n    _mock_queue: [],\n\n    _mock_py_functions: function() {\n        for(let i = 0; i < eel._py_functions.length; i++) {\n            let name = eel._py_functions[i];\n            eel[name] = function() {\n                let call_object = eel._call_object(name, arguments);\n                eel._mock_queue.push(call_object);\n                return eel._call_return(call_object);\n            }\n        }\n    },\n\n    _import_py_function: function(name) {\n        let func_name = name;\n        eel[name] = function() {\n            let call_object = eel._call_object(func_name, arguments);\n            eel._websocket.send(eel._toJSON(call_object));\n            return eel._call_return(call_object);\n        }\n    },\n\n    _call_number: 0,\n\n    _call_return_callbacks: {},\n\n    _call_object: function(name, args) {\n        let arg_array = [];\n        for(let i = 0; i < args.length; i++){\n            arg_array.push(args[i]);\n        }\n\n        let call_id = (eel._call_number += 1) + Math.random();\n        return {'call': call_id, 'name': name, 'args': arg_array};\n    },\n\n    _sleep: function(ms) {\n        return new Promise(resolve => setTimeout(resolve, ms));\n    },\n\n    _toJSON: function(obj) {\n        return JSON.stringify(obj, (k, v) => v === undefined ? null : v);\n    },\n\n    _call_return: function(call) {\n        return function(callback = null) {\n            if(callback != null) {\n                eel._call_return_callbacks[call.call] = {resolve: callback};\n            } else {\n                return new Promise(function(resolve, reject) {\n                    eel._call_return_callbacks[call.call] = {resolve: resolve, reject: reject};\n                });\n            }\n        }\n    },\n\n    _position_window: function(page) {\n        let size = eel._start_geometry['default'].size;\n        let position = eel._start_geometry['default'].position;\n\n        if(page in eel._start_geometry.pages) {\n            size = eel._start_geometry.pages[page].size;\n            position = eel._start_geometry.pages[page].position;\n        }\n\n        if(size != null){\n            window.resizeTo(size[0], size[1]);\n        }\n\n        if(position != null){\n            window.moveTo(position[0], position[1]);\n        }\n    },\n\n    _init: function() {\n        eel._mock_py_functions();\n\n        document.addEventListener(\"DOMContentLoaded\", function(event) {\n            let page = window.location.pathname.substring(1);\n            eel._position_window(page);\n\n            let websocket_addr = (eel._host + '/eel').replace('http', 'ws');\n            websocket_addr += ('?page=' + page);\n            eel._websocket = new WebSocket(websocket_addr);\n\n            eel._websocket.onopen = function() {\n                for(let i = 0; i < eel._py_functions.length; i++){\n                    let py_function = eel._py_functions[i];\n                    eel._import_py_function(py_function);\n                }\n\n                while(eel._mock_queue.length > 0) {\n                    let call = eel._mock_queue.shift();\n                    eel._websocket.send(eel._toJSON(call));\n                }\n            };\n\n            eel._websocket.onmessage = function (e) {\n                let message = JSON.parse(e.data);\n                if(message.hasOwnProperty('call') ) {\n                    // Python making a function call into us\n                    if(message.name in eel._exposed_functions) {\n                        try {\n                            let return_val = eel._exposed_functions[message.name](...message.args);\n                            eel._websocket.send(eel._toJSON({'return': message.call, 'status':'ok', 'value': return_val}));\n                        } catch(err) {\n                            debugger\n                            eel._websocket.send(eel._toJSON(\n                                {'return': message.call,\n                                'status':'error',\n                                'error': err.message,\n                                'stack': err.stack}));\n                        }\n                    }\n                } else if(message.hasOwnProperty('return')) {\n                    // Python returning a value to us\n                    if(message['return'] in eel._call_return_callbacks) {\n                        if(message['status']==='ok'){\n                            eel._call_return_callbacks[message['return']].resolve(message.value);\n                        }\n                        else if(message['status']==='error' &&  eel._call_return_callbacks[message['return']].reject) {\n                                eel._call_return_callbacks[message['return']].reject(message['error']);\n                        }\n                    }\n                } else {\n                    throw 'Invalid message ' + message;\n                }\n\n            };\n        });\n    }\n};\n\neel._init();\n\nif(typeof require !== 'undefined'){\n    // Avoid name collisions when using Electron, so jQuery etc work normally\n    window.nodeRequire = require;\n    delete window.require;\n    delete window.exports;\n    delete window.module;\n}\n"
  },
  {
    "path": "eel/electron.py",
    "content": "from __future__ import annotations\nimport sys\nimport os\nimport subprocess as sps\nfrom shutil import which\nfrom typing import List, Optional\n\nfrom eel.types import OptionsDictT\n\nname: str = 'Electron'\n\ndef run(path: str, options: OptionsDictT, start_urls: List[str]) -> None:\n    if not isinstance(options['cmdline_args'], list):\n        raise TypeError(\"'cmdline_args' option must be of type List[str]\")\n    cmd = [path] + options['cmdline_args']\n    cmd += ['.', ';'.join(start_urls)]\n    sps.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=sps.PIPE)\n\n\ndef find_path() -> Optional[str]:\n    if sys.platform in ['win32', 'win64']:\n        # It doesn't work well passing the .bat file to Popen, so we get the actual .exe\n        bat_path = which('electron')\n        if bat_path:\n            return os.path.join(bat_path, r'..\\node_modules\\electron\\dist\\electron.exe')\n    elif sys.platform in ['darwin', 'linux']:\n        # This should work fine...\n        return which('electron')\n    return None\n"
  },
  {
    "path": "eel/msIE.py",
    "content": "import platform\nimport subprocess as sps\nimport sys\nfrom typing import List\n\nfrom eel.types import OptionsDictT\n\nname: str = 'MSIE'\n\n\ndef run(_path: str, options: OptionsDictT, start_urls: List[str]) -> None:\n    cmd = 'start microsoft-edge:{}'.format(start_urls[0])\n    sps.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=sps.PIPE, shell=True)\n\n\ndef find_path() -> bool:\n    if platform.system() == 'Windows':\n        return True\n\n    return False\n"
  },
  {
    "path": "eel/py.typed",
    "content": ""
  },
  {
    "path": "eel/types.py",
    "content": "from __future__ import annotations\nfrom typing import Union, Dict, List, Tuple, Callable, Optional, Any, TYPE_CHECKING\nfrom typing_extensions import Literal, TypedDict, TypeAlias\nfrom bottle import Bottle\n\n# This business is slightly awkward, but needed for backward compatibility,\n# because Python <3.10 doesn't support TypeAlias, jinja2 may not be available\n# at runtime, and geventwebsocket.websocket doesn't have type annotations so\n# that direct imports will raise an error.\nif TYPE_CHECKING:\n    from jinja2 import Environment\n    JinjaEnvironmentT: TypeAlias = Environment\n    from geventwebsocket.websocket import WebSocket\n    WebSocketT: TypeAlias = WebSocket\nelse:\n    JinjaEnvironmentT: TypeAlias = Any\n    WebSocketT: TypeAlias = Any\n\nOptionsDictT = TypedDict(\n    'OptionsDictT',\n    {\n        'mode': Optional[Union[str, Literal[False]]],\n        'host': str,\n        'port': int,\n        'block': bool,\n        'jinja_templates': Optional[str],\n        'cmdline_args': List[str],\n        'size': Optional[Tuple[int, int]],\n        'position': Optional[Tuple[int, int]],\n        'geometry': Dict[str, Tuple[int, int]],\n        'close_callback': Optional[Callable[..., Any]],\n        'app_mode': bool,\n        'all_interfaces': bool,\n        'disable_cache': bool,\n        'default_path': str,\n        'app': Bottle,\n        'shutdown_delay': float,\n        'suppress_error': bool,\n        'jinja_env': JinjaEnvironmentT,\n    },\n    total=False\n)\n"
  },
  {
    "path": "examples/01 - hello_world/hello.py",
    "content": "import eel\n\n# Set web files folder\neel.init('web')\n\n@eel.expose                         # Expose this function to Javascript\ndef say_hello_py(x):\n    print('Hello from %s' % x)\n\nsay_hello_py('Python World!')\neel.say_hello_js('Python World!')   # Call a Javascript function\n\neel.start('hello.html', size=(300, 200))  # Start\n"
  },
  {
    "path": "examples/01 - hello_world/web/hello.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>Hello, World!</title>\n        \n        <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->\n        <script type=\"text/javascript\" src=\"/eel.js\"></script>\n        <script type=\"text/javascript\">\n        \n        eel.expose(say_hello_js);               // Expose this function to Python\n        function say_hello_js(x) {\n            console.log(\"Hello from \" + x);\n        }\n        \n        say_hello_js(\"Javascript World!\");\n        eel.say_hello_py(\"Javascript World!\");  // Call a Python function\n        \n        </script>\n    </head>\n    \n    <body>\n        Hello, World!\n    </body>\n</html>"
  },
  {
    "path": "examples/01 - hello_world-Edge/hello.py",
    "content": "import os\nimport platform\nimport sys\n\n# Use latest version of Eel from parent directory\nsys.path.insert(1, '../../')\nimport eel\n\n# Use the same static files as the original Example\nos.chdir(os.path.join('..', '01 - hello_world'))\n\n# Set web files folder and optionally specify which file types to check for eel.expose()\neel.init('web', allowed_extensions=['.js', '.html'])\n\n\n@eel.expose                         # Expose this function to Javascript\ndef say_hello_py(x):\n    print('Hello from %s' % x)\n\n\nsay_hello_py('Python World!')\neel.say_hello_js('Python World!')   # Call a Javascript function\n\n# Launch example in Microsoft Edge only on Windows 10 and above\nif sys.platform in ['win32', 'win64'] and int(platform.release()) >= 10:\n    eel.start('hello.html', mode='edge')\nelse:\n    raise EnvironmentError('Error: System is not Windows 10 or above')\n\n# # Launching Edge can also be gracefully handled as a fall back\n# try:\n#     eel.start('hello.html', mode='chrome-app', size=(300, 200))\n# except EnvironmentError:\n#     # If Chrome isn't found, fallback to Microsoft Edge on Win10 or greater\n#     if sys.platform in ['win32', 'win64'] and int(platform.release()) >= 10:\n#         eel.start('hello.html', mode='edge')\n#     else:\n#         raise\n"
  },
  {
    "path": "examples/02 - callbacks/callbacks.py",
    "content": "import eel\nimport random\n\neel.init('web')\n\n@eel.expose\ndef py_random():\n    return random.random()\n\n@eel.expose\ndef py_exception(error):\n    if error:\n        raise ValueError(\"Test\")\n    else:\n        return \"No Error\"\n\ndef print_num(n):\n    print('Got this from Javascript:', n)\n\n\ndef print_num_failed(error, stack):\n    print(\"This is an example of what javascript errors would look like:\")\n    print(\"\\tError: \", error)\n    print(\"\\tStack: \", stack)\n\n# Call Javascript function, and pass explicit callback function    \neel.js_random()(print_num)\n\n# Do the same with an inline callback\neel.js_random()(lambda n: print('Got this from Javascript:', n))\n\n# Show error handling\neel.js_with_error()(print_num, print_num_failed)\n\n\neel.start('callbacks.html', size=(400, 300))\n\n"
  },
  {
    "path": "examples/02 - callbacks/web/callbacks.html",
    "content": " <!DOCTYPE html>\n<html>\n    <head>\n        <title>Callbacks Demo</title>\n        \n        <script type=\"text/javascript\" src=\"/eel.js\"></script>\n        <script type=\"text/javascript\">\n        \n        eel.expose(js_random);\n        function js_random() {\n            return Math.random();\n        }\n\n        eel.expose(js_with_error);\n        function js_with_error() {\n            var test = 0;\n            test.something(\"does not exist\");\n        }\n        \n        function print_num(n) {\n            console.log('Got this from Python: ' + n);\n        }\n        \n        // Call Python function, and pass explicit callback function\n        eel.py_random()(print_num);\n        \n        // Do the same with an inline callback\n        eel.py_random()(n => console.log('Got this from Python: ' + n));\n\n        // show usage with promises\n        // show no error\n        eel.py_exception(false)().then((result) => {\n                // this will execute since we said no error\n                console.log(\"No Error\")\n            }).catch((result) => {\n                console.log(\"This won't be seen if no error\")\n            }\n        );\n        // show if an error occurrs\n        eel.py_exception(true)().then((result) => {\n                // this will not execute\n                console.log(\"No Error\")\n            }).catch((result) => {\n                console.log(\"This is the repr(e) for an exception \" + result.errorText);\n                console.log(\"This is the full traceback:\\n\" + result.errorTraceback);\n            }\n        )\n        </script>\n    </head>\n    \n    <body>\n        Callbacks demo\n    </body>\n</html>\n"
  },
  {
    "path": "examples/03 - sync_callbacks/sync_callbacks.py",
    "content": "import eel, random\n\neel.init('web')\n\n@eel.expose\ndef py_random():\n    return random.random()\n\neel.start('sync_callbacks.html', block=False, size=(400, 300))\n\n# Synchronous calls must happen after start() is called\n\n# Get result returned synchronously by \n# passing nothing in second brackets\n#                   v\nn = eel.js_random()()\nprint('Got this from Javascript:', n)\n\nwhile True:\n    eel.sleep(1.0)\n"
  },
  {
    "path": "examples/03 - sync_callbacks/web/sync_callbacks.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>Synchronous callbacks</title>\n        \n        <script type=\"text/javascript\" src=\"/eel.js\"></script>\n        <script type=\"text/javascript\">\n                \n        eel.expose(js_random);\n        function js_random() {\n            return Math.random();\n        }\n        \n        async function run() {\n            // Synchronous call must be inside function marked 'async'\n            \n            // Get result returned synchronously by \n            //  using 'await' and passing nothing in second brackets\n            //        v                   v\n            let n = await eel.py_random()();\n            console.log('Got this from Python: ' + n);\n        }\n        \n        run();\n        \n        </script>\n    </head>\n    \n    <body>\n        Synchronous callbacks\n    </body>\n</html>"
  },
  {
    "path": "examples/04 - file_access/README.md",
    "content": "# Example 4 - file access\n\n![Screenshot](Screenshot.png)\n"
  },
  {
    "path": "examples/04 - file_access/file_access.py",
    "content": "import eel, os, random\n\neel.init('web')\n\n@eel.expose\ndef pick_file(folder):\n    if os.path.isdir(folder):\n        return random.choice(os.listdir(folder))\n    else:\n        return 'Not valid folder'\n\neel.start('file_access.html', size=(320, 120))\n"
  },
  {
    "path": "examples/04 - file_access/web/file_access.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>Eel Demo</title>\n        <script type='text/javascript' src='/eel.js'></script>\n        <script type='text/javascript'>\n        \n        async function pick_file() {\n            let folder = document.getElementById('input-box').value;\n            let file_div = document.getElementById('file-name');\n            \n            // Call into Python so we can access the file system\n            let random_filename = await eel.pick_file(folder)();\n            file_div.innerHTML = random_filename;\n        }\n        \n        </script>\n    </head>\n    \n    <body>\n      <form onsubmit=\"pick_file(); return false;\" >\n        <input id='input-box' placeholder='Type folder here' value='C:\\Windows'/>\n        <button type=\"submit\">Pick random file</button>\n      </form>\n      <div id='file-name'>---</div>\n    </body>\n</html>\n"
  },
  {
    "path": "examples/05 - input/script.py",
    "content": "import eel\n\neel.init('web')                     # Give folder containing web files\n\n@eel.expose                         # Expose this function to Javascript\ndef handleinput(x):\n    print('%s' % x)\n\neel.say_hello_js('connected!')   # Call a Javascript function\n\neel.start('main.html', size=(500, 200))    # Start\n"
  },
  {
    "path": "examples/05 - input/web/main.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css\" integrity=\"sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy\" crossorigin=\"anonymous\"> \n        <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script>\n        <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->\n        <script type=\"text/javascript\" src=\"/eel.js\"></script>\n        <script type=\"text/javascript\">\n        $(function(){\n\n                    eel.expose(say_hello_js);               // Expose this function to Python\n                    function say_hello_js(x) {\n                    console.log(\"Hello from \" + x);\n                    }\n                    say_hello_js(\"Javascript World!\");\n                    eel.handleinput(\"connected!\");  // Call a Python function\n                    \n                    $(\"#btn\").click(function(){\n                        eel.handleinput($(\"#inp\").val());\n                        $('#inp').val('');\n                    });\n        }); \n        </script>\n    </head>\n    \n    <body>\n        <h1>Input Example: Enter a value and check python console</h1>\n        <div>\n            <input type='text' id='inp' placeholder='Write anything'>\n            <input type='button' id='btn' class='btn btn-primary' value='Submit'>\n        </div>\n    </body>\n</html>\n"
  },
  {
    "path": "examples/06 - jinja_templates/hello.py",
    "content": "import random\n\nimport eel\n\neel.init('web')                     # Give folder containing web files\n\n@eel.expose\ndef py_random():\n    return random.random()\n\n@eel.expose                         # Expose this function to Javascript\ndef say_hello_py(x):\n    print('Hello from %s' % x)\n\nsay_hello_py('Python World!')\neel.say_hello_js('Python World!')   # Call a Javascript function\n\neel.start('templates/hello.html', size=(300, 200), jinja_templates='templates')    # Start\n"
  },
  {
    "path": "examples/06 - jinja_templates/web/templates/base.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>{% block title %}{% endblock %}</title>\n        <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->\n        <script type=\"text/javascript\" src=\"/eel.js\"></script>\n        <script type=\"text/javascript\">\n            {% block head_scripts %}{% endblock %}\n        </script>\n    </head>\n    <body>\n        {% block content %}{% endblock %}\n    </body>\n</html>\n"
  },
  {
    "path": "examples/06 - jinja_templates/web/templates/hello.html",
    "content": "{% extends 'base.html' %} \n{% block title %}Hello, World!{% endblock %}\n{% block head_scripts %}        \n    eel.expose(say_hello_js);               // Expose this function to Python\n        function say_hello_js(x) {\n        console.log(\"Hello from \" + x);\n    }\n\n    eel.expose(js_random);\n    function js_random() {\n        return Math.random();\n    }\n\n    function print_num(n) {\n        console.log('Got this from Python: ' + n);\n    }\n\n    eel.py_random()(print_num);\n        \n    say_hello_js(\"Javascript World!\");\n    eel.say_hello_py(\"Javascript World!\");  // Call a Python function\n{% endblock %}\n{% block content %}\n    Hello, World!\n    <br />\n    <a href=\"page2.html\">Page 2</a>\n{% endblock %}\n"
  },
  {
    "path": "examples/06 - jinja_templates/web/templates/page2.html",
    "content": "{% extends 'base.html' %}\n{% block title %}Hello, World!{% endblock %}\n{% block content %}\n<h1>This is page 2</h1>\n{% endblock %}\n"
  },
  {
    "path": "examples/07 - CreateReactApp/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n*.spec\n"
  },
  {
    "path": "examples/07 - CreateReactApp/README.md",
    "content": "> \"Eello World example\": Create-React-App (CRA) and Eel\n\n**Table of Contents**\n\n<!-- TOC -->\n\n- [07 - CreateReactApp Documentation](#07---createreactapp-documentation)\n    - [Quick Start](#quick-start)\n    - [About](#about)\n    - [Main Files](#main-files)\n\n<!-- /TOC -->\n\n# 07 - CreateReactApp Documentation\n\nEello World example Create-React-App (CRA) with Eel. This particular project was bootstrapped with `npx create-react-app 07_CreateReactApp --typescript` (Typescript enabled), but the below modifications can be implemented in any CRA configuration or CRA version.\n\nIf you run into any issues with this example, open a [new issue](https://github.com/ChrisKnott/Eel/issues/new) and tag @KyleKing\n\n## Quick Start\n\n1. **Configure:** In the app's directory, run `npm install` and `pip install bottle bottle-websocket future pyinstaller`\n2. **Demo:** Build static files with `npm run build` then run the application with `python eel_CRA.py`. A Chrome-app window should open running the built code from `build/`\n3. **Distribute:** (Run `npm run build` first) Build a binary distribution with PyInstaller using `python -m eel eel_CRA.py build --onefile` (See more detailed PyInstaller instructions at bottom of [the main README](https://github.com/ChrisKnott/Eel))\n4. **Develop:** Open two prompts. In one, run  `python eel_CRA.py true` and the other, `npm start`. A browser window should open in your default web browser at: [http://localhost:3000/](http://localhost:3000/). As you make changes to the JavaScript in `src/` the browser will reload. Any changes to `eel_CRA.py` will require a restart to take effect. You may need to refresh the browser window if it gets out of sync with eel.\n\n![Demo.png](Demo.png)\n\n## About\n\n> Use `window.eel.expose(func, 'func')` to circumvent `npm run build` code mangling\n\n`npm run build` will rename variables and functions to minimize file size renaming `eel.expose(funcName)` to something like `D.expose(J)`. The renaming breaks Eel's static JS-code analyzer, which uses a regular expression to look for `eel.expose(*)`. To fix this issue, in your JS code, convert all `eel.expose(funcName)` to `window.eel(funcName, 'funcName')`. This workaround guarantees that 'funcName' will be available to call from Python.\n\n## Main Files\n\nCritical files for this demo\n\n- `src/App.tsx`: Modified to demonstrate exposing a function from JavaScript and how to use callbacks from Python to update React GUI\n- `eel_CRA.py`: Basic `eel` file\n  - If run without arguments, the `eel` script will load `index.html` from the build/ directory (which is ideal for building with PyInstaller/distribution)\n  - If any 2nd argument (i.e. `true`) is provided, the app enables a \"development\" mode and attempts to connect to the React server on port 3000\n- `public/index.html`: Added location of `eel.js` file based on options set in eel_CRA.py\n\n  ```html\n  <!-- Load eel.js from the port specified in the eel.start options -->\n  <script type=\"text/javascript\" src=\"http://localhost:8080/eel.js\"></script>\n  ```\n\n- `src/react-app-env.d.ts`: This file declares window.eel as a valid type for tslint. Note: capitalization of `window`\n- `src/App.css`: Added some basic button styling\n"
  },
  {
    "path": "examples/07 - CreateReactApp/eel_CRA.py",
    "content": "\"\"\"Main Python application file for the EEL-CRA demo.\"\"\"\n\nimport os\nimport platform\nimport random\nimport sys\n\nimport eel\n\n# Use latest version of Eel from parent directory\nsys.path.insert(1, '../../')\n\n\n@eel.expose  # Expose function to JavaScript\ndef say_hello_py(x):\n    \"\"\"Print message from JavaScript on app initialization, then call a JS function.\"\"\"\n    print('Hello from %s' % x)  # noqa T001\n    eel.say_hello_js('Python {from within say_hello_py()}!')\n\n\n@eel.expose\ndef expand_user(folder):\n    \"\"\"Return the full path to display in the UI.\"\"\"\n    return '{}/*'.format(os.path.expanduser(folder))\n\n\n@eel.expose\ndef pick_file(folder):\n    \"\"\"Return a random file from the specified folder.\"\"\"\n    folder = os.path.expanduser(folder)\n    if os.path.isdir(folder):\n        listFiles = [_f for _f in os.listdir(folder) if not os.path.isdir(os.path.join(folder, _f))]\n        if len(listFiles) == 0:\n            return 'No Files found in {}'.format(folder)\n        return random.choice(listFiles)\n    else:\n        return '{} is not a valid folder'.format(folder)\n\n\ndef start_eel(develop):\n    \"\"\"Start Eel with either production or development configuration.\"\"\"\n\n    if develop:\n        directory = 'src'\n        app = None\n        page = {'port': 3000}\n    else:\n        directory = 'build'\n        app = 'chrome-app'\n        page = 'index.html'\n\n    eel.init(directory, ['.tsx', '.ts', '.jsx', '.js', '.html'])\n\n    # These will be queued until the first connection is made, but won't be repeated on a page reload\n    say_hello_py('Python World!')\n    eel.say_hello_js('Python World!')   # Call a JavaScript function (must be after `eel.init()`)\n\n    eel.show_log('https://github.com/samuelhwilliams/Eel/issues/363 (show_log)')\n\n    eel_kwargs = dict(\n        host='localhost',\n        port=8080,\n        size=(1280, 800),\n    )\n    try:\n        eel.start(page, mode=app, **eel_kwargs)\n    except EnvironmentError:\n        # If Chrome isn't found, fallback to Microsoft Edge on Win10 or greater\n        if sys.platform in ['win32', 'win64'] and int(platform.release()) >= 10:\n            eel.start(page, mode='edge', **eel_kwargs)\n        else:\n            raise\n\n\nif __name__ == '__main__':\n    import sys\n\n    # Pass any second argument to enable debugging\n    start_eel(develop=len(sys.argv) == 2)\n"
  },
  {
    "path": "examples/07 - CreateReactApp/package.json",
    "content": "{\n  \"name\": \"07___create-react-app\",\n  \"version\": \"0.1.1\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@types/jest\": \"24.0.14\",\n    \"@types/node\": \"12.0.8\",\n    \"@types/react\": \"16.8.20\",\n    \"@types/react-dom\": \"16.8.4\",\n    \"react\": \"^16.8.6\",\n    \"react-dom\": \"^16.8.6\",\n    \"react-scripts\": \"^3.4.1\",\n    \"typescript\": \"3.4.5\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test\",\n    \"eject\": \"react-scripts eject\"\n  },\n  \"eslintConfig\": {\n    \"extends\": \"react-app\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ]\n}\n"
  },
  {
    "path": "examples/07 - CreateReactApp/public/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n\n    <!-- Load eel.js from the port specified in the eel.start options -->\n    <script type=\"text/javascript\" src=\"http://localhost:8080/eel.js\"></script>\n\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/07 - CreateReactApp/public/manifest.json",
    "content": "{\n  \"short_name\": \"React App\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n      \"sizes\": \"64x64 32x32 24x24 16x16\",\n      \"type\": \"image/x-icon\"\n    }\n  ],\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/07 - CreateReactApp/src/App.css",
    "content": ".App {\n  text-align: center;\n}\n\n.App-logo {\n  animation: App-logo-spin infinite 20s linear;\n  height: 40vmin;\n}\n\n.App-header {\n  background-color: #282c34;\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  font-size: calc(10px + 2vmin);\n  color: white;\n}\n\n.App-button {\n  background-color: #61dafb;\n  border-radius: 2vmin;\n  color: #282c34;\n  font-size: calc(10px + 2vmin);\n  padding: 2vmin;\n}\n\n\n.App-button:hover {\n  background-color: #7ce3ff;\n  cursor: pointer;\n}\n\n@keyframes App-logo-spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n"
  },
  {
    "path": "examples/07 - CreateReactApp/src/App.test.tsx",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\n\nit('renders without crashing', () => {\n  const div = document.createElement('div');\n  ReactDOM.render(<App />, div);\n  ReactDOM.unmountComponentAtNode(div);\n});\n"
  },
  {
    "path": "examples/07 - CreateReactApp/src/App.tsx",
    "content": "import React, { Component } from 'react';\nimport logo from './logo.svg';\nimport './App.css';\n\n// Point Eel web socket to the instance\nexport const eel = window.eel\neel.set_host( 'ws://localhost:8080' )\n\n// Expose the `sayHelloJS` function to Python as `say_hello_js`\nfunction sayHelloJS( x: any ) {\n  console.log( 'Hello from ' + x )\n}\n// WARN: must use window.eel to keep parse-able eel.expose{...}\nwindow.eel.expose( sayHelloJS, 'say_hello_js' )\n\n// Test anonymous function when minimized. See https://github.com/samuelhwilliams/Eel/issues/363\nfunction show_log(msg:string) {\n  console.log(msg)\n}\nwindow.eel.expose(show_log, 'show_log')\n\n// Test calling sayHelloJS, then call the corresponding Python function\nsayHelloJS( 'Javascript World!' )\neel.say_hello_py( 'Javascript World!' )\n\n// Set the default path. Would be a text input, but this is a basic example after all\nconst defPath = '~'\n\ninterface IAppState {\n  message: string\n  path: string\n}\n\nexport class App extends Component<{}, {}> {\n  public state: IAppState = {\n    message: `Click button to choose a random file from the user's system`,\n    path: defPath,\n  }\n\n  public pickFile = () => {\n    eel.pick_file(defPath)(( message: string ) => this.setState( { message } ) )\n  }\n\n  public render() {\n    eel.expand_user(defPath)(( path: string ) => this.setState( { path } ) )\n    return (\n      <div className=\"App\">\n        <header className=\"App-header\">\n          <img src={logo} className=\"App-logo\" alt=\"logo\" />\n          <p>{this.state.message}</p>\n          <button className='App-button' onClick={this.pickFile}>Pick Random File From `{this.state.path}`</button>\n        </header>\n      </div>\n    );\n  }\n}\n\nexport default App;\n"
  },
  {
    "path": "examples/07 - CreateReactApp/src/index.css",
    "content": "body {\n  margin: 0;\n  padding: 0;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n    monospace;\n}\n"
  },
  {
    "path": "examples/07 - CreateReactApp/src/index.tsx",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nReactDOM.render(<App />, document.getElementById('root'));\n\n// If you want your app to work offline and load faster, you can change\n// unregister() to register() below. Note this comes with some pitfalls.\n// Learn more about service workers: http://bit.ly/CRA-PWA\nserviceWorker.unregister();\n"
  },
  {
    "path": "examples/07 - CreateReactApp/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n\ninterface Window {\n  eel: any;\n}\n\ndeclare var window: Window;\n"
  },
  {
    "path": "examples/07 - CreateReactApp/src/serviceWorker.ts",
    "content": "// This optional code is used to register a service worker.\n// register() is not called by default.\n\n// This lets the app load faster on subsequent visits in production, and gives\n// it offline capabilities. However, it also means that developers (and users)\n// will only see deployed updates on subsequent visits to a page, after all the\n// existing tabs open on the page have been closed, since previously cached\n// resources are updated in the background.\n\n// To learn more about the benefits of this model and instructions on how to\n// opt-in, read http://bit.ly/CRA-PWA\n\nconst isLocalhost = Boolean(\n  window.location.hostname === 'localhost' ||\n    // [::1] is the IPv6 localhost address.\n    window.location.hostname === '[::1]' ||\n    // 127.0.0.1/8 is considered localhost for IPv4.\n    window.location.hostname.match(\n      /^127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/\n    )\n);\n\ntype Config = {\n  onSuccess?: (registration: ServiceWorkerRegistration) => void;\n  onUpdate?: (registration: ServiceWorkerRegistration) => void;\n};\n\nexport function register(config?: Config) {\n  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {\n    // The URL constructor is available in all browsers that support SW.\n    const publicUrl = new URL(\n      (process as { env: { [key: string]: string } }).env.PUBLIC_URL,\n      window.location.href\n    );\n    if (publicUrl.origin !== window.location.origin) {\n      // Our service worker won't work if PUBLIC_URL is on a different origin\n      // from what our page is served on. This might happen if a CDN is used to\n      // serve assets; see https://github.com/facebook/create-react-app/issues/2374\n      return;\n    }\n\n    window.addEventListener('load', () => {\n      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;\n\n      if (isLocalhost) {\n        // This is running on localhost. Let's check if a service worker still exists or not.\n        checkValidServiceWorker(swUrl, config);\n\n        // Add some additional logging to localhost, pointing developers to the\n        // service worker/PWA documentation.\n        navigator.serviceWorker.ready.then(() => {\n          console.log(\n            'This web app is being served cache-first by a service ' +\n              'worker. To learn more, visit http://bit.ly/CRA-PWA'\n          );\n        });\n      } else {\n        // Is not localhost. Just register service worker\n        registerValidSW(swUrl, config);\n      }\n    });\n  }\n}\n\nfunction registerValidSW(swUrl: string, config?: Config) {\n  navigator.serviceWorker\n    .register(swUrl)\n    .then(registration => {\n      registration.onupdatefound = () => {\n        const installingWorker = registration.installing;\n        if (installingWorker == null) {\n          return;\n        }\n        installingWorker.onstatechange = () => {\n          if (installingWorker.state === 'installed') {\n            if (navigator.serviceWorker.controller) {\n              // At this point, the updated precached content has been fetched,\n              // but the previous service worker will still serve the older\n              // content until all client tabs are closed.\n              console.log(\n                'New content is available and will be used when all ' +\n                  'tabs for this page are closed. See http://bit.ly/CRA-PWA.'\n              );\n\n              // Execute callback\n              if (config && config.onUpdate) {\n                config.onUpdate(registration);\n              }\n            } else {\n              // At this point, everything has been precached.\n              // It's the perfect time to display a\n              // \"Content is cached for offline use.\" message.\n              console.log('Content is cached for offline use.');\n\n              // Execute callback\n              if (config && config.onSuccess) {\n                config.onSuccess(registration);\n              }\n            }\n          }\n        };\n      };\n    })\n    .catch(error => {\n      console.error('Error during service worker registration:', error);\n    });\n}\n\nfunction checkValidServiceWorker(swUrl: string, config?: Config) {\n  // Check if the service worker can be found. If it can't reload the page.\n  fetch(swUrl)\n    .then(response => {\n      // Ensure service worker exists, and that we really are getting a JS file.\n      const contentType = response.headers.get('content-type');\n      if (\n        response.status === 404 ||\n        (contentType != null && contentType.indexOf('javascript') === -1)\n      ) {\n        // No service worker found. Probably a different app. Reload the page.\n        navigator.serviceWorker.ready.then(registration => {\n          registration.unregister().then(() => {\n            window.location.reload();\n          });\n        });\n      } else {\n        // Service worker found. Proceed as normal.\n        registerValidSW(swUrl, config);\n      }\n    })\n    .catch(() => {\n      console.log(\n        'No internet connection found. App is running in offline mode.'\n      );\n    });\n}\n\nexport function unregister() {\n  if ('serviceWorker' in navigator) {\n    navigator.serviceWorker.ready.then(registration => {\n      registration.unregister();\n    });\n  }\n}\n"
  },
  {
    "path": "examples/07 - CreateReactApp/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\n      \"dom\",\n      \"dom.iterable\",\n      \"esnext\"\n    ],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"preserve\"\n  },\n  \"include\": [\n    \"src\"\n  ]\n}\n"
  },
  {
    "path": "examples/08 - disable_cache/disable_cache.py",
    "content": "import eel\n\n# Set web files folder and optionally specify which file types to check for eel.expose()\neel.init('web')\n\n# disable_cache now defaults to True so this isn't strictly necessary. Set it to False to enable caching.\neel.start('disable_cache.html', size=(300, 200), disable_cache=True)    # Start\n"
  },
  {
    "path": "examples/08 - disable_cache/web/disable_cache.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>Hello, World!</title>\n        \n        <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->\n        <script type=\"text/javascript\" src=\"/eel.js\"></script>\n        <script type=\"text/javascript\" src=\"dont_cache_me.js\"></script>\n    </head>\n    \n    <body>\n        Cache Proof!\n    </body>\n</html>"
  },
  {
    "path": "examples/08 - disable_cache/web/dont_cache_me.js",
    "content": "console.log(\"Check the network activity to see that this file isn't getting cached.\");\n"
  },
  {
    "path": "examples/09 - Eelectron-quick-start/.gitignore",
    "content": "node_modules\n"
  },
  {
    "path": "examples/09 - Eelectron-quick-start/hello.py",
    "content": "import eel\n# Set web files folder\neel.init('web')\n\n@eel.expose                         # Expose this function to Javascript\ndef say_hello_py(x):\n    print('Hello from %s' % x)\n\nsay_hello_py('Python World!')\neel.say_hello_js('Python World!')   # Call a Javascript function\n\neel.start('hello.html',mode='electron')\n#eel.start('hello.html', mode='custom', cmdline_args=['node_modules/electron/dist/electron.exe', '.'])\n"
  },
  {
    "path": "examples/09 - Eelectron-quick-start/main.js",
    "content": "// Modules to control application life and create native browser window\nconst {app, BrowserWindow} = require('electron')\n\n// Keep a global reference of the window object, if you don't, the window will\n// be closed automatically when the JavaScript object is garbage collected.\nlet mainWindow\n\nfunction createWindow () {\n  // Create the browser window.\n  mainWindow = new BrowserWindow({\n    width: 800,\n    height: 600,\n    webPreferences: {\n      nodeIntegration: true\n    }\n  })\n\n  // and load the index.html of the app.\n  mainWindow.loadURL('http://localhost:8000/hello.html');\n\n  // Open the DevTools.\n  // mainWindow.webContents.openDevTools()\n\n  // Emitted when the window is closed.\n  mainWindow.on('closed', function () {\n    // Dereference the window object, usually you would store windows\n    // in an array if your app supports multi windows, this is the time\n    // when you should delete the corresponding element.\n    mainWindow = null\n  })\n}\n\n// This method will be called when Electron has finished\n// initialization and is ready to create browser windows.\n// Some APIs can only be used after this event occurs.\napp.on('ready', createWindow)\n\n// Quit when all windows are closed.\napp.on('window-all-closed', function () {\n  // On macOS it is common for applications and their menu bar\n  // to stay active until the user quits explicitly with Cmd + Q\n  if (process.platform !== 'darwin') app.quit()\n})\n\napp.on('activate', function () {\n  // On macOS it's common to re-create a window in the app when the\n  // dock icon is clicked and there are no other windows open.\n  if (mainWindow === null) createWindow()\n})\n\n// In this file you can include the rest of your app's specific main process\n// code. You can also put them in separate files and require them here.\n"
  },
  {
    "path": "examples/09 - Eelectron-quick-start/package.json",
    "content": "{\n  \"name\": \"Eelectron-quick-start\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A minimal Eelectron application\",\n  \"main\": \"main.js\",\n  \"scripts\": {\n    \"start\": \"electron .\"\n  },\n  \"repository\": \"https://github.com/electron/electron-quick-start\",\n  \"keywords\": [\n    \"Electron\",\n    \"quick\",\n    \"start\",\n    \"tutorial\",\n    \"demo\"\n  ],\n  \"author\": \"GitHub\",\n  \"license\": \"CC0-1.0\",\n  \"devDependencies\": {\n    \"electron\": \"^7.2.4\"\n  }\n}\n"
  },
  {
    "path": "examples/09 - Eelectron-quick-start/web/hello.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>Hello, World!</title>\n        \n        <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->\n        <script type=\"text/javascript\" src=\"/eel.js\"></script>\n        <script type=\"text/javascript\">\n        \n        eel.expose(say_hello_js);               // Expose this function to Python\n        function say_hello_js(x) {\n            console.log(\"Hello from \" + x);\n        }\n        \n        say_hello_js(\"Javascript World!\");\n        eel.say_hello_py(\"Javascript World!\");  // Call a Python function\n        \n        </script>\n    </head>\n    \n    <body>\n        Hello, World!\n    </body>\n</html>"
  },
  {
    "path": "examples/10 - custom_app_routes/custom_app.py",
    "content": "import eel\nimport bottle\n# from beaker.middleware import SessionMiddleware\n\napp = bottle.Bottle()\n@app.route('/custom')\ndef custom_route():\n    return 'Hello, World!'\n\neel.init('web')\n\n# need to manually add eel routes if we are wrapping our Bottle instance with middleware\n# eel.add_eel_routes(app)\n# middleware = SessionMiddleware(app)\n# eel.start('index.html', app=middleware)\n\neel.start('index.html', app=app)\n"
  },
  {
    "path": "examples/10 - custom_app_routes/web/index.html",
    "content": "<!DOCTYPE html>\n<html>\n\n<head>\n    <title>Hello, World!</title>\n</head>\n\n</html>\n"
  },
  {
    "path": "mypy.ini",
    "content": "[mypy]\npython_version = 3.10\nwarn_unused_configs = True\n\n[mypy-bottle_websocket]\nignore_missing_imports = True\n\n[mypy-gevent]\nignore_missing_imports = True\n\n[mypy-gevent.threading]\nignore_missing_imports = True\n\n[mypy-geventwebsocket.websocket]\nignore_missing_imports = True\n\n[mypy-bottle]\nignore_missing_imports = True\n\n[mypy-bottle.ext]\nignore_missing_imports = True\n\n[mypy-bottle.ext.websocket]\nignore_missing_imports = True\n\n[mypy-PyInstaller]\nignore_missing_imports = True\n\n[mypy-PyInstaller.__main__]\nignore_missing_imports = True\n"
  },
  {
    "path": "requirements-meta.txt",
    "content": "tox>=3.15.2,<4.0.0\ntox-pyenv==1.1.0\ntox-gh-actions==2.0.0\nvirtualenv>=16.7.10\nsetuptools\n"
  },
  {
    "path": "requirements-test.txt",
    "content": ".[jinja2]\n\npsutil>=5.0.0,<6.0.0\npytest>=7.0.0,<8.0.0\npytest-timeout>=2.0.0,<3.0.0\nselenium>=4.0.0,<5.0.0\nwebdriver_manager>=4.0.0,<5.0.0\nmypy>=1.0.0,<2.0.0\npyinstaller\ntypes-setuptools\nimportlib_resources>=1.3\n"
  },
  {
    "path": "requirements.txt",
    "content": "bottle<1.0.0\nbottle-websocket<1.0.0\ngevent\ngevent-websocket<1.0.0\ngreenlet>=1.0.0,<2.0.0\npyparsing>=3.0.0,<4.0.0\ntyping-extensions>=4.3.0\nimportlib_resources>=1.3\n"
  },
  {
    "path": "setup.py",
    "content": "from io import open\nfrom setuptools import setup\n\nwith open('README.md') as read_me:\n    long_description = read_me.read()\n\nsetup(\n    name='Eel',\n    version='0.18.2',\n    author='Python Eel Organisation',\n    author_email='python-eel@protonmail.com',\n    url='https://github.com/python-eel/Eel',\n    packages=['eel'],\n    package_data={\n        'eel': ['eel.js', 'py.typed'],\n    },\n    install_requires=['bottle', 'bottle-websocket', 'future', 'pyparsing', 'typing_extensions', 'importlib_resources'],\n    extras_require={\n        \"jinja2\": ['jinja2>=2.10']\n    },\n    python_requires='>=3.7',\n    description='For little HTML GUI applications, with easy Python/JS interop',\n    long_description=long_description,\n    long_description_content_type='text/markdown',\n    keywords=['gui', 'html', 'javascript', 'electron'],\n    classifiers=[\n        'Development Status :: 3 - Alpha',\n        'Natural Language :: English',\n        'Operating System :: MacOS',\n        'Operating System :: POSIX',\n        'Operating System :: Microsoft :: Windows :: Windows 10',\n        'Programming Language :: Python :: 3',\n        'Programming Language :: Python :: 3.7',\n        'Programming Language :: Python :: 3.8',\n        'Programming Language :: Python :: Implementation :: CPython',\n        'License :: OSI Approved :: MIT License',\n    ],\n)\n"
  },
  {
    "path": "tests/conftest.py",
    "content": "import os\nimport platform\nfrom unittest import mock\n\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service as ChromeService\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\n@pytest.fixture\ndef driver():\n    TEST_BROWSER = os.environ.get(\"TEST_BROWSER\", \"chrome\").lower()\n\n    if TEST_BROWSER == \"chrome\":\n        options = webdriver.ChromeOptions()\n        options.add_argument('--headless=new')\n        options.set_capability(\"goog:loggingPrefs\", {\"browser\": \"ALL\"})\n\n        if platform.system() == \"Windows\":\n            options.binary_location = \"C:/Program Files/Google/Chrome/Application/chrome.exe\"\n\n        driver = webdriver.Chrome(\n            service=ChromeService(ChromeDriverManager().install()),\n            options=options,\n        )\n\n    # Firefox doesn't currently supported pulling JavaScript console logs, which we currently scan to affirm that\n    # JS/Python can communicate in some places. So for now, we can't really use firefox/geckodriver during testing.\n    # This may be added in the future: https://github.com/mozilla/geckodriver/issues/284\n\n    # elif TEST_BROWSER == \"firefox\":\n    #     options = webdriver.FirefoxOptions()\n    #     options.headless = True\n    #     capabilities = DesiredCapabilities.FIREFOX\n    #     capabilities['loggingPrefs'] = {\"browser\": \"ALL\"}\n    #\n    #     driver = webdriver.Firefox(options=options, capabilities=capabilities, service_log_path=os.path.devnull)\n\n    else:\n        raise ValueError(f\"Unsupported browser for testing: {TEST_BROWSER}\")\n\n    with mock.patch(\"eel.browsers.open\"):\n        yield driver\n"
  },
  {
    "path": "tests/data/init_test/App.tsx",
    "content": "import React, { Component } from 'react';\nimport logo from './logo.svg';\nimport './App.css';\n\n// Point Eel web socket to the instance\nexport const eel = window.eel\neel.set_host( 'ws://localhost:8080' )\n\n// Expose the `sayHelloJS` function to Python as `say_hello_js`\nfunction sayHelloJS( x: any ) {\n  console.log( 'Hello from ' + x )\n}\n// WARN: must use window.eel to keep parse-able eel.expose{...}\nwindow.eel.expose( sayHelloJS, 'say_hello_js' )\n\n// Test anonymous function when minimized. See https://github.com/samuelhwilliams/Eel/issues/363\nfunction show_log(msg:string) {\n  console.log(msg)\n}\nwindow.eel.expose(show_log, 'show_log')\n\n// Test calling sayHelloJS, then call the corresponding Python function\nsayHelloJS( 'Javascript World!' )\neel.say_hello_py( 'Javascript World!' )\n\n// Set the default path. Would be a text input, but this is a basic example after all\nconst defPath = '~'\n\ninterface IAppState {\n  message: string\n  path: string\n}\n\nexport class App extends Component<{}, {}> {\n  public state: IAppState = {\n    message: `Click button to choose a random file from the user's system`,\n    path: defPath,\n  }\n\n  public pickFile = () => {\n    eel.pick_file(defPath)(( message: string ) => this.setState( { message } ) )\n  }\n\n  public render() {\n    eel.expand_user(defPath)(( path: string ) => this.setState( { path } ) )\n    return (\n      <div className=\"App\">\n        <header className=\"App-header\">\n          <img src={logo} className=\"App-logo\" alt=\"logo\" />\n          <p>{this.state.message}</p>\n          <button className='App-button' onClick={this.pickFile}>Pick Random File From `{this.state.path}`</button>\n        </header>\n      </div>\n    );\n  }\n}\n\nexport default App;\n"
  },
  {
    "path": "tests/data/init_test/hello.html",
    "content": "{% extends 'base.html' %} \n{% block title %}Hello, World!{% endblock %}\n{% block head_scripts %}        \n    eel.expose(say_hello_js);               // Expose this function to Python\n        function say_hello_js(x) {\n        console.log(\"Hello from \" + x);\n    }\n\n    eel.expose(js_random);\n    function js_random() {\n        return Math.random();\n    }\n\n    function print_num(n) {\n        console.log('Got this from Python: ' + n);\n    }\n\n    eel.py_random()(print_num);\n        \n    say_hello_js(\"Javascript World!\");\n    eel.say_hello_py(\"Javascript World!\");  // Call a Python function\n{% endblock %}\n{% block content %}\n    Hello, World!\n    <br />\n    <a href=\"page2.html\">Page 2</a>\n{% endblock %}\n"
  },
  {
    "path": "tests/data/init_test/minified.js",
    "content": "(window.webpackJsonp=window.webpackJsonp||[]).push([[0],{15:function(e,t,o){},16:function(e,t,o){},17:function(e,t,o){\"use strict\";o.r(t);var n=o(0),a=o.n(n),s=o(2),c=o.n(s),r=(o(15),o(3)),i=o(4),l=o(7),p=o(5),u=o(8),m=o(6),h=o.n(m),d=(o(16),window.eel);function w(e){console.log(\"Hello from \"+e)}d.set_host(\"ws://localhost:8081\"),window.eel.expose(w,\"say_hello_js\"),window.eel.expose(function(e){console.log(e)},\"show_log_alt\"),window.eel.expose((function show_log(e) {console.log(e)}), \"show_log\"),w(\"Javascript World!\"),d.say_hello_py(\"Javascript World!\");var f=\"~\",g=function(e){function t(){var e,o;Object(r.a)(this,t);for(var n=arguments.length,a=new Array(n),s=0;s<n;s++)a[s]=arguments[s];return(o=Object(l.a)(this,(e=Object(p.a)(t)).call.apply(e,[this].concat(a)))).state={message:\"Click button to choose a random file from the user's system\",path:f},o.pickFile=function(){d.pick_file(f)(function(e){return o.setState({message:e})})},o}return Object(u.a)(t,e),Object(i.a)(t,[{key:\"render\",value:function(){var e=this;return d.expand_user(f)(function(t){return e.setState({path:t})}),a.a.createElement(\"div\",{className:\"App\"},a.a.createElement(\"header\",{className:\"App-header\"},a.a.createElement(\"img\",{src:h.a,className:\"App-logo\",alt:\"logo\"}),a.a.createElement(\"p\",null,this.state.message),a.a.createElement(\"button\",{className:\"App-button\",onClick:this.pickFile},\"Pick Random File From `\",this.state.path,\"`\")))}}]),t}(n.Component);Boolean(\"localhost\"===window.location.hostname||\"[::1]\"===window.location.hostname||window.location.hostname.match(/^127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/));c.a.render(a.a.createElement(g,null),document.getElementById(\"root\")),\"serviceWorker\"in navigator&&navigator.serviceWorker.ready.then(function(e){e.unregister()})},6:function(e,t,o){e.exports=o.p+\"static/media/logo.5d5d9eef.svg\"},9:function(e,t,o){e.exports=o(17)}},[[9,1,2]]]);\n//# sourceMappingURL=main.f500e2b1.chunk.js.map\n// Example minified code from https://github.com/samuelhwilliams/Eel/issues/363#issuecomment-663506276\n"
  },
  {
    "path": "tests/data/init_test/sample.html",
    "content": "<!-- Below is from: https://github.com/samuelhwilliams/Eel/blob/master/examples/05%20-%20input/web/main.html  -->\n\n<!DOCTYPE html>\n<html>\n<head>\n    <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css\" integrity=\"sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy\" crossorigin=\"anonymous\">\n    <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script>\n    <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->\n    <script type=\"text/javascript\" src=\"/eel.js\"></script>\n    <script type=\"text/javascript\">\n    $(function(){\n\n                eel.expose(say_hello_js);               // Expose this function to Python\n                function say_hello_js(x) {\n                console.log(\"Hello from \" + x);\n                }\n                say_hello_js(\"Javascript World!\");\n                eel.handleinput(\"connected!\");  // Call a Python function\n\n                $(\"#btn\").click(function(){\n                    eel.handleinput($(\"#inp\").val());\n                    $('#inp').val('');\n                });\n    });\n    </script>\n</head>\n\n<body>\n    <h1>Input Example: Enter a value and check python console</h1>\n    <div>\n        <input type='text' id='inp' placeholder='Write anything'>\n        <input type='button' id='btn' class='btn btn-primary' value='Submit'>\n    </div>\n</body>\n</html>\n"
  },
  {
    "path": "tests/integration/test_examples.py",
    "content": "import os\nimport time\nfrom tempfile import TemporaryDirectory, NamedTemporaryFile\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom tests.utils import get_eel_server, get_console_logs\n\n\ndef test_01_hello_world(driver):\n    with get_eel_server('examples/01 - hello_world/hello.py', 'hello.html') as eel_url:\n        driver.get(eel_url)\n        assert driver.title == \"Hello, World!\"\n\n        console_logs = get_console_logs(driver, minimum_logs=2)\n        assert \"Hello from Javascript World!\" in console_logs[0]['message']\n        assert \"Hello from Python World!\" in console_logs[1]['message']\n\n\ndef test_02_callbacks(driver):\n    with get_eel_server('examples/02 - callbacks/callbacks.py', 'callbacks.html') as eel_url:\n        driver.get(eel_url)\n        assert driver.title == \"Callbacks Demo\"\n\n        console_logs = get_console_logs(driver, minimum_logs=1)\n        assert \"Got this from Python:\" in console_logs[0]['message']\n        assert \"callbacks.html\" in console_logs[0]['message']\n\n\ndef test_03_callbacks(driver):\n    with get_eel_server('examples/03 - sync_callbacks/sync_callbacks.py', 'sync_callbacks.html') as eel_url:\n        driver.get(eel_url)\n        assert driver.title == \"Synchronous callbacks\"\n\n        console_logs = get_console_logs(driver, minimum_logs=1)\n        assert \"Got this from Python:\" in console_logs[0]['message']\n        assert \"callbacks.html\" in console_logs[0]['message']\n\n\ndef test_04_file_access(driver: webdriver.Remote):\n    with get_eel_server('examples/04 - file_access/file_access.py', 'file_access.html') as eel_url:\n        driver.get(eel_url)\n        assert driver.title == \"Eel Demo\"\n\n        with TemporaryDirectory() as temp_dir, NamedTemporaryFile(dir=temp_dir) as temp_file:\n            driver.find_element(value='input-box').clear()\n            driver.find_element(value='input-box').send_keys(temp_dir)\n            time.sleep(0.5)\n            driver.find_element(By.CSS_SELECTOR, 'button').click()\n\n            assert driver.find_element(value='file-name').text == os.path.basename(temp_file.name)\n\n\ndef test_06_jinja_templates(driver: webdriver.Remote):\n    with get_eel_server('examples/06 - jinja_templates/hello.py', 'templates/hello.html') as eel_url:\n        driver.get(eel_url)\n        assert driver.title == \"Hello, World!\"\n\n        driver.find_element(By.CSS_SELECTOR, 'a').click()\n        WebDriverWait(driver, 2.0).until(expected_conditions.presence_of_element_located((By.XPATH, '//h1[text()=\"This is page 2\"]')))\n\n\ndef test_10_custom_app(driver: webdriver.Remote):\n    # test default eel routes are working\n    with get_eel_server('examples/10 - custom_app_routes/custom_app.py', 'index.html') as eel_url:\n        driver.get(eel_url)\n        # we really need to test if the page 404s, but selenium has no support for status codes\n        # so we just test if we can get our page title\n        assert driver.title == 'Hello, World!'\n\n    # test custom routes are working\n    with get_eel_server('examples/10 - custom_app_routes/custom_app.py', 'custom') as eel_url:\n        driver.get(eel_url)\n        assert 'Hello, World!' in driver.page_source\n"
  },
  {
    "path": "tests/unit/test_eel.py",
    "content": "import eel\nimport pytest\nfrom tests.utils import TEST_DATA_DIR\n\n# Directory for testing eel.__init__\nINIT_DIR = TEST_DATA_DIR / 'init_test'\n\n\n@pytest.mark.parametrize('js_code, expected_matches', [\n    ('eel.expose(w,\"say_hello_js\")', ['say_hello_js']),\n    ('eel.expose(function(e){console.log(e)},\"show_log_alt\")', ['show_log_alt']),\n    (' \\t\\nwindow.eel.expose((function show_log(e) {console.log(e)}), \"show_log\")\\n', ['show_log']),\n    ((INIT_DIR / 'minified.js').read_text(), ['say_hello_js', 'show_log_alt', 'show_log']),\n    ((INIT_DIR / 'sample.html').read_text(), ['say_hello_js']),\n    ((INIT_DIR / 'App.tsx').read_text(), ['say_hello_js', 'show_log']),\n    ((INIT_DIR / 'hello.html').read_text(), ['say_hello_js', 'js_random']),\n])\ndef test_exposed_js_functions(js_code, expected_matches):\n    \"\"\"Test the PyParsing PEG against several specific test cases.\"\"\"\n    matches = eel.EXPOSED_JS_FUNCTIONS.parseString(js_code).asList()\n    assert matches == expected_matches, f'Expected {expected_matches} (found: {matches}) in: {js_code}'\n\n\ndef test_init():\n    \"\"\"Test eel.init() against a test directory and ensure that all JS functions are in the global _js_functions.\"\"\"\n    eel.init(path=INIT_DIR)\n    result = eel._js_functions.sort()\n    functions = ['show_log', 'js_random', 'show_log_alt', 'say_hello_js'].sort()\n    assert result == functions, f'Expected {functions} (found: {result}) in {INIT_DIR}'\n"
  },
  {
    "path": "tests/utils.py",
    "content": "import contextlib\nimport os\nimport sys\nimport platform\nimport subprocess\nimport tempfile\nimport time\nfrom pathlib import Path\n\nimport psutil\n\n# Path to the test data folder.\nTEST_DATA_DIR = Path(__file__).parent / \"data\"\n\n\ndef get_process_listening_port(proc):\n    conn = None\n    if platform.system() == \"Windows\":\n        current_process = psutil.Process(proc.pid)\n        children = []\n        while children == []:\n            time.sleep(0.01)\n            children = current_process.children(recursive=True)\n            if (3, 6) <= sys.version_info < (3, 7):\n                children = [current_process]\n        for child in children:\n            while child.connections() == [] and not any(conn.status == \"LISTEN\" for conn in child.connections()):\n                time.sleep(0.01)\n\n            conn = next(filter(lambda conn: conn.status == \"LISTEN\", child.connections()))\n    else:\n        psutil_proc = psutil.Process(proc.pid)\n        while not any(conn.status == \"LISTEN\" for conn in psutil_proc.connections()):\n            time.sleep(0.01)\n\n        conn = next(filter(lambda conn: conn.status == \"LISTEN\", psutil_proc.connections()))\n    return conn.laddr.port\n\n\n@contextlib.contextmanager\ndef get_eel_server(example_py, start_html):\n    \"\"\"Run an Eel example with the mode/port overridden so that no browser is launched and a random port is assigned\"\"\"\n    test = None\n\n    try:\n        with tempfile.NamedTemporaryFile(mode='w', dir=os.path.dirname(example_py), delete=False) as test:\n            # We want to run the examples unmodified to keep the test as realistic as possible, but all of the examples\n            # want to launch browsers, which won't be supported in CI. The below script will configure eel to open on\n            # a random port and not open a browser, before importing the Python example file - which will then\n            # do the rest of the set up and start the eel server. This is definitely hacky, and means we can't\n            # test mode/port settings for examples ... but this is OK for now.\n            test.write(f\"\"\"\nimport eel\n\neel._start_args['mode'] = None\neel._start_args['port'] = 0\n\nimport {os.path.splitext(os.path.basename(example_py))[0]}\n\"\"\")\n        proc = subprocess.Popen(\n                [sys.executable, test.name],\n                cwd=os.path.dirname(example_py),\n            )\n        eel_port = get_process_listening_port(proc)\n\n        yield f\"http://localhost:{eel_port}/{start_html}\"\n\n        proc.terminate()\n\n    finally:\n        if test:\n            try:\n                os.unlink(test.name)\n            except FileNotFoundError:\n                pass\n\n\ndef get_console_logs(driver, minimum_logs=0):\n    console_logs = driver.get_log('browser')\n\n    while len(console_logs) < minimum_logs:\n        console_logs += driver.get_log('browser')\n        time.sleep(0.1)\n\n    return console_logs\n"
  },
  {
    "path": "tox.ini",
    "content": "[tox]\nenvlist = typecheck,py{37,38,39,310,311,312,313}\n\n[pytest]\ntimeout = 30\n\n[gh-actions]\npython =\n    3.7: py37\n    3.8: py38\n    3.9: py39\n    3.10: py310\n    3.11: py311\n    3.12: py312\n    3.13: py313\n\n\n[testenv]\ndescription = run py.test tests\ndeps = -r requirements-test.txt\ncommands =\n  # this ugly hack is here because:\n  # https://github.com/tox-dev/tox/issues/149\n  pip install -q -r '{toxinidir}'/requirements-test.txt\n  '{envpython}' -m pytest {posargs}\n\n[testenv:typecheck]\ndescription = run type checks\ndeps =  -r requirements-test.txt\ncommands =\n  mypy --strict {posargs:eel}\n"
  }
]